diff --git a/Build/build-functions.psm1 b/Build/build-functions.psm1 index bf777a7b73..9ac597c7ce 100644 --- a/Build/build-functions.psm1 +++ b/Build/build-functions.psm1 @@ -63,7 +63,8 @@ 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.Tests\UnitsNet.Serialization.JsonNet.Tests.csproj", + "UnitsNet.Serialization.SystemTextJson.Tests\UnitsNet.Serialization.SystemTextJson.csproj" ) # Parent dir must exist before xunit tries to write files to it @@ -102,6 +103,7 @@ function Start-PackNugets([boolean] $IncludeNanoFramework = $false) { $projectPaths = @( "UnitsNet\UnitsNet.csproj", "UnitsNet.Serialization.JsonNet\UnitsNet.Serialization.JsonNet.csproj", + "UnitsNet.Serialization.SystemTextJson\UnitsNet.Serialization.SystemTextJson.csproj", "UnitsNet.NumberExtensions\UnitsNet.NumberExtensions.csproj" ) diff --git a/CodeGen/CodeGen.csproj b/CodeGen/CodeGen.csproj index b33eb9dfc1..1f4e0f9007 100644 --- a/CodeGen/CodeGen.csproj +++ b/CodeGen/CodeGen.csproj @@ -1,4 +1,4 @@ - + Exe @@ -10,6 +10,7 @@ + diff --git a/CodeGen/Generators/NanoFrameworkGen/NuspecGenerator.cs b/CodeGen/Generators/NanoFrameworkGen/NuspecGenerator.cs index 1998e15872..b252824880 100644 --- a/CodeGen/Generators/NanoFrameworkGen/NuspecGenerator.cs +++ b/CodeGen/Generators/NanoFrameworkGen/NuspecGenerator.cs @@ -1,4 +1,4 @@ -using System; +using System; using CodeGen.JsonTypes; namespace CodeGen.Generators.NanoFrameworkGen diff --git a/CodeGen/Generators/UnitsNetGen/NumberExtensionsGenerator.cs b/CodeGen/Generators/UnitsNetGen/NumberExtensionsGenerator.cs index 4765e49d9e..2965ebccbb 100644 --- a/CodeGen/Generators/UnitsNetGen/NumberExtensionsGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/NumberExtensionsGenerator.cs @@ -40,7 +40,7 @@ public static class NumberTo{_quantityName}Extensions continue; Writer.WL(2, $@" -/// "); +/// "); // Include obsolete text from the quantity per extension method, to make it visible when the class is not explicitly referenced in code. Writer.WLIfText(2, GetObsoleteAttributeOrNull(unit.ObsoleteText ?? _quantity.ObsoleteText)); @@ -49,10 +49,10 @@ public static class NumberTo{_quantityName}Extensions where T : notnull #if NET7_0_OR_GREATER , INumber - => {_quantityName}.From{unit.PluralName}(double.CreateChecked(value)); + => {_quantityName}.From{unit.PluralName}(QuantityValue.CreateChecked(value)); #else , IConvertible - => {_quantityName}.From{unit.PluralName}(value.ToDouble(null)); + => {_quantityName}.From{unit.PluralName}(value.ToQuantityValue()); #endif "); } diff --git a/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs b/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs index 6c5cf268d0..c7dc941d61 100644 --- a/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/QuantityGenerator.cs @@ -4,7 +4,10 @@ using System; using System.Linq; using CodeGen.Helpers; +using CodeGen.Helpers.ExpressionAnalyzer; +using CodeGen.Helpers.ExpressionAnalyzer.Expressions; using CodeGen.JsonTypes; +using Fractions; namespace CodeGen.Generators.UnitsNetGen { @@ -34,13 +37,10 @@ public string Generate() { Writer.WL(GeneratedFileHeader); Writer.WL(@" - using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -62,7 +62,8 @@ namespace UnitsNet Writer.WLIfText(1, GetObsoleteAttributeOrNull(_quantity)); Writer.WL(@$" [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct {_quantity.Name} :"); GenerateInterfaceExtensions(); @@ -71,13 +72,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = ""Value"", Order = 1)] - private readonly double _value; + [DataMember(Name = ""Value"", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = ""Unit"", Order = 2)] + [DataMember(Name = ""Unit"", Order = 2, EmitDefaultValue = false)] private readonly {_unitEnumName}? _unit; "); GenerateQuantityInfo(); @@ -141,7 +142,7 @@ private void GenerateInterfaceExtensions() default: continue; } - Writer.WL($"<{relation.LeftQuantity.Name}, {relation.RightQuantity.Name}, {relation.ResultQuantity.Name}>,"); + Writer.WL($"<{relation.LeftQuantity.Name}, {relation.RightQuantity.Name}, {relation.ResultQuantity.Name.Replace("double", "QuantityValue")}>,"); } } @@ -250,8 +251,31 @@ public sealed class {quantityInfoClassName}: QuantityInfo<{_quantity.Name}, {_un }.Where(str => str != null))})"; } - Writer.WL($@" + if (unit.SingularName == _quantity.BaseUnit) + { + Writer.WL($@" yield return new ({_unitEnumName}.{unit.SingularName}, ""{unit.SingularName}"", ""{unit.PluralName}"", {baseUnitsFormat});"); + } + else + { + // note: omitting the extra parameter (where possible) saves us 36 KB + CompositeExpression expressionFromBaseToUnit = ExpressionEvaluator.Evaluate(unit.FromBaseToUnitFunc, "{x}"); + if (expressionFromBaseToUnit.Terms.Count == 1 && expressionFromBaseToUnit.Degree == Fraction.One) + { + Writer.WL($@" + yield return new ({_unitEnumName}.{unit.SingularName}, ""{unit.SingularName}"", ""{unit.PluralName}"", {baseUnitsFormat}, + {expressionFromBaseToUnit.GetConversionExpressionFormat()} + );"); + } + else + { + Writer.WL($@" + yield return new ({_unitEnumName}.{unit.SingularName}, ""{unit.SingularName}"", ""{unit.PluralName}"", {baseUnitsFormat}, + {expressionFromBaseToUnit.GetConversionExpressionFormat()}, + {unit.GetUnitToBaseConversionExpressionFormat()} + );"); + } + } } Writer.WL($@" @@ -266,9 +290,7 @@ private void GenerateStaticConstructor() static {_quantity.Name}() {{"); Writer.WL($@" - Info = {_quantity.Name}Info.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo({_quantity.Name}Info.CreateDefault); }} "); } @@ -281,7 +303,7 @@ private void GenerateInstanceConstructors() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public {_quantity.Name}(double value, {_unitEnumName} unit) + public {_quantity.Name}(QuantityValue value, {_unitEnumName} unit) {{"); Writer.WL(@" _value = value;"); @@ -300,7 +322,7 @@ private void GenerateInstanceConstructors() /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public {_quantity.Name}(double value, UnitSystem unitSystem) + public {_quantity.Name}(QuantityValue value, UnitSystem unitSystem) {{ _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -317,7 +339,8 @@ private void GenerateStaticProperties() /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions {{ get; }} + [Obsolete(""Replaced by UnitConverter.Default"")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo<{_quantity.Name}, {_unitEnumName}> Info {{ get; }} @@ -347,7 +370,7 @@ private void GenerateStaticProperties() { Writer.WL($@" /// - public static double LogarithmicScalingFactor {{get;}} = {10 * _quantity.LogarithmicScalingFactor}; + public static QuantityValue LogarithmicScalingFactor {{get;}} = {10 * _quantity.LogarithmicScalingFactor}; "); } @@ -361,10 +384,8 @@ private void GenerateProperties() Writer.WL($@" #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public {_unitEnumName} Unit => _unit.GetValueOrDefault(BaseUnit); @@ -400,7 +421,7 @@ private void GenerateProperties() { Writer.WL($@" #if NETSTANDARD2_0 - double ILogarithmicQuantity<{_quantity.Name}>.LogarithmicScalingFactor => LogarithmicScalingFactor; + QuantityValue ILogarithmicQuantity<{_quantity.Name}>.LogarithmicScalingFactor => LogarithmicScalingFactor; #endif "); } @@ -423,11 +444,11 @@ private void GenerateConversionProperties() Writer.WL($@" /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// "); Writer.WLIfText(2, GetObsoleteAttributeOrNull(unit)); Writer.WL($@" - public double {unit.PluralName} => As({_unitEnumName}.{unit.SingularName}); + public QuantityValue {unit.PluralName} => this.As({_unitEnumName}.{unit.SingularName}); "); } @@ -443,41 +464,6 @@ private void GenerateStaticMethods() #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - {{ - // Register in unit converter: {_unitEnumName} -> BaseUnit"); - - foreach (Unit unit in _quantity.Units) - { - if (unit.SingularName == _quantity.BaseUnit) continue; - - Writer.WL($@" - unitConverter.SetConversionFunction<{_quantity.Name}>({_unitEnumName}.{unit.SingularName}, {_unitEnumName}.{_quantity.BaseUnit}, quantity => quantity.ToUnit({_unitEnumName}.{_quantity.BaseUnit}));"); - } - - Writer.WL(); - Writer.WL($@" - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction<{_quantity.Name}>({_unitEnumName}.{_quantity.BaseUnit}, {_unitEnumName}.{_quantity.BaseUnit}, quantity => quantity); - - // Register in unit converter: BaseUnit -> {_unitEnumName}"); - - foreach (Unit unit in _quantity.Units) - { - if (unit.SingularName == _quantity.BaseUnit) continue; - - Writer.WL($@" - unitConverter.SetConversionFunction<{_quantity.Name}>({_unitEnumName}.{_quantity.BaseUnit}, {_unitEnumName}.{unit.SingularName}, quantity => quantity.ToUnit({_unitEnumName}.{unit.SingularName}));"); - } - - Writer.WL($@" - }} - /// /// Get unit abbreviation string. /// @@ -518,7 +504,7 @@ private void GenerateStaticFactoryMethods() /// "); Writer.WLIfText(2, GetObsoleteAttributeOrNull(unit)); Writer.WL($@" - public static {_quantity.Name} From{unit.PluralName}(double value) + public static {_quantity.Name} From{unit.PluralName}(QuantityValue value) {{ return new {_quantity.Name}(value, {_unitEnumName}.{unit.SingularName}); }} @@ -532,7 +518,7 @@ private void GenerateStaticFactoryMethods() /// Value to convert from. /// Unit to convert from. /// {_quantity.Name} unit value. - public static {_quantity.Name} From(double value, {_unitEnumName} fromUnit) + public static {_quantity.Name} From(QuantityValue value, {_unitEnumName} fromUnit) {{ return new {_quantity.Name}(value, fromUnit); }} @@ -598,10 +584,7 @@ private void GenerateStaticParseMethods() /// Format to use when parsing number and unit. Defaults to if null. public static {_quantity.Name} Parse(string str, IFormatProvider? provider) {{ - return UnitsNetSetup.Default.QuantityParser.Parse<{_quantity.Name}, {_unitEnumName}>( - str, - provider, - From); + return QuantityParser.Default.Parse<{_quantity.Name}, {_unitEnumName}>(str, provider, From); }} /// @@ -629,11 +612,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out {_quantity.Name} /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out {_quantity.Name} result) {{ - return UnitsNetSetup.Default.QuantityParser.TryParse<{_quantity.Name}, {_unitEnumName}>( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse<{_quantity.Name}, {_unitEnumName}>(str, provider, From, out result); }} /// @@ -654,7 +633,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? pro /// Parse a unit string. /// /// String to parse. Typically in the form: {{number}} {{unit}} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit(""m"", CultureInfo.GetCultureInfo(""en-US"")); /// @@ -665,7 +644,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? pro return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; }} - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out {_unitEnumName} unit) {{ return TryParseUnit(str, null, out unit); @@ -680,7 +659,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out {_unitEnumNa /// /// Length.TryParseUnit(""m"", CultureInfo.GetCultureInfo(""en-US"")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out {_unitEnumName} unit) {{ return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -718,35 +697,35 @@ private void GenerateArithmeticOperators() /// Get from adding two . public static {_quantity.Name} operator +({_quantity.Name} left, {_quantity.Name} right) {{ - return new {_quantity.Name}(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new {_quantity.Name}(left.Value + right.As(left.Unit), left.Unit); }} /// Get from subtracting two . public static {_quantity.Name} operator -({_quantity.Name} left, {_quantity.Name} right) {{ - return new {_quantity.Name}(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new {_quantity.Name}(left.Value - right.As(left.Unit), left.Unit); }} /// Get from multiplying value and . - public static {_quantity.Name} operator *(double left, {_quantity.Name} right) + public static {_quantity.Name} operator *(QuantityValue left, {_quantity.Name} right) {{ return new {_quantity.Name}(left * right.Value, right.Unit); }} /// Get from multiplying value and . - public static {_quantity.Name} operator *({_quantity.Name} left, double right) + public static {_quantity.Name} operator *({_quantity.Name} left, QuantityValue right) {{ return new {_quantity.Name}(left.Value * right, left.Unit); }} /// Get from dividing by value. - public static {_quantity.Name} operator /({_quantity.Name} left, double right) + public static {_quantity.Name} operator /({_quantity.Name} left, QuantityValue right) {{ return new {_quantity.Name}(left.Value / right, left.Unit); }} /// Get ratio value from dividing by . - public static double operator /({_quantity.Name} left, {_quantity.Name} right) + public static QuantityValue operator /({_quantity.Name} left, {_quantity.Name} right) {{ return left.{_baseUnit.PluralName} / right.{_baseUnit.PluralName}; }} @@ -764,53 +743,61 @@ private void GenerateLogarithmicArithmeticOperators() #region Logarithmic Arithmetic Operators /// Negate the value. - public static {_quantity.Name} operator -({_quantity.Name} right) + public static {_quantity.Name} operator -({_quantity.Name} quantity) {{ - return new {_quantity.Name}(-right.Value, right.Unit); + return new {_quantity.Name}(-quantity.Value, quantity.Unit); }} /// Get from logarithmic addition of two . + /// This operation involves a conversion of the values to linear space, which is not guaranteed to produce an exact value. + /// The final result is rounded to 15 significant digits. + /// public static {_quantity.Name} operator +({_quantity.Name} left, {_quantity.Name} right) {{ // 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.ToUnit(left.Unit).Value / {x})), left.Unit); + var leftUnit = left.Unit; + return new {_quantity.Name}(QuantityValueExtensions.AddWithLogScaling(left.Value, right.As(leftUnit), LogarithmicScalingFactor), leftUnit); }} /// Get from logarithmic subtraction of two . + /// This operation involves a conversion of the values to linear space, which is not guaranteed to produce an exact value. + /// The final result is rounded to 15 significant digits. + /// public static {_quantity.Name} operator -({_quantity.Name} left, {_quantity.Name} right) {{ // 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.ToUnit(left.Unit).Value / {x})), left.Unit); + var leftUnit = left.Unit; + return new {_quantity.Name}(QuantityValueExtensions.SubtractWithLogScaling(left.Value, right.As(leftUnit), LogarithmicScalingFactor), leftUnit); }} /// Get from logarithmic multiplication of value and . - public static {_quantity.Name} operator *(double left, {_quantity.Name} right) + public static {_quantity.Name} operator *(QuantityValue left, {_quantity.Name} right) {{ // Logarithmic multiplication = addition return new {_quantity.Name}(left + right.Value, right.Unit); }} /// Get from logarithmic multiplication of value and . - public static {_quantity.Name} operator *({_quantity.Name} left, double right) + public static {_quantity.Name} operator *({_quantity.Name} left, QuantityValue right) {{ // Logarithmic multiplication = addition return new {_quantity.Name}(left.Value + right, left.Unit); }} /// Get from logarithmic division of by value. - public static {_quantity.Name} operator /({_quantity.Name} left, double right) + public static {_quantity.Name} operator /({_quantity.Name} left, QuantityValue right) {{ // Logarithmic division = subtraction return new {_quantity.Name}(left.Value - right, left.Unit); }} /// Get ratio value from logarithmic division of by . - public static double operator /({_quantity.Name} left, {_quantity.Name} right) + public static QuantityValue operator /({_quantity.Name} left, {_quantity.Name} right) {{ // Logarithmic division = subtraction - return Convert.ToDouble(left.Value - right.ToUnit(left.Unit).Value); + return left.Value - right.As(left.Unit); }} #endregion @@ -837,46 +824,137 @@ private void GenerateRelationalOperators() /// The corresponding inverse quantity, . public {relation.RightQuantity.Name} Inverse() {{ - return {relation.RightQuantity.Name}.From{relation.RightUnit.PluralName}(1 / {relation.LeftUnit.PluralName}); + return UnitConverter.Default.ConvertTo(Value, Unit, {relation.RightQuantity.Name}.Info); + }} +"); + } + else + { + var leftParameterType = relation.LeftQuantity.Name; + var leftParameterName = leftParameterType.ToCamelCase(); + var leftConversionProperty = relation.LeftUnit.PluralName; + var rightParameterType = relation.RightQuantity.Name; + var rightParameterName = relation.RightQuantity.Name.ToCamelCase(); + var rightConversionProperty = relation.RightUnit.PluralName; + + if (leftParameterName == rightParameterName) + { + leftParameterName = "left"; + rightParameterName = "right"; + } + + var leftPart = $"{leftParameterName}.{leftConversionProperty}"; + var rightPart = $"{rightParameterName}.{rightConversionProperty}"; + + if (leftParameterName is "double") + { + leftParameterType = "QuantityValue"; + leftParameterName = leftPart = "value"; + } + + if (rightParameterName is "double") + { + rightParameterType = "QuantityValue"; + rightParameterName = rightPart = "value"; + } + + var expression = $"{leftPart} {relation.Operator} {rightPart}"; + + var resultType = relation.ResultQuantity.Name; + if (resultType is "double") + { + resultType = "QuantityValue"; + } + else + { + expression = $"{resultType}.From{relation.ResultUnit.PluralName}({expression})"; + } + + Writer.WL($@" + /// Get from {relation.Operator} . + public static {resultType} operator {relation.Operator}({leftParameterType} {leftParameterName}, {rightParameterType} {rightParameterName}) + {{ + return {expression}; + }} +"); + } + } + + Writer.WL($@" + + #endregion +"); + } + + /// + /// Generates operators that express relations between quantities as applied by . + /// + private void GenerateRelationalOperatorsWithFixedUnits() + { + if (!_quantity.Relations.Any()) return; + + Writer.WL($@" + #region Relational Operators +"); + + foreach (QuantityRelation relation in _quantity.Relations) + { + if (relation.Operator == "inverse") + { + Writer.WL($@" + /// Calculates the inverse of this quantity. + /// The corresponding inverse quantity, . + public {relation.RightQuantity.Name} Inverse() + {{ + return {relation.RightQuantity.Name}.From{relation.RightUnit.PluralName}(QuantityValue.Inverse({relation.LeftUnit.PluralName})); }} "); } else { - var leftParameter = relation.LeftQuantity.Name.ToCamelCase(); + var leftParameterType = relation.LeftQuantity.Name; + var leftParameterName = leftParameterType.ToCamelCase(); var leftConversionProperty = relation.LeftUnit.PluralName; - var rightParameter = relation.RightQuantity.Name.ToCamelCase(); + var rightParameterType = relation.RightQuantity.Name; + var rightParameterName = relation.RightQuantity.Name.ToCamelCase(); var rightConversionProperty = relation.RightUnit.PluralName; - if (leftParameter == rightParameter) + if (leftParameterName == rightParameterName) { - leftParameter = "left"; - rightParameter = "right"; + leftParameterName = "left"; + rightParameterName = "right"; } - var leftPart = $"{leftParameter}.{leftConversionProperty}"; - var rightPart = $"{rightParameter}.{rightConversionProperty}"; + var leftPart = $"{leftParameterName}.{leftConversionProperty}"; + var rightPart = $"{rightParameterName}.{rightConversionProperty}"; - if (leftParameter is "double") + if (leftParameterName is "double") { - leftParameter = leftPart = "value"; + leftParameterType = "QuantityValue"; + leftParameterName = leftPart = "value"; } - if (rightParameter is "double") + if (rightParameterName is "double") { - rightParameter = rightPart = "value"; + rightParameterType = "QuantityValue"; + rightParameterName = rightPart = "value"; } var expression = $"{leftPart} {relation.Operator} {rightPart}"; - if (relation.ResultQuantity.Name is not "double") + var resultType = relation.ResultQuantity.Name; + if (resultType is "double") + { + resultType = "QuantityValue"; + } + else { - expression = $"{relation.ResultQuantity.Name}.From{relation.ResultUnit.PluralName}({expression})"; + expression = $"{resultType}.From{relation.ResultUnit.PluralName}({expression})"; } Writer.WL($@" - /// Get from {relation.Operator} . - public static {relation.ResultQuantity.Name} operator {relation.Operator}({relation.LeftQuantity.Name} {leftParameter}, {relation.RightQuantity.Name} {rightParameter}) + /// Get from {relation.Operator} . + public static {resultType} operator {relation.Operator}({leftParameterType} {leftParameterName}, {rightParameterType} {rightParameterName}) {{ return {expression}; }} @@ -898,97 +976,82 @@ private void GenerateEqualityAndComparison() /// Returns true if less or equal to. public static bool operator <=({_quantity.Name} left, {_quantity.Name} right) {{ - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); }} /// Returns true if greater than or equal to. public static bool operator >=({_quantity.Name} left, {_quantity.Name} right) {{ - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); }} /// Returns true if less than. public static bool operator <({_quantity.Name} left, {_quantity.Name} right) {{ - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); }} /// Returns true if greater than. public static bool operator >({_quantity.Name} left, {_quantity.Name} right) {{ - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); }} - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete(""For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals({_quantity.Name} other, {_quantity.Name} tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units."")] + /// Indicates strict equality of two quantities. public static bool operator ==({_quantity.Name} left, {_quantity.Name} right) {{ return left.Equals(right); }} - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete(""For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals({_quantity.Name} other, {_quantity.Name} tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units."")] + /// Indicates strict inequality of two quantities. public static bool operator !=({_quantity.Name} left, {_quantity.Name} right) {{ return !(left == right); }} /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete(""Use Equals({_quantity.Name} other, {_quantity.Name} tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units."")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) {{ - if (obj is null || !(obj is {_quantity.Name} otherQuantity)) + if (obj is not {_quantity.Name} otherQuantity) return false; return Equals(otherQuantity); }} /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete(""Use Equals({_quantity.Name} other, {_quantity.Name} tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units."")] + /// Indicates strict equality of two quantities. public bool Equals({_quantity.Name} other) {{ - return new {{ Value, Unit }}.Equals(new {{ other.Value, other.Unit }}); + return _value.Equals(other.As(this.Unit)); }} - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current {_quantity.Name}. public override int GetHashCode() {{ - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof({_quantity.Name}), this.As(BaseUnit)); }} - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) {{ - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is {_quantity.Name} otherQuantity)) throw new ArgumentException(""Expected type {_quantity.Name}."", nameof(obj)); + if (obj is not {_quantity.Name} otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException<{_quantity.Name}>(obj, nameof(obj)); return CompareTo(otherQuantity); }} - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1000,7 +1063,7 @@ public int CompareTo(object? obj) /// public int CompareTo({_quantity.Name} other) {{ - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); }} #endregion @@ -1010,174 +1073,19 @@ public int CompareTo({_quantity.Name} other) private void GenerateConversionMethods() { Writer.WL($@" - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As({_unitEnumName} unit) - {{ - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - }} -"); - - Writer.WL( $@" - - /// - public double As(UnitKey unitKey) - {{ - return As(unitKey.ToUnit<{_unitEnumName}>()); - }} -"); - - Writer.WL( $@" + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - public double As(UnitSystem unitSystem) - {{ - return As(Info.GetDefaultUnit(unitSystem)); - }} -"); - - Writer.WL($@" - /// - /// Converts this {_quantity.Name} to another {_quantity.Name} with the unit representation . - /// - /// The unit to convert to. - /// A {_quantity.Name} with the specified unit. - public {_quantity.Name} ToUnit({_unitEnumName} unit) - {{ - return ToUnit(unit, DefaultConversionFunctions); - }} - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A {_quantity.Name} with the specified unit. - public {_quantity.Name} ToUnit({_unitEnumName} unit, UnitConverter unitConverter) - {{ - if (TryToUnit(unit, out var converted)) - {{ - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - }} - else if (unitConverter.TryGetConversionFunction((typeof({_quantity.Name}), Unit, typeof({_quantity.Name}), unit), out var conversionFunction)) - {{ - // See if the unit converter has an extensibility conversion registered. - return ({_quantity.Name})conversionFunction(this); - }} - else if (Unit != BaseUnit) - {{ - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - }} - else - {{ - // No possible conversion - throw new UnitNotFoundException($""Can't convert {{Unit}} to {{unit}}.""); - }} - }} - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit({_unitEnumName} unit, [NotNullWhen(true)] out {_quantity.Name}? converted) - {{ - if (Unit == unit) - {{ - converted = this; - return true; - }} - - {_quantity.Name}? convertedOrNull = (Unit, unit) switch - {{ - // {_unitEnumName} -> BaseUnit"); - - foreach (Unit unit in _quantity.Units) - { - if (unit.SingularName == _quantity.BaseUnit) continue; - - var func = unit.FromUnitToBaseFunc.Replace("{x}", "_value"); - Writer.WL($@" - ({_unitEnumName}.{unit.SingularName}, {_unitEnumName}.{_quantity.BaseUnit}) => new {_quantity.Name}({func}, {_unitEnumName}.{_quantity.BaseUnit}),"); - } - - Writer.WL(); - Writer.WL($@" - - // BaseUnit -> {_unitEnumName}"); - foreach(Unit unit in _quantity.Units) - { - if (unit.SingularName == _quantity.BaseUnit) continue; - - var func = unit.FromBaseToUnitFunc.Replace("{x}", "_value"); - Writer.WL($@" - ({_unitEnumName}.{_quantity.BaseUnit}, {_unitEnumName}.{unit.SingularName}) => new {_quantity.Name}({func}, {_unitEnumName}.{unit.SingularName}),"); - } - - Writer.WL(); - Writer.WL($@" - _ => null - }}; - - if (convertedOrNull is null) - {{ - converted = default; - return false; - }} - - converted = convertedOrNull.Value; - return true; - }} -"); - Writer.WL($@" - /// - public {_quantity.Name} ToUnit(UnitSystem unitSystem) - {{ - return ToUnit(Info.GetDefaultUnit(unitSystem)); - }} -"); - - Writer.WL($@" - #region Explicit implementations - - double IQuantity.As(Enum unit) - {{ - if (unit is not {_unitEnumName} typedUnit) - throw new ArgumentException($""The given unit is of type {{unit.GetType()}}. Only {{typeof({_unitEnumName})}} is supported."", nameof(unit)); - - return As(typedUnit); - }} - - /// - IQuantity IQuantity.ToUnit(Enum unit) - {{ - 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(typedUnit, DefaultConversionFunctions); - }} +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity<{_unitEnumName}> IQuantity<{_unitEnumName}>.ToUnit({_unitEnumName} unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity<{_unitEnumName}> IQuantity<{_unitEnumName}>.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity<{_unitEnumName}> IQuantity<{_unitEnumName}>.ToUnit({_unitEnumName} unit) => this.ToUnit(unit); - #endregion + IQuantity<{_unitEnumName}> IQuantity<{_unitEnumName}>.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion "); @@ -1197,7 +1105,7 @@ public override string ToString() return ToString(null, null); }} - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs b/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs index 64479dbfa2..8240857c25 100644 --- a/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/StaticQuantityGenerator.cs @@ -1,4 +1,6 @@ -using CodeGen.JsonTypes; +using System.Collections.Generic; +using System.Linq; +using CodeGen.JsonTypes; namespace CodeGen.Generators.UnitsNetGen { @@ -33,27 +35,46 @@ internal static class DefaultProvider /// /// All QuantityInfo instances that are present in UnitsNet by default. /// - internal static IReadOnlyList Quantities { get; } = - ["); + internal static IReadOnlyList Quantities => new QuantityInfo[] + {"); foreach (var quantity in _quantities) Writer.WL($@" {quantity.Name}.Info,"); Writer.WL(@" - ]; + }; - internal static void RegisterUnitConversions(UnitConverter unitConverter) + /// + /// All implicit quantity conversions that exist by default. + /// + internal static readonly IReadOnlyList Conversions = new QuantityConversionMapping[] {"); - foreach (Quantity quantity in _quantities) - { + foreach (var quantityRelation in _quantities.SelectMany(quantity => quantity.Relations.Where(x => x.Operator == "inverse")).Distinct(new CumulativeRelationshipEqualityComparer()).OrderBy(relation => relation.LeftQuantity.Name)) Writer.WL($@" - {quantity.Name}.RegisterDefaultConversions(unitConverter);"); - } - + new (typeof({quantityRelation.LeftQuantity.Name}), typeof({quantityRelation.RightQuantity.Name})),"); Writer.WL(@" - } + }; } }"); return Writer.ToString(); } } + + internal class CumulativeRelationshipEqualityComparer: IEqualityComparer{ + public bool Equals(QuantityRelation? x, QuantityRelation? y) + { + if (ReferenceEquals(x, y)) return true; + if (x is null) return false; + if (y is null) return false; + if (x.GetType() != y.GetType()) return false; + return + x.ResultQuantity == y.ResultQuantity && ( + (x.LeftQuantity.Equals(y.LeftQuantity) && x.RightQuantity.Equals(y.RightQuantity)) + || (x.LeftQuantity.Equals(y.RightQuantity) && x.RightQuantity.Equals(y.LeftQuantity))); + } + + public int GetHashCode(QuantityRelation obj) + { + return obj.LeftQuantity.GetHashCode() ^ obj.RightQuantity.GetHashCode(); + } + } } diff --git a/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs b/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs index 9f9345ee88..55856f49c3 100644 --- a/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs +++ b/CodeGen/Generators/UnitsNetGen/UnitTestBaseClassGenerator.cs @@ -59,7 +59,7 @@ internal class UnitTestBaseClassGenerator : GeneratorBase /// A dimensionless quantity has all base dimensions (L, M, T, I, Θ, N, J) equal to zero. /// private readonly bool _isDimensionless; - + /// /// Stores a mapping of culture names to their corresponding unique unit abbreviations. /// Each culture maps to a dictionary where the key is the unit abbreviation and the value is the corresponding @@ -101,7 +101,7 @@ internal class UnitTestBaseClassGenerator : GeneratorBase /// is not available for the defined unit localizations. /// private const string FallbackCultureName = "en-US"; - + public UnitTestBaseClassGenerator(Quantity quantity) { _quantity = quantity; @@ -263,6 +263,7 @@ public abstract partial class {_quantity.Name}TestsBase : QuantityTestsBase Writer.WL($@" new object[] {{ {GetUnitFullName(unit)} }},"); } + Writer.WL($@" }}; @@ -339,6 +340,20 @@ public void Ctor_UnitSystem_ThrowsArgumentExceptionIfNotSupported() Assert.Equal(quantityInfo, ((IQuantity<{_unitEnumName}>)quantity).QuantityInfo); }} + [Fact] + public void {_quantity.Name}Info_CreateWithCustomUnitInfos() + {{ + {_unitEnumName}[] expectedUnits = [{_baseUnitFullName}]; + + {_quantity.Name}.{_quantity.Name}Info quantityInfo = {_quantity.Name}.{_quantity.Name}Info.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal(""{_quantity.Name}"", quantityInfo.Name); + Assert.Equal({_quantity.Name}.Zero, quantityInfo.Zero); + Assert.Equal({_quantity.Name}.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + }} + [Fact] public void {_baseUnit.SingularName}To{_quantity.Name}Units() {{ @@ -584,7 +599,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() } Writer.WL($@" - public void Parse(string culture, string quantityString, {_unitEnumName} expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, {_unitEnumName} expectedUnit, decimal expectedValue) {{ using var _ = new CultureScope(culture); var parsed = {_quantity.Name}.Parse(quantityString); @@ -629,7 +644,7 @@ public void ParseWithAmbiguousAbbreviation(string culture, string quantityString } Writer.WL($@" - public void TryParse(string culture, string quantityString, {_unitEnumName} expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, {_unitEnumName} expectedUnit, decimal expectedValue) {{ using var _ = new CultureScope(culture); Assert.True({_quantity.Name}.TryParse(quantityString, out {_quantity.Name} parsed)); @@ -887,7 +902,7 @@ public void GetAbbreviationWithDefaultCulture() }}); }} "); - + Writer.WL($@" [Theory] [MemberData(nameof(UnitTypes))] @@ -919,6 +934,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit({_unitEnumName} var quantity = {_quantity.Name}.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }}); }} @@ -942,20 +958,22 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity({_unitEnumName} uni IQuantity<{_unitEnumName}> quantityToConvert = quantity; IQuantity<{_unitEnumName}> convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }}, () => {{ IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }}); }} [Fact] public void ConversionRoundTrip() {{ - {_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(1);"); + {_quantity.Name} {baseUnitVariableName} = {_quantity.Name}.From{_baseUnit.PluralName}(3);"); foreach (var unit in _quantity.Units) Writer.WL($@" - AssertEx.EqualTolerance(1, {_quantity.Name}.From{unit.PluralName}({baseUnitVariableName}.{unit.PluralName}).{_baseUnit.PluralName}, {unit.PluralName}Tolerance);"); + Assert.Equal(3, {_quantity.Name}.From{unit.PluralName}({baseUnitVariableName}.{unit.PluralName}).{_baseUnit.PluralName});"); Writer.WL($@" }} "); @@ -967,13 +985,13 @@ public void ConversionRoundTrip() public void LogarithmicArithmeticOperators() {{ {_quantity.Name} v = {_quantity.Name}.From{_baseUnit.PluralName}(40); - AssertEx.EqualTolerance(-40, -v.{_baseUnit.PluralName}, {unit.PluralName}Tolerance); + Assert.Equal(-40, -v.{_baseUnit.PluralName}); AssertLogarithmicAddition(); AssertLogarithmicSubtraction(); - AssertEx.EqualTolerance(50, (v*10).{_baseUnit.PluralName}, {unit.PluralName}Tolerance); - AssertEx.EqualTolerance(50, (10*v).{_baseUnit.PluralName}, {unit.PluralName}Tolerance); - AssertEx.EqualTolerance(35, (v/5).{_baseUnit.PluralName}, {unit.PluralName}Tolerance); - AssertEx.EqualTolerance(35, v/{_quantity.Name}.From{_baseUnit.PluralName}(5), {unit.PluralName}Tolerance); + Assert.Equal(50, (v * 10).{_baseUnit.PluralName}); + Assert.Equal(50, (10 * v).{_baseUnit.PluralName}); + Assert.Equal(35, (v / 5).{_baseUnit.PluralName}); + Assert.Equal(35, v / {_quantity.Name}.From{_baseUnit.PluralName}(5)); }} protected abstract void AssertLogarithmicAddition(); @@ -988,13 +1006,13 @@ public void LogarithmicArithmeticOperators() public void ArithmeticOperators() {{ {_quantity.Name} v = {_quantity.Name}.From{_baseUnit.PluralName}(1); - AssertEx.EqualTolerance(-1, -v.{_baseUnit.PluralName}, {_baseUnit.PluralName}Tolerance); - AssertEx.EqualTolerance(2, ({_quantity.Name}.From{_baseUnit.PluralName}(3)-v).{_baseUnit.PluralName}, {_baseUnit.PluralName}Tolerance); - AssertEx.EqualTolerance(2, (v + v).{_baseUnit.PluralName}, {_baseUnit.PluralName}Tolerance); - AssertEx.EqualTolerance(10, (v*10).{_baseUnit.PluralName}, {_baseUnit.PluralName}Tolerance); - AssertEx.EqualTolerance(10, (10*v).{_baseUnit.PluralName}, {_baseUnit.PluralName}Tolerance); - AssertEx.EqualTolerance(2, ({_quantity.Name}.From{_baseUnit.PluralName}(10)/5).{_baseUnit.PluralName}, {_baseUnit.PluralName}Tolerance); - AssertEx.EqualTolerance(2, {_quantity.Name}.From{_baseUnit.PluralName}(10)/{_quantity.Name}.From{_baseUnit.PluralName}(5), {_baseUnit.PluralName}Tolerance); + Assert.Equal(-1, -v.{_baseUnit.PluralName}); + Assert.Equal(2, ({_quantity.Name}.From{_baseUnit.PluralName}(3) - v).{_baseUnit.PluralName}); + Assert.Equal(2, (v + v).{_baseUnit.PluralName}); + Assert.Equal(10, (v * 10).{_baseUnit.PluralName}); + Assert.Equal(10, (10 * v).{_baseUnit.PluralName}); + Assert.Equal(2, ({_quantity.Name}.From{_baseUnit.PluralName}(10) / 5).{_baseUnit.PluralName}); + Assert.Equal(2, {_quantity.Name}.From{_baseUnit.PluralName}(10) / {_quantity.Name}.From{_baseUnit.PluralName}(5)); }} "); } @@ -1047,13 +1065,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, {_baseUnitFullName}, 1, {_baseUnitFullName}, true)] // Same value and unit. [InlineData(1, {_baseUnitFullName}, 2, {_baseUnitFullName}, false)] // Different value. - [InlineData(2, {_baseUnitFullName}, 1, {_otherOrBaseUnitFullName}, false)] // Different value and unit."); - if (_baseUnit != _otherOrBaseUnit) - { - Writer.WL($@" - [InlineData(1, {_baseUnitFullName}, 1, {_otherOrBaseUnitFullName}, false)] // Different unit."); - } - Writer.WL($@" public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, {_unitEnumName} unitA, double valueB, {_unitEnumName} unitB, bool expectEqual) {{ var a = new {_quantity.Name}(valueA, unitA); @@ -1118,8 +1129,8 @@ public void Equals_Logarithmic_WithTolerance(double firstValue, double secondVal var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(firstValue); var otherQuantity = {_quantity.Name}.From{_baseUnit.PluralName}(secondValue); {differenceResultType} maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, {differenceResultType}.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, largerTolerance)); @@ -1151,8 +1162,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(firstValue); var otherQuantity = {_quantity.Name}.From{_baseUnit.PluralName}(secondValue); {differenceResultType} maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, {differenceResultType}.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1193,7 +1204,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() {{ - var units = Enum.GetValues<{_unitEnumName}>(); + var units = EnumHelper.GetValues<{_unitEnumName}>(); foreach (var unit in units) {{ var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1206,6 +1217,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False({_quantity.Name}.BaseDimensions is null); }} + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + {{ + Assert.Equal({_quantity.Name}.Info.Units, {_quantity.Name}.Units); + }} + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + {{ + Assert.Equal(UnitConverter.Default, {_quantity.Name}.DefaultConversionFunctions); + }} + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() {{ @@ -1278,7 +1301,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() {{ var quantity = {_quantity.Name}.From{_baseUnit.PluralName}(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof({_quantity.Name}), quantity.As({_quantity.Name}.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); }} "); diff --git a/CodeGen/Generators/UnitsNetGenerator.cs b/CodeGen/Generators/UnitsNetGenerator.cs index 907f70e4a6..ca23308212 100644 --- a/CodeGen/Generators/UnitsNetGenerator.cs +++ b/CodeGen/Generators/UnitsNetGenerator.cs @@ -153,9 +153,6 @@ private static void GenerateResourceFiles(Quantity[] quantities, string resource $"{resourcesDirectory}/{quantity.Name}.restext" : $"{resourcesDirectory}/{quantity.Name}.{culture}.restext"; - // Ensure parent folder exists - Directory.CreateDirectory(resourcesDirectory); - using var writer = File.CreateText(fileName); foreach(Unit unit in quantity.Units) diff --git a/CodeGen/Helpers/ExpressionAnalyzer/ExpressionEvaluationTerm.cs b/CodeGen/Helpers/ExpressionAnalyzer/ExpressionEvaluationTerm.cs new file mode 100644 index 0000000000..559e476240 --- /dev/null +++ b/CodeGen/Helpers/ExpressionAnalyzer/ExpressionEvaluationTerm.cs @@ -0,0 +1,14 @@ +using Fractions; + +namespace CodeGen.Helpers.ExpressionAnalyzer; + +/// +/// A term of the form "P^n" where P is a term that hasn't been parsed, raised to the given power. +/// +/// The actual expression to parse +/// The exponent to use on the parsed expression (default is 1) +/// +/// Since we're tokenizing the expressions from top to bottom, the first step is parsing the exponent of the +/// expression: e.g. Math.Pow(P, 2) +/// +public record ExpressionEvaluationTerm(string Expression, Fraction Exponent); diff --git a/CodeGen/Helpers/ExpressionAnalyzer/ExpressionEvaluator.cs b/CodeGen/Helpers/ExpressionAnalyzer/ExpressionEvaluator.cs new file mode 100644 index 0000000000..2f850a9be4 --- /dev/null +++ b/CodeGen/Helpers/ExpressionAnalyzer/ExpressionEvaluator.cs @@ -0,0 +1,296 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +using CodeGen.Helpers.ExpressionAnalyzer.Expressions; +using CodeGen.Helpers.ExpressionAnalyzer.Functions; +using CodeGen.Helpers.ExpressionAnalyzer.Functions.Math; +using CodeGen.Helpers.ExpressionAnalyzer.Functions.Math.Trigonometry; +using Fractions; + +namespace CodeGen.Helpers.ExpressionAnalyzer; + +internal class ExpressionEvaluator // TODO make public (and move out in a separate project) +{ + public static readonly Fraction Pi = FractionExtensions.FromDoubleRounded(Math.PI, 16); + private readonly IReadOnlyDictionary _constantValues; + private readonly Dictionary _expressionsEvaluated = []; + + private readonly IReadOnlyDictionary _functionEvaluators; + + public ExpressionEvaluator(string parameterName, params IFunctionEvaluator[] functionEvaluators) + : this(parameterName, functionEvaluators.ToDictionary(x => x.FunctionName), new Dictionary()) + { + } + + public ExpressionEvaluator(string parameterName, IReadOnlyDictionary constantValues, params IFunctionEvaluator[] functionEvaluators) + : this(parameterName, functionEvaluators.ToDictionary(x => x.FunctionName), constantValues) + { + } + + public ExpressionEvaluator(string parameterName, IReadOnlyDictionary functionEvaluators, + IReadOnlyDictionary constantValues) + { + ParameterName = parameterName; + _constantValues = constantValues; + _functionEvaluators = functionEvaluators; + } + + public string ParameterName { get; } + + protected string Add(CompositeExpression expression) + { + var label = "{" + (char)('a' + _expressionsEvaluated.Count) + "}"; + _expressionsEvaluated[label] = expression; + return label; + } + + public CompositeExpression Evaluate(ExpressionEvaluationTerm expressionEvaluationTerm) // TODO either replace by string or add a coefficient + { + if (TryParseExpressionTerm(expressionEvaluationTerm.Expression, expressionEvaluationTerm.Exponent, out ExpressionTerm? expressionTerm)) + { + return expressionTerm; + } + + var expressionToParse = expressionEvaluationTerm.Expression; + Fraction exponent = expressionEvaluationTerm.Exponent; + string previousExpression; + do + { + previousExpression = expressionToParse; + // the regex captures the innermost occurrence of a function group: "Sin(x)", "Pow(x, y)", "(x + 1)" are all valid matches + expressionToParse = Regex.Replace(expressionToParse, @"(\w*)\(([^()]*)\)", match => + { + var functionName = match.Groups[1].Value; + var functionBodyToParse = match.Groups[2].Value; + var evaluationTerm = new ExpressionEvaluationTerm(functionBodyToParse, exponent); + if (string.IsNullOrEmpty(functionName)) // standard grouping (technically this is equivalent to f(x) -> x) + { + // all terms within the group are expanded: extract the simplified expression + CompositeExpression expression = ReplaceTokenizedExpressions(evaluationTerm); + return Add(expression); + } + + if (_functionEvaluators.TryGetValue(functionName, out IFunctionEvaluator? functionEvaluator)) + { + // resolve the expression using the custom function evaluator + CompositeExpression expression = functionEvaluator.CreateExpression(evaluationTerm, ReplaceTokenizedExpressions); + return Add(expression); + } + + throw new FormatException($"No function evaluator available for {functionName}({functionBodyToParse})"); + }); + } while (previousExpression != expressionToParse); + + return ReplaceTokenizedExpressions(expressionEvaluationTerm with { Expression = expressionToParse }); + } + + private CompositeExpression ReplaceTokenizedExpressions(ExpressionEvaluationTerm tokenizedExpression) + { + // all groups and function are expanded: we're left with a standard arithmetic expression such as "4 * a + 2 * b * x - c - d + 5" + // with a, b, c, d representing the previously evaluated expressions + var result = new CompositeExpression(); + var stringBuilder = new StringBuilder(); + ArithmeticOperationToken lastToken = ArithmeticOperationToken.Addition; + CompositeExpression? runningExpression = null; + foreach (var character in tokenizedExpression.Expression) + { + if (!TryReadToken(character, out ArithmeticOperationToken currentToken)) // TODO use None? + { + continue; + } + + switch (currentToken) + { + case ArithmeticOperationToken.Addition or ArithmeticOperationToken.Subtraction: + { + if (stringBuilder.Length == 0) // ignore the leading sign + { + lastToken = currentToken; + continue; + } + + // we're at the end of a term expression + CompositeExpression lastTerm = ParseTerm(); + if (runningExpression is null) + { + result.AddTerms(lastTerm); + } + else // the last term is part of a running multiplication + { + result.AddTerms(runningExpression * lastTerm); + runningExpression = null; + } + + lastToken = currentToken; + break; + } + case ArithmeticOperationToken.Multiplication or ArithmeticOperationToken.Division: + { + CompositeExpression previousTerm = ParseTerm(); + if (runningExpression is null) + { + runningExpression = previousTerm; + } + else // the previousTerm term is part of a running multiplication (which is going to be followed by at least one more multiplication/division) + { + runningExpression *= previousTerm; + } + + lastToken = currentToken; + break; + } + } + } + + CompositeExpression finalTerm = ParseTerm(); + if (runningExpression is null) + { + result.AddTerms(finalTerm); + } + else + { + result.AddTerms(runningExpression * finalTerm); + } + + return result; + + bool TryReadToken(char character, out ArithmeticOperationToken token) + { + switch (character) + { + case '+': + token = ArithmeticOperationToken.Addition; + return true; + case '-': + token = ArithmeticOperationToken.Subtraction; + return true; + case '*': + token = ArithmeticOperationToken.Multiplication; + return true; + case '/': + token = ArithmeticOperationToken.Division; + return true; + case not ' ': + stringBuilder.Append(character); + break; + } + + token = default; + return false; + } + + CompositeExpression ParseTerm() + { + var previousExpression = stringBuilder.ToString(); + stringBuilder.Clear(); + if (_expressionsEvaluated.TryGetValue(previousExpression, out CompositeExpression? expression)) + { + return lastToken switch + { + ArithmeticOperationToken.Subtraction => expression.Negate(), + ArithmeticOperationToken.Division => expression.Invert(), + _ => expression + }; + } + + if (TryParseExpressionTerm(previousExpression, tokenizedExpression.Exponent, out ExpressionTerm? expressionTerm)) + { + return lastToken switch + { + ArithmeticOperationToken.Subtraction => expressionTerm.Negate(), + ArithmeticOperationToken.Division => expressionTerm.Invert(), + _ => expressionTerm + }; + } + + throw new FormatException($"Failed to parse the previous token: {previousExpression}"); + } + } + + + private bool TryParseExpressionTerm(string expressionToParse, Fraction exponent, [MaybeNullWhen(false)] out ExpressionTerm expressionTerm) + { + if (expressionToParse == ParameterName) + { + expressionTerm = new ExpressionTerm(Fraction.One, exponent); + return true; + } + + if (_constantValues.TryGetValue(expressionToParse, out Fraction constantExpression) || Fraction.TryParse(expressionToParse, out constantExpression)) + { + if (exponent.Numerator == exponent.Denominator) + { + expressionTerm = ExpressionTerm.Constant(constantExpression); + return true; + } + + if (exponent.Denominator.IsOne) + { + expressionTerm = ExpressionTerm.Constant(Fraction.Pow(constantExpression, (int)exponent.Numerator)); + return true; + } + + // constant expression using a non-integer power: there is currently no Fraction.Pow(Fraction, Fraction) + expressionTerm = ExpressionTerm.Constant(FractionExtensions.FromDoubleRounded(Math.Pow(constantExpression.ToDouble(), exponent.ToDouble()))); + return true; + } + + expressionTerm = null; + return false; + } + + public static string ReplaceDecimalNotations(string expression, Dictionary constantValues) + { + return Regex.Replace(expression, @"\d*(\.\d*)?[eE][-\+]?\d*[dD]?", match => + { + var tokens = match.Value.ToLower().Replace("d", "").Split('e'); + if (tokens.Length != 2 || !Fraction.TryParse(tokens[0], out Fraction mantissa) || !int.TryParse(tokens[1], out var exponent)) + { + throw new FormatException($"The expression contains invalid tokens: {expression}"); + } + + var label = $"{{v{constantValues.Count}}}"; + constantValues[label] = mantissa * Fraction.Pow(10, exponent); + return label; + }).Replace("d", string.Empty); // TODO these are force-generated for the BitRate (we should stop doing it) + } + + public static string ReplaceMathPi(string expression, Dictionary constantValues) + { + return Regex.Replace(expression, @"Math\.PI", _ => + { + constantValues[nameof(Pi)] = Pi; + return nameof(Pi); + }); + } + + public static CompositeExpression Evaluate(string expression, string parameter) + { + var constantExpressions = new Dictionary(); + + expression = ReplaceDecimalNotations(expression, constantExpressions); // TODO expose an IPreprocessor (or something) + expression = ReplaceMathPi(expression, constantExpressions); + expression = expression.Replace("Math.", string.Empty); + + // these are no longer necessary + // var expressionEvaluator = new ExpressionEvaluator(parameter, constantExpressions, + // new SqrtFunctionEvaluator(), + // new PowFunctionEvaluator(), + // new SinFunctionEvaluator(), + // new AsinFunctionEvaluator()); + var expressionEvaluator = new ExpressionEvaluator(parameter, constantExpressions); + + return expressionEvaluator.Evaluate(new ExpressionEvaluationTerm(expression, Fraction.One)); + } + + private enum ArithmeticOperationToken + { + Addition, + Subtraction, + Multiplication, + Division + } +} diff --git a/CodeGen/Helpers/ExpressionAnalyzer/Expressions/CompositeExpression.cs b/CodeGen/Helpers/ExpressionAnalyzer/Expressions/CompositeExpression.cs new file mode 100644 index 0000000000..7175578acb --- /dev/null +++ b/CodeGen/Helpers/ExpressionAnalyzer/Expressions/CompositeExpression.cs @@ -0,0 +1,213 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using Fractions; + +namespace CodeGen.Helpers.ExpressionAnalyzer.Expressions; + +/// +/// A set of terms, ordered by their degree: "P(x)^2 + P(x) + 1" +/// +internal class CompositeExpression : IEnumerable +{ + private readonly SortedSet _terms; + + /// + /// Initializes a new instance of the class. + /// + /// + /// This constructor creates an empty CompositeExpression with terms sorted in descending order. + /// + public CompositeExpression() + { + _terms = new SortedSet(DescendingOrderComparer); + } + + /// + /// Initializes a new instance of the class with a single term. + /// + /// The initial term of the composite expression. + /// + /// This constructor creates a CompositeExpression with a single term, sorted in descending order. + /// + public CompositeExpression(ExpressionTerm term) + { + _terms = new SortedSet(DescendingOrderComparer) { term }; + } + + private CompositeExpression(IEnumerable terms) + { + _terms = new SortedSet(terms, DescendingOrderComparer); + } + + public Fraction Degree => _terms.Min?.Exponent ?? Fraction.Zero; + + public bool IsConstant => Degree == Fraction.Zero; + + public IReadOnlyCollection Terms => _terms; + + public void Add(ExpressionTerm term) + { + if (_terms.TryGetValue(term, out ExpressionTerm? sameDegreeTerm)) + { + // merge the two terms + term = term with { Coefficient = sameDegreeTerm.Coefficient + term.Coefficient }; + _terms.Remove(sameDegreeTerm); + } + + _terms.Add(term); + } + + public void AddTerms(IEnumerable expressionTerms) + { + foreach (ExpressionTerm term in expressionTerms) + { + Add(term); + } + } + + + public static implicit operator CompositeExpression(ExpressionTerm term) + { + return new CompositeExpression(term); + } + + public static explicit operator ExpressionTerm(CompositeExpression term) + { + return term._terms.Max!; + } + + public CompositeExpression Negate() + { + return new CompositeExpression(_terms.Select(term => term.Negate())); + } + + public CompositeExpression Invert() + { + return new CompositeExpression(_terms.Select(term => term.Invert())); + } + + public CompositeExpression SolveForY() + { + if (_terms.Count == 0) + { + throw new InvalidOperationException("The expression is empty"); + } + + if (_terms.Count > 2) + { + throw new NotImplementedException("Solving is only supported for expressions of first degree"); + } + + ExpressionTerm degreeTerm = _terms.Min!; + if (degreeTerm.Exponent == Fraction.One) + { + return new CompositeExpression(_terms.Where(x => x.IsConstant).Select(x => x with { Coefficient = x.Coefficient.Negate() / degreeTerm.Coefficient }) + .Prepend(new ExpressionTerm(degreeTerm.Coefficient.Reciprocal(), 1))); + } + + if (degreeTerm.Exponent == Fraction.MinusOne) + { + return new CompositeExpression(_terms.Where(x => x.IsConstant).Select(x => x with { Coefficient = degreeTerm.Coefficient / x.Coefficient.Negate() }) + .Prepend(new ExpressionTerm(degreeTerm.Coefficient, -1))); + } + + throw new NotImplementedException("Solving is only supported for expressions of first degree"); + } + + public CompositeExpression Multiply(CompositeExpression other) + { + var result = new CompositeExpression(); + foreach (ExpressionTerm otherTerm in other) + { + result.AddTerms(_terms.Select(x => x.Multiply(otherTerm))); + } + + return result; + } + + public CompositeExpression Divide(CompositeExpression other) + { + var result = new CompositeExpression(); + foreach (ExpressionTerm otherTerm in other) + { + result.AddTerms(_terms.Select(x => x.Divide(otherTerm))); + } + + return result; + } + + public static CompositeExpression operator *(CompositeExpression left, CompositeExpression right) + { + return left.Multiply(right); + } + + public static CompositeExpression operator /(CompositeExpression left, CompositeExpression right) + { + return left.Divide(right); + } + + public override string ToString() + { + return string.Join(" + ", _terms); + } + + public CompositeExpression Evaluate(Fraction x) + { + var result = new CompositeExpression(); + result.AddTerms(_terms.Select(t => t.Evaluate(x))); + return result; + } + + public CompositeExpression Evaluate(CompositeExpression expression) + { + var result = new CompositeExpression(); + foreach (ExpressionTerm expressionTerm in _terms) + { + if (expressionTerm.IsConstant) + { + result.Add(expressionTerm); + } + else + { + result.AddTerms(expression.Terms.Select(term => expressionTerm.Evaluate(term))); + } + } + + return result; + } + + #region TermComparer + + private sealed class DescendingOrderTermComparer : IComparer + { + public int Compare(ExpressionTerm? y, ExpressionTerm? x) + { + if (ReferenceEquals(x, y)) return 0; + if (ReferenceEquals(null, y)) return 1; + if (ReferenceEquals(null, x)) return -1; + var nestedFunctionComparison = Comparer.Default.Compare(x.NestedFunction, y.NestedFunction); + if (nestedFunctionComparison != 0) return nestedFunctionComparison; + return x.Exponent.Abs().CompareTo(y.Exponent.Abs()); + } + } + + public static IComparer DescendingOrderComparer { get; } = new DescendingOrderTermComparer(); + + #endregion + + #region Implementation of IEnumerable + + public IEnumerator GetEnumerator() + { + return _terms.GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + #endregion +} diff --git a/CodeGen/Helpers/ExpressionAnalyzer/Expressions/CustomFunction.cs b/CodeGen/Helpers/ExpressionAnalyzer/Expressions/CustomFunction.cs new file mode 100644 index 0000000000..292347f8c7 --- /dev/null +++ b/CodeGen/Helpers/ExpressionAnalyzer/Expressions/CustomFunction.cs @@ -0,0 +1,43 @@ +using System; + +namespace CodeGen.Helpers.ExpressionAnalyzer.Expressions; + +/// +/// A custom function f(ax^n + bx^m) +/// +/// +/// +/// +/// +/// These are functions that we don't directly support, such as Sqrt. +internal record CustomFunction(string Namespace, string Name, CompositeExpression Terms, params string[] AdditionalParameters) : IComparable, IComparable +{ + #region Overrides of Object + + public override string ToString() + { + if(AdditionalParameters.Length == 0) + return $"{Name}({Terms})"; + return $"{Name}({Terms}, {string.Join(", ", AdditionalParameters)})"; + } + + #endregion + + #region Relational members + + public int CompareTo(CustomFunction? other) + { + if (ReferenceEquals(this, other)) return 0; + if (ReferenceEquals(null, other)) return 1; + return string.Compare(Name, other.Name, StringComparison.Ordinal); + } + + public int CompareTo(object? obj) + { + if (ReferenceEquals(null, obj)) return 1; + if (ReferenceEquals(this, obj)) return 0; + return obj is CustomFunction other ? CompareTo(other) : throw new ArgumentException($"Object must be of type {nameof(CustomFunction)}"); + } + + #endregion +} diff --git a/CodeGen/Helpers/ExpressionAnalyzer/Expressions/ExpressionTerm.cs b/CodeGen/Helpers/ExpressionAnalyzer/Expressions/ExpressionTerm.cs new file mode 100644 index 0000000000..ecfb25d88c --- /dev/null +++ b/CodeGen/Helpers/ExpressionAnalyzer/Expressions/ExpressionTerm.cs @@ -0,0 +1,130 @@ +using System; +using System.Collections.Generic; +using System.Numerics; +using CodeGen.Helpers.ExpressionAnalyzer.Functions.Math; +using Fractions; + +namespace CodeGen.Helpers.ExpressionAnalyzer.Expressions; + +/// +/// A term of the form "a * f(x)^n". +/// +/// The constant coefficient (a) +/// The degree of the term (n) +/// f(x) if one is available +/// When there is no nested function f(x) = x +internal record ExpressionTerm(Fraction Coefficient, Fraction Exponent, CustomFunction? NestedFunction = null) : IComparable, IComparable +{ + public bool IsRational => NestedFunction is null && Exponent.Denominator.IsOne; + + public bool IsConstant => NestedFunction is null && Exponent.IsZero; + + public ExpressionTerm Negate() + { + return this with { Coefficient = Coefficient.Negate() }; + } + + public ExpressionTerm Invert() + { + return this with { Exponent = Exponent.Negate(), Coefficient = Coefficient.Reciprocal() }; + } + + public ExpressionTerm Multiply(ExpressionTerm otherTerm) + { + if (NestedFunction != null && otherTerm.NestedFunction != null && + NestedFunction != otherTerm.NestedFunction) // there aren't any cases of this in the code-base + { + throw new NotSupportedException( + "Multiplying terms with different functions is currently not supported"); // if we need to, we should use a collection or create some function-composition + } + + return new ExpressionTerm(Coefficient * otherTerm.Coefficient, Exponent + otherTerm.Exponent, NestedFunction ?? otherTerm.NestedFunction); + } + + public ExpressionTerm Divide(ExpressionTerm otherTerm) + { + return Multiply(otherTerm.Invert()); + } + + public static ExpressionTerm Constant(Fraction coefficient) + { + return new ExpressionTerm(coefficient, Fraction.Zero); + } + + #region Overrides of Object + + public override string ToString() + { + var coefficientFormat = Coefficient == Fraction.One ? "" : + Coefficient == Fraction.MinusOne ? "-" : $"{Coefficient.ToDouble()} * "; + if (NestedFunction == null) + { + if (Exponent == Fraction.Zero) + { + return $"{Coefficient.ToDouble()}"; + } + + if (Exponent == Fraction.One) + { + return $"{coefficientFormat}x"; + } + + return $"{coefficientFormat}x^{Exponent.ToDouble()}"; + } + + return $"{coefficientFormat}{NestedFunction}"; + } + + #endregion + + public ExpressionTerm Evaluate(Fraction x) + { + if (NestedFunction != null || Exponent.IsZero) + { + return this; + } + + return IsRational + ? Constant(Coefficient * Fraction.Pow(x, Exponent.ToInt32())) + : Constant(Coefficient * FractionExtensions.FromDoubleRounded(Math.Pow(x.ToDouble(), Exponent.ToDouble()))); + } + + public ExpressionTerm Evaluate(ExpressionTerm term) + { + if (Exponent.IsZero) + { + return this; + } + + if (NestedFunction == null) + { + return new ExpressionTerm(Coefficient * term.Coefficient.Pow(Exponent), term.Exponent * Exponent); + } + + CompositeExpression nestedTerms = NestedFunction.Terms.Evaluate(term); + return this with { NestedFunction = NestedFunction with { Terms = nestedTerms } }; + + } + + #region Relational members + + public int CompareTo(ExpressionTerm? other) + { + if (ReferenceEquals(this, other)) return 0; + if (other is null) return 1; + var exponentComparison = Exponent.CompareTo(other.Exponent); + if (exponentComparison != 0) return exponentComparison; + var nestedFunctionComparison = Comparer.Default.Compare(NestedFunction, other.NestedFunction); + if (nestedFunctionComparison != 0) return nestedFunctionComparison; + return Coefficient.CompareTo(other.Coefficient); + } + + public int CompareTo(object? obj) + { + if (ReferenceEquals(null, obj)) return 1; + if (ReferenceEquals(this, obj)) return 0; + return obj is ExpressionTerm other ? CompareTo(other) : throw new ArgumentException($"Object must be of type {nameof(ExpressionTerm)}"); + } + + #endregion +} diff --git a/CodeGen/Helpers/ExpressionAnalyzer/Functions/IFunctionEvaluator.cs b/CodeGen/Helpers/ExpressionAnalyzer/Functions/IFunctionEvaluator.cs new file mode 100644 index 0000000000..3af9dcd222 --- /dev/null +++ b/CodeGen/Helpers/ExpressionAnalyzer/Functions/IFunctionEvaluator.cs @@ -0,0 +1,26 @@ +using System; +using CodeGen.Helpers.ExpressionAnalyzer.Expressions; + +namespace CodeGen.Helpers.ExpressionAnalyzer.Functions; + +/// +/// Defines the contract for a function evaluator that can parse and create expressions. +/// +/// +/// Implementations of this interface are used to evaluate specific mathematical functions. +/// +internal interface IFunctionEvaluator +{ + /// + /// Gets the name of the function that this evaluator can handle. + /// + string FunctionName { get; } + + /// + /// Parses the given expression and returns a pending term. + /// + /// The expression to parse. + /// Can be used to evaluate the function body expression. + /// A that represents the parsed expression. + CompositeExpression CreateExpression(ExpressionEvaluationTerm expressionToParse, Func expressionResolver); +} diff --git a/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/FractionExtensions.cs b/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/FractionExtensions.cs new file mode 100644 index 0000000000..a07ef2d67d --- /dev/null +++ b/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/FractionExtensions.cs @@ -0,0 +1,69 @@ +// 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.Numerics; +using Fractions; + +namespace CodeGen.Helpers.ExpressionAnalyzer.Functions.Math; + +/// +/// We should try to push these extensions to the original library (working on the PRs) +/// +internal static class FractionExtensions +{ + public static readonly Fraction OneHalf = new(BigInteger.One, new BigInteger(2)); + public static readonly BigInteger Ten = new(10); + + public static Fraction Pow(this Fraction x, Fraction power) + { + if (power == Fraction.One) + { + return x; + } + + if (x == Fraction.One) + { + return x; + } + + power = power.Reduce(); + if (power.Denominator.IsOne) + { + return Fraction.Pow(x, (int)power); + } + + // return FromDoubleRounded(System.Math.Pow(x.ToDouble(), power.ToDouble())); + return PowRational(x, power); + } + + private static Fraction PowRational(this Fraction x, Fraction power) + { + var numeratorRaised = Fraction.Pow(x, (int)power.Numerator); + return numeratorRaised.Root((int)power.Denominator, 30); + } + + public static Fraction Root(this Fraction number, int n, int nbDigits) + { + var precision = BigInteger.Pow(10, nbDigits); + // Fraction x = number; // Initial guess + var initialGuess = System.Math.Pow(number.ToDouble(), 1.0 / n); + Fraction x = initialGuess == 0.0 ? number : FromDoubleRounded(initialGuess); + Fraction xPrev; + var minChange = new Fraction(1, precision); + do + { + xPrev = x; + x = ((n - 1) * x + number / Fraction.Pow(x, n - 1)) / n; + } while ((x - xPrev).Abs() > minChange); + + return Fraction.Round(x, nbDigits); + } + + /// + /// + /// + public static Fraction FromDoubleRounded(double value, int nbSignificantDigits = 15) + { + return Fraction.FromDoubleRounded(value, nbSignificantDigits); + } +} diff --git a/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/MathFunctionEvaluator.cs b/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/MathFunctionEvaluator.cs new file mode 100644 index 0000000000..d5df4dacae --- /dev/null +++ b/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/MathFunctionEvaluator.cs @@ -0,0 +1,27 @@ +using System; +using CodeGen.Helpers.ExpressionAnalyzer.Expressions; +using Fractions; + +namespace CodeGen.Helpers.ExpressionAnalyzer.Functions.Math; + +internal abstract class MathFunctionEvaluator : IFunctionEvaluator +{ + public virtual string Namespace => nameof(System.Math); + public abstract string FunctionName { get; } + + public CompositeExpression CreateExpression(ExpressionEvaluationTerm expressionToParse, Func expressionResolver) + { + CompositeExpression functionBody = expressionResolver(expressionToParse with {Exponent = 1}); + Fraction power = expressionToParse.Exponent; + if (functionBody.IsConstant) // constant expression (directly evaluate the function) + { + var constantTerm = (ExpressionTerm)functionBody; + Fraction resultingValue = Evaluate(constantTerm.Coefficient); + return ExpressionTerm.Constant(resultingValue.Pow(power)); + } + // we cannot expand a function of x + return new ExpressionTerm(1, power, new CustomFunction(Namespace, FunctionName, functionBody)); + } + + public abstract Fraction Evaluate(Fraction value); +} diff --git a/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/PowFunctionEvaluator.cs b/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/PowFunctionEvaluator.cs new file mode 100644 index 0000000000..b1a6bafc7a --- /dev/null +++ b/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/PowFunctionEvaluator.cs @@ -0,0 +1,50 @@ +using System; +using System.Globalization; +using CodeGen.Helpers.ExpressionAnalyzer.Expressions; +using Fractions; + +namespace CodeGen.Helpers.ExpressionAnalyzer.Functions.Math; + +internal class PowFunctionEvaluator : IFunctionEvaluator +{ + public string Namespace => nameof(System.Math); + public string FunctionName => nameof(System.Math.Pow); + + public bool ExpandNonConstantExpressions { get; set; } = false; // while it's possible to expand the expression (even for non-rational powers)- probably we shouldn't + + public CompositeExpression CreateExpression(ExpressionEvaluationTerm expressionToParse, + Func expressionResolver) + { + var functionParams = expressionToParse.Expression.Split(','); + if (functionParams.Length != 2 || !Fraction.TryParse(functionParams[1], out Fraction exponentParsed)) + { + throw new FormatException($"The provided string is not in the correct format for the Pow function {expressionToParse}"); + } + + CompositeExpression functionBody = expressionResolver(new ExpressionEvaluationTerm(functionParams[0], 1)); + Fraction power = expressionToParse.Exponent * exponentParsed; + + if (functionBody.IsConstant) + { + var singleTerm = (ExpressionTerm)functionBody; + Fraction coefficient = singleTerm.Coefficient.Pow(power); + return ExpressionTerm.Constant(coefficient); + } + + if (!ExpandNonConstantExpressions) + { + return new ExpressionTerm(1, 1, new CustomFunction(Namespace, FunctionName, functionBody, power.ToDecimal().ToString(CultureInfo.InvariantCulture))); + } + + // while it's possible to expand the expression (even for non-rational powers)- we shouldn't, as the operation would not be reversible: the result of (x^0.5)^2 may be different from x + if (functionBody.Terms.Count == 1) + { + var singleTerm = (ExpressionTerm)functionBody; + Fraction coefficient = singleTerm.Coefficient.Pow(power); + return singleTerm with { Coefficient = coefficient, Exponent = singleTerm.Exponent * power }; + } + + // TODO see about handling the multi-term expansion (at least for integer exponents) + return new ExpressionTerm(1, 1, new CustomFunction(Namespace, FunctionName, functionBody, power.ToDecimal().ToString(CultureInfo.InvariantCulture))); + } +} diff --git a/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/SqrtFunctionEvaluator.cs b/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/SqrtFunctionEvaluator.cs new file mode 100644 index 0000000000..989a63c992 --- /dev/null +++ b/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/SqrtFunctionEvaluator.cs @@ -0,0 +1,40 @@ +using System; +using CodeGen.Helpers.ExpressionAnalyzer.Expressions; +using Fractions; + +namespace CodeGen.Helpers.ExpressionAnalyzer.Functions.Math; + +internal class SqrtFunctionEvaluator : IFunctionEvaluator +{ + public string Namespace => nameof(System.Math); // we could switch this to QuantityValue if we decide to add it later + public string FunctionName => nameof(System.Math.Sqrt); + public bool ExpandNonConstantExpressions { get; set; } = false; // while it's possible to expand the expression (even for non-rational powers)- probably we shouldn't + + public CompositeExpression CreateExpression(ExpressionEvaluationTerm expressionToParse, Func expressionResolver) + { + CompositeExpression functionBody = expressionResolver(expressionToParse with {Exponent = 1}); + if (functionBody.IsConstant) + { + var constantTerm = (ExpressionTerm)functionBody; + Fraction coefficient = constantTerm.Coefficient.Pow(expressionToParse.Exponent * FractionExtensions.OneHalf); + return ExpressionTerm.Constant(coefficient); + } + + if (!ExpandNonConstantExpressions) + { + return new ExpressionTerm(1, expressionToParse.Exponent, new CustomFunction(Namespace, FunctionName, functionBody)); + } + + // while it's possible to expand the expression (even for non-rational powers)- we shouldn't, as the operation would not be reversible: the result of (x^0.5)^2 may be different from x + Fraction power = expressionToParse.Exponent * FractionExtensions.OneHalf; + if (functionBody.Terms.Count == 1) + { + var constantTerm = (ExpressionTerm)functionBody; + Fraction coefficient = constantTerm.Coefficient.Pow(power); + return constantTerm with { Coefficient = coefficient, Exponent = constantTerm.Exponent * power }; + } + + // TODO see about handling the multi-term expansion (at least for integer exponents) + return new ExpressionTerm(1, power, new CustomFunction(Namespace, FunctionName, functionBody)); + } +} diff --git a/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/Trigonometry/AsinFunctionEvaluator.cs b/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/Trigonometry/AsinFunctionEvaluator.cs new file mode 100644 index 0000000000..de7ef7623c --- /dev/null +++ b/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/Trigonometry/AsinFunctionEvaluator.cs @@ -0,0 +1,13 @@ +using Fractions; + +namespace CodeGen.Helpers.ExpressionAnalyzer.Functions.Math.Trigonometry; + +internal class AsinFunctionEvaluator : MathFunctionEvaluator +{ + public override string FunctionName => nameof(System.Math.Asin); + + public override Fraction Evaluate(Fraction value) + { + return FractionExtensions.FromDoubleRounded(System.Math.Asin(value.ToDouble())); + } +} diff --git a/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/Trigonometry/SinFunctionEvaluator.cs b/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/Trigonometry/SinFunctionEvaluator.cs new file mode 100644 index 0000000000..b81d69613c --- /dev/null +++ b/CodeGen/Helpers/ExpressionAnalyzer/Functions/Math/Trigonometry/SinFunctionEvaluator.cs @@ -0,0 +1,13 @@ +using Fractions; + +namespace CodeGen.Helpers.ExpressionAnalyzer.Functions.Math.Trigonometry; + +internal class SinFunctionEvaluator : MathFunctionEvaluator +{ + public override string FunctionName => nameof(System.Math.Sin); + + public override Fraction Evaluate(Fraction value) + { + return FractionExtensions.FromDoubleRounded(System.Math.Sin(value.ToDouble())); + } +} diff --git a/CodeGen/Helpers/ExpressionEvaluationHelpers.cs b/CodeGen/Helpers/ExpressionEvaluationHelpers.cs new file mode 100644 index 0000000000..a252f4f71e --- /dev/null +++ b/CodeGen/Helpers/ExpressionEvaluationHelpers.cs @@ -0,0 +1,462 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Numerics; +using CodeGen.Helpers.ExpressionAnalyzer; +using CodeGen.Helpers.ExpressionAnalyzer.Expressions; +using CodeGen.JsonTypes; +using Fractions; + +namespace CodeGen.Helpers; + +internal static class ExpressionEvaluationHelpers +{ + private record struct Factor(BigInteger Number, int Power, BigInteger Value) + { + public static Factor FromNumber(BigInteger number) => new(number, 1, number); + + private sealed class ValueRelationalComparer : IComparer + { + public int Compare(Factor x, Factor y) + { + return x.Value.CompareTo(y.Value); + } + } + + public static IComparer ValueComparer { get; } = new ValueRelationalComparer(); + }; + + private static List ExtractFactors(this BigInteger number) + { + number = BigInteger.Abs(number); + var factors = new List(); + if (number.IsPowerOfTwo) + { + var exponent = (int)(number.GetBitLength() - 1); + var divisor = BigInteger.Pow(2, exponent); + factors.Add(new Factor(2, exponent, divisor)); + return factors; + } + + var factorsToTryFirst = new BigInteger[] {10, 2, 3, 5, 7}; + foreach (BigInteger divisor in factorsToTryFirst) + { + if (TryGetFactors(number, divisor, out number, out Factor factor)) + { + factors.Add(factor); + if (number.IsOne) + { + return factors; + } + + if (number <= long.MaxValue) + { + factors.Add(Factor.FromNumber(number)); + return factors; + } + } + } + + BigInteger currentDivisor = 11; + do + { + if (TryGetFactors(number, currentDivisor, out number, out Factor factor)) + { + factors.Add(factor); + } + + currentDivisor++; + } while (number > long.MaxValue && number > currentDivisor); + + if (!number.IsOne) + { + factors.Add(Factor.FromNumber(number)); + } + + return factors; + } + + private static bool TryGetFactors(BigInteger number, BigInteger divisor, out BigInteger quotient, out Factor factor) + { + quotient = number; + var power = 0; + while (true) + { + var nextQuotient = BigInteger.DivRem(quotient, divisor, out BigInteger remainder); + if (remainder.IsZero) + { + quotient = nextQuotient; + power++; + } + else + { + factor = new Factor(divisor, power, BigInteger.Pow(divisor, power)); + return power > 0; + } + } + } + + private static SortedSet MergeFactors(this IEnumerable factorsToMerge) + { + var factors = new SortedSet(factorsToMerge, Factor.ValueComparer); + while (factors.Count > 1) + { + // try to merge the next two factors + Factor smallestFactor = factors.First(); + Factor secondSmallestFactor = factors.Skip(1).First(); + var mergedFactor = Factor.FromNumber(smallestFactor.Value * secondSmallestFactor.Value); + if (mergedFactor.Value > long.MaxValue) + { + return factors; // we've got the smallest possible set + } + + // replace the two factors with their merged version + factors.Remove(smallestFactor); + factors.Remove(secondSmallestFactor); + factors.Add(mergedFactor); + } + + return factors; + } + + private static string GetConstantFormat(this Factor factor) + { + if (factor.Power == 1) + { + return $"new BigInteger({factor.Value})"; + } + else if (factor.Number == 10) + { + return $"QuantityValue.PowerOfTen({factor.Power})"; + } + else + { + return $"BigInteger.Pow({factor.Number}, {factor.Power})"; + } + } + + private static string GetConstantMultiplicationFormat(this IEnumerable factors, bool negate = false) + { + var expression = string.Join(" * ", factors.Select(x => x.GetConstantFormat())); + if (negate) + { + expression = "-" + expression; + } + + return expression; + } + + private static string GetConstantFormat(this Fraction coefficient) + { + if (coefficient == Fraction.One) + { + return "1"; + } + + return coefficient.Denominator.IsOne + ? coefficient.Numerator.ToString() + : $"new QuantityValue({coefficient.Numerator}, {coefficient.Denominator})"; + } + + private static string GetLongConstantFormat(this Fraction coefficient) + { + var numeratorExpression = coefficient.Numerator > long.MaxValue || coefficient.Numerator < long.MinValue + ? coefficient.Numerator.ExtractFactors().MergeFactors().GetConstantMultiplicationFormat(coefficient.IsNegative) + : coefficient.Numerator.ToString(); + var denominatorExpression = coefficient.Denominator > long.MaxValue + ? coefficient.Denominator.ExtractFactors().MergeFactors().GetConstantMultiplicationFormat() + : coefficient.Denominator.ToString(); + var expandedExpression = $"new QuantityValue({numeratorExpression}, {denominatorExpression})"; + return expandedExpression; + } + + private static string GetFractionalConstantFormat(this Fraction coefficient) + { + coefficient = coefficient.Reduce(); + // making sure that neither the Numerator nor the Denominator contain a value that cannot be represented as a compiler constant + if (coefficient.Numerator >= long.MinValue && coefficient.Numerator <= long.MaxValue && coefficient.Denominator <= long.MaxValue) + { + return coefficient.GetConstantFormat(); + } + + // need to represent the fraction in terms of two terms: "a * b" + return coefficient.GetLongConstantFormat(); + } + + private static string GetConstantExpression(this Fraction coefficient, string csharpParameter) + { + if (coefficient == Fraction.One) + { + return csharpParameter; + } + + if (coefficient.Denominator.IsOne) + { + return $"{csharpParameter} * {coefficient.Numerator}"; + } + + if (coefficient.Numerator.IsOne) + { + return $"{csharpParameter} / {coefficient.Denominator}"; + } + + if (coefficient.Numerator == BigInteger.MinusOne) + { + return $"{csharpParameter} / -{coefficient.Denominator}"; + } + + return $"{csharpParameter} * new QuantityValue({coefficient.Numerator}, {coefficient.Denominator})"; + } + + private static string GetFractionalExpressionFormat(this Fraction coefficient, string csharpParameter) + { + coefficient = coefficient.Reduce(); + // making sure that neither the Numerator nor the Denominator contain a value that cannot be represented as a compiler constant + if (coefficient.Numerator >= long.MinValue && coefficient.Numerator <= long.MaxValue && coefficient.Denominator <= long.MaxValue) + { + return coefficient.GetConstantExpression(csharpParameter); + } + + // need to represent the fraction in terms of two (or more) terms: "x * a * b" + return $"{csharpParameter} * {coefficient.GetLongConstantFormat()}"; + } + + + public static string GetExpressionFormat(this CustomFunction customFunction, string csharpParameter) + { + // TODO see about redirecting these to a static method in the quantity's class which is responsible for handling the required operations (efficiently) + var mainArgument = $"({customFunction.Terms.GetExpressionFormat(csharpParameter)}).ToDouble()"; + var functionArguments = string.Join(", ", customFunction.AdditionalParameters.Prepend(mainArgument)); + return $"QuantityValue.FromDoubleRounded({customFunction.Namespace}.{customFunction.Name}({functionArguments}))"; + } + + public static string GetConstantExpressionFormat(this CustomFunction customFunction) + { + // TODO see about redirecting these to a static method in the quantity's class which is responsible for handling the required operations (efficiently) + var functionArguments = string.Join(", ", customFunction.AdditionalParameters); + return $"QuantityValue.FromDoubleRounded({customFunction.Namespace}.{customFunction.Name}({functionArguments}))"; + } + + public static string GetExponentFormat(this Fraction exponent, string csharpParameter) + { + if (exponent == Fraction.One) + { + return csharpParameter; + } + + // alternatively this could be an operator: e.g. $"({csharpParameter} ^ {exponent.ToInt32()})" + return exponent.Denominator.IsOne + ? $"QuantityValue.Pow({csharpParameter}, {exponent.ToInt32()})" + : $"QuantityValue.FromDoubleRounded(Math.Pow({csharpParameter}.ToDouble(), {exponent.ToDouble()}))"; + } + + public static string GetExpressionFormat(this ExpressionTerm term, string csharpParameter) + { + if (term.IsConstant) + { + return term.Coefficient.GetFractionalConstantFormat(); + } + + if (term is { NestedFunction: not null, Exponent.IsZero: true }) + { + return term.NestedFunction.GetConstantExpressionFormat(); + } + + var expressionFormat = term.NestedFunction is null ? csharpParameter : term.NestedFunction.GetExpressionFormat(csharpParameter); + return term.Coefficient.GetFractionalExpressionFormat(term.Exponent.GetExponentFormat(expressionFormat)); + } + + public static string GetExpressionFormat(this CompositeExpression expression, string csharpParameter) + { + return string.Join(" + ", expression.Terms.Select(x => x.GetExpressionFormat(csharpParameter))); + } + + private static string GetStringExpression(string expression, string csharpParameter, string jsonParameter = "{x}") + { + CompositeExpression compositeExpression = ExpressionEvaluator.Evaluate(expression, jsonParameter); + var expectedFormat = compositeExpression.GetExpressionFormat(csharpParameter); + return expectedFormat; + } + + public static string GetConversionExpressionFormat(this CompositeExpression expression, string csharpParameter = "value") + { + string? coefficientTermFormat = null; + string? exponentFormat = null; + string? customConversionFunctionFormat = null; + string? constantTermValue = null; + + foreach (ExpressionTerm expressionTerm in expression.Terms) + { + if (expressionTerm.IsConstant) + { + constantTermValue = expressionTerm.Coefficient.GetFractionalConstantFormat(); + } + else if (expressionTerm.Exponent == 0) + { + throw new InvalidOperationException("The ConversionExpression class does not support custom functions as the constant term."); + } + else + { + if (coefficientTermFormat is not null || exponentFormat is not null || customConversionFunctionFormat is not null) + { + throw new InvalidOperationException("The ConversionExpression class does not support more than 2 terms"); + } + + coefficientTermFormat = expressionTerm.Coefficient.GetFractionalConstantFormat(); + + if (expressionTerm.NestedFunction is not null) + { + customConversionFunctionFormat = expressionTerm.NestedFunction.GetExpressionFormat(csharpParameter); + } + + if (expressionTerm.Exponent == Fraction.One) + { + continue; + } + + if (expressionTerm.Exponent.Denominator.IsOne) + { + exponentFormat = expressionTerm.Exponent.Numerator.ToString(); + } + else if (customConversionFunctionFormat is null) + { + customConversionFunctionFormat = expressionTerm.Exponent.GetExponentFormat(csharpParameter); + } + else // create a composition between the two functions + { + customConversionFunctionFormat = expressionTerm.Exponent.GetExponentFormat(customConversionFunctionFormat); + } + } + } + + coefficientTermFormat ??= "1"; + + if (constantTermValue is not null && exponentFormat is null && customConversionFunctionFormat is null) + { + return $"new ConversionExpression({coefficientTermFormat}, {constantTermValue})"; + } + + if (customConversionFunctionFormat is not null) + { + return $"new ConversionExpression({coefficientTermFormat}, {csharpParameter} => {customConversionFunctionFormat}, {exponentFormat ?? "1"}, {constantTermValue ?? "0"})"; + } + + if (constantTermValue is not null) + { + return $"new ConversionExpression({coefficientTermFormat}, null, {exponentFormat ?? "1"}, {constantTermValue})"; + } + + if (exponentFormat is not null) + { + return $"new ConversionExpression({coefficientTermFormat}, null, {exponentFormat})"; + } + + // return $"new ConversionExpression({coefficientTermFormat})"; + return coefficientTermFormat; // using the implicit constructor from QuantityValue + } + + private static string GetConversionExpressionFormat(string expression, string csharpParameter = "value", string jsonParameter = "{x}") + { + CompositeExpression compositeExpression = ExpressionEvaluator.Evaluate(expression, jsonParameter); + var expectedFormat = compositeExpression.GetConversionExpressionFormat(csharpParameter); + return expectedFormat; + } + + /// + /// Gets the format of the conversion from the unit to the base unit. + /// + /// The unit for which to get the conversion format. + /// The C# parameter to be used in the conversion expression. + /// A string representing the format of the conversion from the unit to the base unit. + internal static string GetUnitToBaseConversionFormat(this Unit unit, string csharpParameter = "value") + { + return GetStringExpression(unit.FromUnitToBaseFunc, csharpParameter); + } + + /// + /// Gets the format of the conversion from the base unit to the specified unit. + /// + /// The unit to which the conversion format is to be obtained. + /// The C# parameter to be used in the conversion expression. + /// A string representing the format of the conversion from the base unit to the specified unit. + internal static string GetFromBaseToUnitConversionFormat(this Unit unit, string csharpParameter = "value") + { + return GetStringExpression(unit.FromBaseToUnitFunc, csharpParameter); + } + + /// + /// Gets the format of the conversion from the unit to the base unit using a ConversionExpression. + /// + /// The unit for which to get the conversion format. + /// The C# parameter to be used in the conversion expression. + /// A string representing the constructor of a ConversionExpression from the unit to the base unit. + internal static string GetUnitToBaseConversionExpressionFormat(this Unit unit, string csharpParameter = "value") + { + return GetConversionExpressionFormat(unit.FromUnitToBaseFunc, csharpParameter); + } + + /// + /// Gets the format of the conversion from the base unit to the specified unit using a ConversionExpression. + /// + /// The unit to which the conversion format is to be obtained. + /// The C# parameter to be used in the conversion expression. + /// A string representing the constructor of a ConversionExpression from the base unit to the specified unit. + internal static string GetFromBaseToUnitConversionExpressionFormat(this Unit unit, string csharpParameter = "value") + { + return GetConversionExpressionFormat(unit.FromBaseToUnitFunc, csharpParameter); + } + + /// + /// Generates a dictionary of conversion expressions for a given quantity, mapping each unit to its conversion + /// expressions with other units. + /// + /// The quantity for which conversion expressions are generated. + /// + /// An optional JSON parameter used in the evaluation of conversion expressions. Defaults to + /// "{x}". + /// + /// + /// A dictionary where each key is a unit and the value is another dictionary mapping other units to their + /// respective conversion expressions. + /// + /// + /// Thrown if the calculated conversion expression does not match the expected + /// conversion expression. + /// + internal static Dictionary> GetConversionExpressions(this Quantity quantity, string jsonParameter = "{x}") + { + var conversionsFromBase = new Dictionary(); + var conversionsToBase = new Dictionary(); + Unit baseUnit = quantity.Units.First(unit => unit.SingularName == quantity.BaseUnit); + foreach (Unit unit in quantity.Units) + { + if (unit == baseUnit) continue; + CompositeExpression conversionFromBase = conversionsFromBase[unit] = ExpressionEvaluator.Evaluate(unit.FromBaseToUnitFunc, jsonParameter); + if (conversionFromBase.Terms.Count == 1 && conversionFromBase.Degree.Abs() == Fraction.One) + { + // as long as there aren't any complex functions we can just invert the expression + conversionsToBase[unit] = conversionFromBase.SolveForY(); + } + else + { + // complex conversion functions require an explicit expression in both directions + conversionsToBase[unit] = ExpressionEvaluator.Evaluate(unit.FromUnitToBaseFunc, jsonParameter); + } + } + + var conversionsFrom = new Dictionary> { [baseUnit] = conversionsToBase }; + foreach ((Unit fromUnit, CompositeExpression expressionFromBase) in conversionsFromBase) + { + Dictionary fromUnitConversion = conversionsFrom[fromUnit] = new Dictionary(); + foreach ((Unit otherUnit, CompositeExpression expressionToBase) in conversionsToBase) + { + if (fromUnit == otherUnit) continue; + fromUnitConversion[otherUnit] = expressionFromBase.Evaluate(expressionToBase); + } + + fromUnitConversion[baseUnit] = conversionsFromBase[fromUnit]; + } + + return conversionsFrom; + } +} diff --git a/CodeGen/JsonTypes/BaseDimensions.cs b/CodeGen/JsonTypes/BaseDimensions.cs index 59f9389505..87ffc2c272 100644 --- a/CodeGen/JsonTypes/BaseDimensions.cs +++ b/CodeGen/JsonTypes/BaseDimensions.cs @@ -54,10 +54,10 @@ private static void AppendDimensionString(StringBuilder sb, string name, int val case 0: return; case 1: - sb.AppendFormat("[{0}]", name); + sb.Append(name); break; default: - sb.AppendFormat("[{0}^{1}]", name, value); + sb.Append($"{name}^{value}"); break; } } diff --git a/Directory.Packages.props b/Directory.Packages.props index 54479369db..5e553c66cf 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -3,18 +3,23 @@ true - + + - + + + - + + - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive + \ No newline at end of file diff --git a/Samples/Directory.Packages.props b/Samples/Directory.Packages.props index 3f24827b01..e04094e657 100644 --- a/Samples/Directory.Packages.props +++ b/Samples/Directory.Packages.props @@ -5,9 +5,10 @@ - + + \ No newline at end of file diff --git a/Samples/MvvmSample.Wpf/MvvmSample.Wpf/MvvmSample.Wpf.csproj b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/MvvmSample.Wpf.csproj index cb757e1ceb..515c20e6c0 100644 --- a/Samples/MvvmSample.Wpf/MvvmSample.Wpf/MvvmSample.Wpf.csproj +++ b/Samples/MvvmSample.Wpf/MvvmSample.Wpf/MvvmSample.Wpf.csproj @@ -19,7 +19,12 @@ - + + + + + + \ No newline at end of file diff --git a/Samples/Nuget.config b/Samples/Nuget.config new file mode 100644 index 0000000000..d92d9fff56 --- /dev/null +++ b/Samples/Nuget.config @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Samples/Samples.slnx b/Samples/Samples.slnx index 1fc01829b9..abd1c9b970 100644 --- a/Samples/Samples.slnx +++ b/Samples/Samples.slnx @@ -17,4 +17,5 @@ + diff --git a/Samples/UnitConverter.Console/Program.cs b/Samples/UnitConverter.Console/Program.cs index 7ba55aef09..86d77a015f 100644 --- a/Samples/UnitConverter.Console/Program.cs +++ b/Samples/UnitConverter.Console/Program.cs @@ -1,4 +1,5 @@ using UnitsNet; +using UnitsNet.Units; using static System.Console; using static UnitsNet.Units.LengthUnit; diff --git a/Samples/UnitConverter.Console/UnitConverter.Console.csproj b/Samples/UnitConverter.Console/UnitConverter.Console.csproj index 3f3de72140..9c22ea83c5 100644 --- a/Samples/UnitConverter.Console/UnitConverter.Console.csproj +++ b/Samples/UnitConverter.Console/UnitConverter.Console.csproj @@ -1,14 +1,18 @@ - + Exe - net8.0 + net9.0 enable enable - - + + + + + + \ No newline at end of file diff --git a/Samples/UnitConverter.Wpf/UnitConverter.Wpf/IMainWindowVm.cs b/Samples/UnitConverter.Wpf/UnitConverter.Wpf/IMainWindowVm.cs index c2ed86fb67..e696c1fbc9 100644 --- a/Samples/UnitConverter.Wpf/UnitConverter.Wpf/IMainWindowVm.cs +++ b/Samples/UnitConverter.Wpf/UnitConverter.Wpf/IMainWindowVm.cs @@ -23,8 +23,8 @@ public interface IMainWindowVm : INotifyPropertyChanged string FromHeader { get; } string ToHeader { get; } - double FromValue { get; set; } - double ToValue { get; } + QuantityValue FromValue { get; set; } + QuantityValue ToValue { get; } ICommand SwapCommand { get; } } } diff --git a/Samples/UnitConverter.Wpf/UnitConverter.Wpf/MainWindow.xaml b/Samples/UnitConverter.Wpf/UnitConverter.Wpf/MainWindow.xaml index 81d8491452..fb6d0e18ef 100644 --- a/Samples/UnitConverter.Wpf/UnitConverter.Wpf/MainWindow.xaml +++ b/Samples/UnitConverter.Wpf/UnitConverter.Wpf/MainWindow.xaml @@ -7,15 +7,12 @@ xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:wpf="clr-namespace:UnitsNet.Samples.UnitConverter.Wpf" mc:Ignorable="d" - WindowStartupLocation="CenterScreen" - Title="UnitsNet - WPF unit converter sample app" Height="800" Width="800" - d:DesignHeight="600" d:DesignWidth="600" + Title="UnitsNet - WPF unit converter sample app" Height="600" Width="800" d:DataContext="{d:DesignInstance wpf:MainWindowDesignVm, IsDesignTimeCreatable=True}"> - @@ -32,7 +29,7 @@ SelectionChanged="Selector_OnSelectionChanged" /> - + - + - + + + + + + + Text="{Binding FromValue, StringFormat=G35, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/> - + public static class NumberToAbsorbedDoseOfIonizingRadiationExtensions { - /// + /// public static AbsorbedDoseOfIonizingRadiation Centigrays(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AbsorbedDoseOfIonizingRadiation.FromCentigrays(double.CreateChecked(value)); + => AbsorbedDoseOfIonizingRadiation.FromCentigrays(QuantityValue.CreateChecked(value)); #else , IConvertible - => AbsorbedDoseOfIonizingRadiation.FromCentigrays(value.ToDouble(null)); + => AbsorbedDoseOfIonizingRadiation.FromCentigrays(value.ToQuantityValue()); #endif - /// + /// public static AbsorbedDoseOfIonizingRadiation Decigrays(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AbsorbedDoseOfIonizingRadiation.FromDecigrays(double.CreateChecked(value)); + => AbsorbedDoseOfIonizingRadiation.FromDecigrays(QuantityValue.CreateChecked(value)); #else , IConvertible - => AbsorbedDoseOfIonizingRadiation.FromDecigrays(value.ToDouble(null)); + => AbsorbedDoseOfIonizingRadiation.FromDecigrays(value.ToQuantityValue()); #endif - /// + /// public static AbsorbedDoseOfIonizingRadiation Femtograys(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AbsorbedDoseOfIonizingRadiation.FromFemtograys(double.CreateChecked(value)); + => AbsorbedDoseOfIonizingRadiation.FromFemtograys(QuantityValue.CreateChecked(value)); #else , IConvertible - => AbsorbedDoseOfIonizingRadiation.FromFemtograys(value.ToDouble(null)); + => AbsorbedDoseOfIonizingRadiation.FromFemtograys(value.ToQuantityValue()); #endif - /// + /// public static AbsorbedDoseOfIonizingRadiation Gigagrays(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AbsorbedDoseOfIonizingRadiation.FromGigagrays(double.CreateChecked(value)); + => AbsorbedDoseOfIonizingRadiation.FromGigagrays(QuantityValue.CreateChecked(value)); #else , IConvertible - => AbsorbedDoseOfIonizingRadiation.FromGigagrays(value.ToDouble(null)); + => AbsorbedDoseOfIonizingRadiation.FromGigagrays(value.ToQuantityValue()); #endif - /// + /// public static AbsorbedDoseOfIonizingRadiation Grays(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AbsorbedDoseOfIonizingRadiation.FromGrays(double.CreateChecked(value)); + => AbsorbedDoseOfIonizingRadiation.FromGrays(QuantityValue.CreateChecked(value)); #else , IConvertible - => AbsorbedDoseOfIonizingRadiation.FromGrays(value.ToDouble(null)); + => AbsorbedDoseOfIonizingRadiation.FromGrays(value.ToQuantityValue()); #endif - /// + /// public static AbsorbedDoseOfIonizingRadiation Kilograys(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AbsorbedDoseOfIonizingRadiation.FromKilograys(double.CreateChecked(value)); + => AbsorbedDoseOfIonizingRadiation.FromKilograys(QuantityValue.CreateChecked(value)); #else , IConvertible - => AbsorbedDoseOfIonizingRadiation.FromKilograys(value.ToDouble(null)); + => AbsorbedDoseOfIonizingRadiation.FromKilograys(value.ToQuantityValue()); #endif - /// + /// public static AbsorbedDoseOfIonizingRadiation Kilorads(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AbsorbedDoseOfIonizingRadiation.FromKilorads(double.CreateChecked(value)); + => AbsorbedDoseOfIonizingRadiation.FromKilorads(QuantityValue.CreateChecked(value)); #else , IConvertible - => AbsorbedDoseOfIonizingRadiation.FromKilorads(value.ToDouble(null)); + => AbsorbedDoseOfIonizingRadiation.FromKilorads(value.ToQuantityValue()); #endif - /// + /// public static AbsorbedDoseOfIonizingRadiation Megagrays(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AbsorbedDoseOfIonizingRadiation.FromMegagrays(double.CreateChecked(value)); + => AbsorbedDoseOfIonizingRadiation.FromMegagrays(QuantityValue.CreateChecked(value)); #else , IConvertible - => AbsorbedDoseOfIonizingRadiation.FromMegagrays(value.ToDouble(null)); + => AbsorbedDoseOfIonizingRadiation.FromMegagrays(value.ToQuantityValue()); #endif - /// + /// public static AbsorbedDoseOfIonizingRadiation Megarads(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AbsorbedDoseOfIonizingRadiation.FromMegarads(double.CreateChecked(value)); + => AbsorbedDoseOfIonizingRadiation.FromMegarads(QuantityValue.CreateChecked(value)); #else , IConvertible - => AbsorbedDoseOfIonizingRadiation.FromMegarads(value.ToDouble(null)); + => AbsorbedDoseOfIonizingRadiation.FromMegarads(value.ToQuantityValue()); #endif - /// + /// public static AbsorbedDoseOfIonizingRadiation Micrograys(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AbsorbedDoseOfIonizingRadiation.FromMicrograys(double.CreateChecked(value)); + => AbsorbedDoseOfIonizingRadiation.FromMicrograys(QuantityValue.CreateChecked(value)); #else , IConvertible - => AbsorbedDoseOfIonizingRadiation.FromMicrograys(value.ToDouble(null)); + => AbsorbedDoseOfIonizingRadiation.FromMicrograys(value.ToQuantityValue()); #endif - /// + /// public static AbsorbedDoseOfIonizingRadiation Milligrays(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AbsorbedDoseOfIonizingRadiation.FromMilligrays(double.CreateChecked(value)); + => AbsorbedDoseOfIonizingRadiation.FromMilligrays(QuantityValue.CreateChecked(value)); #else , IConvertible - => AbsorbedDoseOfIonizingRadiation.FromMilligrays(value.ToDouble(null)); + => AbsorbedDoseOfIonizingRadiation.FromMilligrays(value.ToQuantityValue()); #endif - /// + /// public static AbsorbedDoseOfIonizingRadiation Millirads(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AbsorbedDoseOfIonizingRadiation.FromMillirads(double.CreateChecked(value)); + => AbsorbedDoseOfIonizingRadiation.FromMillirads(QuantityValue.CreateChecked(value)); #else , IConvertible - => AbsorbedDoseOfIonizingRadiation.FromMillirads(value.ToDouble(null)); + => AbsorbedDoseOfIonizingRadiation.FromMillirads(value.ToQuantityValue()); #endif - /// + /// public static AbsorbedDoseOfIonizingRadiation Nanograys(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AbsorbedDoseOfIonizingRadiation.FromNanograys(double.CreateChecked(value)); + => AbsorbedDoseOfIonizingRadiation.FromNanograys(QuantityValue.CreateChecked(value)); #else , IConvertible - => AbsorbedDoseOfIonizingRadiation.FromNanograys(value.ToDouble(null)); + => AbsorbedDoseOfIonizingRadiation.FromNanograys(value.ToQuantityValue()); #endif - /// + /// public static AbsorbedDoseOfIonizingRadiation Petagrays(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AbsorbedDoseOfIonizingRadiation.FromPetagrays(double.CreateChecked(value)); + => AbsorbedDoseOfIonizingRadiation.FromPetagrays(QuantityValue.CreateChecked(value)); #else , IConvertible - => AbsorbedDoseOfIonizingRadiation.FromPetagrays(value.ToDouble(null)); + => AbsorbedDoseOfIonizingRadiation.FromPetagrays(value.ToQuantityValue()); #endif - /// + /// public static AbsorbedDoseOfIonizingRadiation Picograys(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AbsorbedDoseOfIonizingRadiation.FromPicograys(double.CreateChecked(value)); + => AbsorbedDoseOfIonizingRadiation.FromPicograys(QuantityValue.CreateChecked(value)); #else , IConvertible - => AbsorbedDoseOfIonizingRadiation.FromPicograys(value.ToDouble(null)); + => AbsorbedDoseOfIonizingRadiation.FromPicograys(value.ToQuantityValue()); #endif - /// + /// public static AbsorbedDoseOfIonizingRadiation Rads(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AbsorbedDoseOfIonizingRadiation.FromRads(double.CreateChecked(value)); + => AbsorbedDoseOfIonizingRadiation.FromRads(QuantityValue.CreateChecked(value)); #else , IConvertible - => AbsorbedDoseOfIonizingRadiation.FromRads(value.ToDouble(null)); + => AbsorbedDoseOfIonizingRadiation.FromRads(value.ToQuantityValue()); #endif - /// + /// public static AbsorbedDoseOfIonizingRadiation Teragrays(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AbsorbedDoseOfIonizingRadiation.FromTeragrays(double.CreateChecked(value)); + => AbsorbedDoseOfIonizingRadiation.FromTeragrays(QuantityValue.CreateChecked(value)); #else , IConvertible - => AbsorbedDoseOfIonizingRadiation.FromTeragrays(value.ToDouble(null)); + => AbsorbedDoseOfIonizingRadiation.FromTeragrays(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToAccelerationExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToAccelerationExtensions.g.cs index c0eb105add..8dcc9ec0da 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToAccelerationExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToAccelerationExtensions.g.cs @@ -32,158 +32,158 @@ namespace UnitsNet.NumberExtensions.NumberToAcceleration /// public static class NumberToAccelerationExtensions { - /// + /// public static Acceleration CentimetersPerSecondSquared(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Acceleration.FromCentimetersPerSecondSquared(double.CreateChecked(value)); + => Acceleration.FromCentimetersPerSecondSquared(QuantityValue.CreateChecked(value)); #else , IConvertible - => Acceleration.FromCentimetersPerSecondSquared(value.ToDouble(null)); + => Acceleration.FromCentimetersPerSecondSquared(value.ToQuantityValue()); #endif - /// + /// public static Acceleration DecimetersPerSecondSquared(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Acceleration.FromDecimetersPerSecondSquared(double.CreateChecked(value)); + => Acceleration.FromDecimetersPerSecondSquared(QuantityValue.CreateChecked(value)); #else , IConvertible - => Acceleration.FromDecimetersPerSecondSquared(value.ToDouble(null)); + => Acceleration.FromDecimetersPerSecondSquared(value.ToQuantityValue()); #endif - /// + /// public static Acceleration FeetPerSecondSquared(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Acceleration.FromFeetPerSecondSquared(double.CreateChecked(value)); + => Acceleration.FromFeetPerSecondSquared(QuantityValue.CreateChecked(value)); #else , IConvertible - => Acceleration.FromFeetPerSecondSquared(value.ToDouble(null)); + => Acceleration.FromFeetPerSecondSquared(value.ToQuantityValue()); #endif - /// + /// public static Acceleration InchesPerSecondSquared(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Acceleration.FromInchesPerSecondSquared(double.CreateChecked(value)); + => Acceleration.FromInchesPerSecondSquared(QuantityValue.CreateChecked(value)); #else , IConvertible - => Acceleration.FromInchesPerSecondSquared(value.ToDouble(null)); + => Acceleration.FromInchesPerSecondSquared(value.ToQuantityValue()); #endif - /// + /// public static Acceleration KilometersPerSecondSquared(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Acceleration.FromKilometersPerSecondSquared(double.CreateChecked(value)); + => Acceleration.FromKilometersPerSecondSquared(QuantityValue.CreateChecked(value)); #else , IConvertible - => Acceleration.FromKilometersPerSecondSquared(value.ToDouble(null)); + => Acceleration.FromKilometersPerSecondSquared(value.ToQuantityValue()); #endif - /// + /// public static Acceleration KnotsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Acceleration.FromKnotsPerHour(double.CreateChecked(value)); + => Acceleration.FromKnotsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Acceleration.FromKnotsPerHour(value.ToDouble(null)); + => Acceleration.FromKnotsPerHour(value.ToQuantityValue()); #endif - /// + /// public static Acceleration KnotsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Acceleration.FromKnotsPerMinute(double.CreateChecked(value)); + => Acceleration.FromKnotsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => Acceleration.FromKnotsPerMinute(value.ToDouble(null)); + => Acceleration.FromKnotsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static Acceleration KnotsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Acceleration.FromKnotsPerSecond(double.CreateChecked(value)); + => Acceleration.FromKnotsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Acceleration.FromKnotsPerSecond(value.ToDouble(null)); + => Acceleration.FromKnotsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static Acceleration MetersPerSecondSquared(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Acceleration.FromMetersPerSecondSquared(double.CreateChecked(value)); + => Acceleration.FromMetersPerSecondSquared(QuantityValue.CreateChecked(value)); #else , IConvertible - => Acceleration.FromMetersPerSecondSquared(value.ToDouble(null)); + => Acceleration.FromMetersPerSecondSquared(value.ToQuantityValue()); #endif - /// + /// public static Acceleration MicrometersPerSecondSquared(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Acceleration.FromMicrometersPerSecondSquared(double.CreateChecked(value)); + => Acceleration.FromMicrometersPerSecondSquared(QuantityValue.CreateChecked(value)); #else , IConvertible - => Acceleration.FromMicrometersPerSecondSquared(value.ToDouble(null)); + => Acceleration.FromMicrometersPerSecondSquared(value.ToQuantityValue()); #endif - /// + /// public static Acceleration MillimetersPerSecondSquared(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Acceleration.FromMillimetersPerSecondSquared(double.CreateChecked(value)); + => Acceleration.FromMillimetersPerSecondSquared(QuantityValue.CreateChecked(value)); #else , IConvertible - => Acceleration.FromMillimetersPerSecondSquared(value.ToDouble(null)); + => Acceleration.FromMillimetersPerSecondSquared(value.ToQuantityValue()); #endif - /// + /// public static Acceleration MillistandardGravity(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Acceleration.FromMillistandardGravity(double.CreateChecked(value)); + => Acceleration.FromMillistandardGravity(QuantityValue.CreateChecked(value)); #else , IConvertible - => Acceleration.FromMillistandardGravity(value.ToDouble(null)); + => Acceleration.FromMillistandardGravity(value.ToQuantityValue()); #endif - /// + /// public static Acceleration NanometersPerSecondSquared(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Acceleration.FromNanometersPerSecondSquared(double.CreateChecked(value)); + => Acceleration.FromNanometersPerSecondSquared(QuantityValue.CreateChecked(value)); #else , IConvertible - => Acceleration.FromNanometersPerSecondSquared(value.ToDouble(null)); + => Acceleration.FromNanometersPerSecondSquared(value.ToQuantityValue()); #endif - /// + /// public static Acceleration StandardGravity(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Acceleration.FromStandardGravity(double.CreateChecked(value)); + => Acceleration.FromStandardGravity(QuantityValue.CreateChecked(value)); #else , IConvertible - => Acceleration.FromStandardGravity(value.ToDouble(null)); + => Acceleration.FromStandardGravity(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToAmountOfSubstanceExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToAmountOfSubstanceExtensions.g.cs index d68957f638..8d9555a0bc 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToAmountOfSubstanceExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToAmountOfSubstanceExtensions.g.cs @@ -32,191 +32,191 @@ namespace UnitsNet.NumberExtensions.NumberToAmountOfSubstance /// public static class NumberToAmountOfSubstanceExtensions { - /// + /// public static AmountOfSubstance Centimoles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmountOfSubstance.FromCentimoles(double.CreateChecked(value)); + => AmountOfSubstance.FromCentimoles(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmountOfSubstance.FromCentimoles(value.ToDouble(null)); + => AmountOfSubstance.FromCentimoles(value.ToQuantityValue()); #endif - /// + /// public static AmountOfSubstance CentipoundMoles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmountOfSubstance.FromCentipoundMoles(double.CreateChecked(value)); + => AmountOfSubstance.FromCentipoundMoles(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmountOfSubstance.FromCentipoundMoles(value.ToDouble(null)); + => AmountOfSubstance.FromCentipoundMoles(value.ToQuantityValue()); #endif - /// + /// public static AmountOfSubstance Decimoles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmountOfSubstance.FromDecimoles(double.CreateChecked(value)); + => AmountOfSubstance.FromDecimoles(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmountOfSubstance.FromDecimoles(value.ToDouble(null)); + => AmountOfSubstance.FromDecimoles(value.ToQuantityValue()); #endif - /// + /// public static AmountOfSubstance DecipoundMoles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmountOfSubstance.FromDecipoundMoles(double.CreateChecked(value)); + => AmountOfSubstance.FromDecipoundMoles(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmountOfSubstance.FromDecipoundMoles(value.ToDouble(null)); + => AmountOfSubstance.FromDecipoundMoles(value.ToQuantityValue()); #endif - /// + /// public static AmountOfSubstance Femtomoles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmountOfSubstance.FromFemtomoles(double.CreateChecked(value)); + => AmountOfSubstance.FromFemtomoles(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmountOfSubstance.FromFemtomoles(value.ToDouble(null)); + => AmountOfSubstance.FromFemtomoles(value.ToQuantityValue()); #endif - /// + /// public static AmountOfSubstance Kilomoles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmountOfSubstance.FromKilomoles(double.CreateChecked(value)); + => AmountOfSubstance.FromKilomoles(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmountOfSubstance.FromKilomoles(value.ToDouble(null)); + => AmountOfSubstance.FromKilomoles(value.ToQuantityValue()); #endif - /// + /// public static AmountOfSubstance KilopoundMoles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmountOfSubstance.FromKilopoundMoles(double.CreateChecked(value)); + => AmountOfSubstance.FromKilopoundMoles(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmountOfSubstance.FromKilopoundMoles(value.ToDouble(null)); + => AmountOfSubstance.FromKilopoundMoles(value.ToQuantityValue()); #endif - /// + /// public static AmountOfSubstance Megamoles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmountOfSubstance.FromMegamoles(double.CreateChecked(value)); + => AmountOfSubstance.FromMegamoles(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmountOfSubstance.FromMegamoles(value.ToDouble(null)); + => AmountOfSubstance.FromMegamoles(value.ToQuantityValue()); #endif - /// + /// public static AmountOfSubstance Micromoles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmountOfSubstance.FromMicromoles(double.CreateChecked(value)); + => AmountOfSubstance.FromMicromoles(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmountOfSubstance.FromMicromoles(value.ToDouble(null)); + => AmountOfSubstance.FromMicromoles(value.ToQuantityValue()); #endif - /// + /// public static AmountOfSubstance MicropoundMoles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmountOfSubstance.FromMicropoundMoles(double.CreateChecked(value)); + => AmountOfSubstance.FromMicropoundMoles(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmountOfSubstance.FromMicropoundMoles(value.ToDouble(null)); + => AmountOfSubstance.FromMicropoundMoles(value.ToQuantityValue()); #endif - /// + /// public static AmountOfSubstance Millimoles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmountOfSubstance.FromMillimoles(double.CreateChecked(value)); + => AmountOfSubstance.FromMillimoles(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmountOfSubstance.FromMillimoles(value.ToDouble(null)); + => AmountOfSubstance.FromMillimoles(value.ToQuantityValue()); #endif - /// + /// public static AmountOfSubstance MillipoundMoles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmountOfSubstance.FromMillipoundMoles(double.CreateChecked(value)); + => AmountOfSubstance.FromMillipoundMoles(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmountOfSubstance.FromMillipoundMoles(value.ToDouble(null)); + => AmountOfSubstance.FromMillipoundMoles(value.ToQuantityValue()); #endif - /// + /// public static AmountOfSubstance Moles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmountOfSubstance.FromMoles(double.CreateChecked(value)); + => AmountOfSubstance.FromMoles(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmountOfSubstance.FromMoles(value.ToDouble(null)); + => AmountOfSubstance.FromMoles(value.ToQuantityValue()); #endif - /// + /// public static AmountOfSubstance Nanomoles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmountOfSubstance.FromNanomoles(double.CreateChecked(value)); + => AmountOfSubstance.FromNanomoles(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmountOfSubstance.FromNanomoles(value.ToDouble(null)); + => AmountOfSubstance.FromNanomoles(value.ToQuantityValue()); #endif - /// + /// public static AmountOfSubstance NanopoundMoles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmountOfSubstance.FromNanopoundMoles(double.CreateChecked(value)); + => AmountOfSubstance.FromNanopoundMoles(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmountOfSubstance.FromNanopoundMoles(value.ToDouble(null)); + => AmountOfSubstance.FromNanopoundMoles(value.ToQuantityValue()); #endif - /// + /// public static AmountOfSubstance Picomoles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmountOfSubstance.FromPicomoles(double.CreateChecked(value)); + => AmountOfSubstance.FromPicomoles(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmountOfSubstance.FromPicomoles(value.ToDouble(null)); + => AmountOfSubstance.FromPicomoles(value.ToQuantityValue()); #endif - /// + /// public static AmountOfSubstance PoundMoles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmountOfSubstance.FromPoundMoles(double.CreateChecked(value)); + => AmountOfSubstance.FromPoundMoles(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmountOfSubstance.FromPoundMoles(value.ToDouble(null)); + => AmountOfSubstance.FromPoundMoles(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToAmplitudeRatioExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToAmplitudeRatioExtensions.g.cs index 57d41c7817..59186c1a1f 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToAmplitudeRatioExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToAmplitudeRatioExtensions.g.cs @@ -32,48 +32,48 @@ namespace UnitsNet.NumberExtensions.NumberToAmplitudeRatio /// public static class NumberToAmplitudeRatioExtensions { - /// + /// public static AmplitudeRatio DecibelMicrovolts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmplitudeRatio.FromDecibelMicrovolts(double.CreateChecked(value)); + => AmplitudeRatio.FromDecibelMicrovolts(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmplitudeRatio.FromDecibelMicrovolts(value.ToDouble(null)); + => AmplitudeRatio.FromDecibelMicrovolts(value.ToQuantityValue()); #endif - /// + /// public static AmplitudeRatio DecibelMillivolts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmplitudeRatio.FromDecibelMillivolts(double.CreateChecked(value)); + => AmplitudeRatio.FromDecibelMillivolts(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmplitudeRatio.FromDecibelMillivolts(value.ToDouble(null)); + => AmplitudeRatio.FromDecibelMillivolts(value.ToQuantityValue()); #endif - /// + /// public static AmplitudeRatio DecibelsUnloaded(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmplitudeRatio.FromDecibelsUnloaded(double.CreateChecked(value)); + => AmplitudeRatio.FromDecibelsUnloaded(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmplitudeRatio.FromDecibelsUnloaded(value.ToDouble(null)); + => AmplitudeRatio.FromDecibelsUnloaded(value.ToQuantityValue()); #endif - /// + /// public static AmplitudeRatio DecibelVolts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AmplitudeRatio.FromDecibelVolts(double.CreateChecked(value)); + => AmplitudeRatio.FromDecibelVolts(QuantityValue.CreateChecked(value)); #else , IConvertible - => AmplitudeRatio.FromDecibelVolts(value.ToDouble(null)); + => AmplitudeRatio.FromDecibelVolts(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToAngleExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToAngleExtensions.g.cs index 94270005db..c766192414 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToAngleExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToAngleExtensions.g.cs @@ -32,169 +32,169 @@ namespace UnitsNet.NumberExtensions.NumberToAngle /// public static class NumberToAngleExtensions { - /// + /// public static Angle Arcminutes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Angle.FromArcminutes(double.CreateChecked(value)); + => Angle.FromArcminutes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Angle.FromArcminutes(value.ToDouble(null)); + => Angle.FromArcminutes(value.ToQuantityValue()); #endif - /// + /// public static Angle Arcseconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Angle.FromArcseconds(double.CreateChecked(value)); + => Angle.FromArcseconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Angle.FromArcseconds(value.ToDouble(null)); + => Angle.FromArcseconds(value.ToQuantityValue()); #endif - /// + /// public static Angle Centiradians(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Angle.FromCentiradians(double.CreateChecked(value)); + => Angle.FromCentiradians(QuantityValue.CreateChecked(value)); #else , IConvertible - => Angle.FromCentiradians(value.ToDouble(null)); + => Angle.FromCentiradians(value.ToQuantityValue()); #endif - /// + /// public static Angle Deciradians(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Angle.FromDeciradians(double.CreateChecked(value)); + => Angle.FromDeciradians(QuantityValue.CreateChecked(value)); #else , IConvertible - => Angle.FromDeciradians(value.ToDouble(null)); + => Angle.FromDeciradians(value.ToQuantityValue()); #endif - /// + /// public static Angle Degrees(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Angle.FromDegrees(double.CreateChecked(value)); + => Angle.FromDegrees(QuantityValue.CreateChecked(value)); #else , IConvertible - => Angle.FromDegrees(value.ToDouble(null)); + => Angle.FromDegrees(value.ToQuantityValue()); #endif - /// + /// public static Angle Gradians(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Angle.FromGradians(double.CreateChecked(value)); + => Angle.FromGradians(QuantityValue.CreateChecked(value)); #else , IConvertible - => Angle.FromGradians(value.ToDouble(null)); + => Angle.FromGradians(value.ToQuantityValue()); #endif - /// + /// public static Angle Microdegrees(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Angle.FromMicrodegrees(double.CreateChecked(value)); + => Angle.FromMicrodegrees(QuantityValue.CreateChecked(value)); #else , IConvertible - => Angle.FromMicrodegrees(value.ToDouble(null)); + => Angle.FromMicrodegrees(value.ToQuantityValue()); #endif - /// + /// public static Angle Microradians(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Angle.FromMicroradians(double.CreateChecked(value)); + => Angle.FromMicroradians(QuantityValue.CreateChecked(value)); #else , IConvertible - => Angle.FromMicroradians(value.ToDouble(null)); + => Angle.FromMicroradians(value.ToQuantityValue()); #endif - /// + /// public static Angle Millidegrees(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Angle.FromMillidegrees(double.CreateChecked(value)); + => Angle.FromMillidegrees(QuantityValue.CreateChecked(value)); #else , IConvertible - => Angle.FromMillidegrees(value.ToDouble(null)); + => Angle.FromMillidegrees(value.ToQuantityValue()); #endif - /// + /// public static Angle Milliradians(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Angle.FromMilliradians(double.CreateChecked(value)); + => Angle.FromMilliradians(QuantityValue.CreateChecked(value)); #else , IConvertible - => Angle.FromMilliradians(value.ToDouble(null)); + => Angle.FromMilliradians(value.ToQuantityValue()); #endif - /// + /// public static Angle Nanodegrees(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Angle.FromNanodegrees(double.CreateChecked(value)); + => Angle.FromNanodegrees(QuantityValue.CreateChecked(value)); #else , IConvertible - => Angle.FromNanodegrees(value.ToDouble(null)); + => Angle.FromNanodegrees(value.ToQuantityValue()); #endif - /// + /// public static Angle Nanoradians(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Angle.FromNanoradians(double.CreateChecked(value)); + => Angle.FromNanoradians(QuantityValue.CreateChecked(value)); #else , IConvertible - => Angle.FromNanoradians(value.ToDouble(null)); + => Angle.FromNanoradians(value.ToQuantityValue()); #endif - /// + /// public static Angle NatoMils(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Angle.FromNatoMils(double.CreateChecked(value)); + => Angle.FromNatoMils(QuantityValue.CreateChecked(value)); #else , IConvertible - => Angle.FromNatoMils(value.ToDouble(null)); + => Angle.FromNatoMils(value.ToQuantityValue()); #endif - /// + /// public static Angle Radians(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Angle.FromRadians(double.CreateChecked(value)); + => Angle.FromRadians(QuantityValue.CreateChecked(value)); #else , IConvertible - => Angle.FromRadians(value.ToDouble(null)); + => Angle.FromRadians(value.ToQuantityValue()); #endif - /// + /// public static Angle Revolutions(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Angle.FromRevolutions(double.CreateChecked(value)); + => Angle.FromRevolutions(QuantityValue.CreateChecked(value)); #else , IConvertible - => Angle.FromRevolutions(value.ToDouble(null)); + => Angle.FromRevolutions(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToAreaDensityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToAreaDensityExtensions.g.cs index 0ce7edeee7..38257e1c7c 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToAreaDensityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToAreaDensityExtensions.g.cs @@ -32,37 +32,37 @@ namespace UnitsNet.NumberExtensions.NumberToAreaDensity /// public static class NumberToAreaDensityExtensions { - /// + /// public static AreaDensity GramsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AreaDensity.FromGramsPerSquareMeter(double.CreateChecked(value)); + => AreaDensity.FromGramsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => AreaDensity.FromGramsPerSquareMeter(value.ToDouble(null)); + => AreaDensity.FromGramsPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static AreaDensity KilogramsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AreaDensity.FromKilogramsPerSquareMeter(double.CreateChecked(value)); + => AreaDensity.FromKilogramsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => AreaDensity.FromKilogramsPerSquareMeter(value.ToDouble(null)); + => AreaDensity.FromKilogramsPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static AreaDensity MilligramsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AreaDensity.FromMilligramsPerSquareMeter(double.CreateChecked(value)); + => AreaDensity.FromMilligramsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => AreaDensity.FromMilligramsPerSquareMeter(value.ToDouble(null)); + => AreaDensity.FromMilligramsPerSquareMeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToAreaExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToAreaExtensions.g.cs index 246fec606f..f253ba26bb 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToAreaExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToAreaExtensions.g.cs @@ -32,158 +32,158 @@ namespace UnitsNet.NumberExtensions.NumberToArea /// public static class NumberToAreaExtensions { - /// + /// public static Area Acres(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Area.FromAcres(double.CreateChecked(value)); + => Area.FromAcres(QuantityValue.CreateChecked(value)); #else , IConvertible - => Area.FromAcres(value.ToDouble(null)); + => Area.FromAcres(value.ToQuantityValue()); #endif - /// + /// public static Area Hectares(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Area.FromHectares(double.CreateChecked(value)); + => Area.FromHectares(QuantityValue.CreateChecked(value)); #else , IConvertible - => Area.FromHectares(value.ToDouble(null)); + => Area.FromHectares(value.ToQuantityValue()); #endif - /// + /// public static Area SquareCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Area.FromSquareCentimeters(double.CreateChecked(value)); + => Area.FromSquareCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Area.FromSquareCentimeters(value.ToDouble(null)); + => Area.FromSquareCentimeters(value.ToQuantityValue()); #endif - /// + /// public static Area SquareDecimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Area.FromSquareDecimeters(double.CreateChecked(value)); + => Area.FromSquareDecimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Area.FromSquareDecimeters(value.ToDouble(null)); + => Area.FromSquareDecimeters(value.ToQuantityValue()); #endif - /// + /// public static Area SquareFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Area.FromSquareFeet(double.CreateChecked(value)); + => Area.FromSquareFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => Area.FromSquareFeet(value.ToDouble(null)); + => Area.FromSquareFeet(value.ToQuantityValue()); #endif - /// + /// public static Area SquareInches(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Area.FromSquareInches(double.CreateChecked(value)); + => Area.FromSquareInches(QuantityValue.CreateChecked(value)); #else , IConvertible - => Area.FromSquareInches(value.ToDouble(null)); + => Area.FromSquareInches(value.ToQuantityValue()); #endif - /// + /// public static Area SquareKilometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Area.FromSquareKilometers(double.CreateChecked(value)); + => Area.FromSquareKilometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => Area.FromSquareKilometers(value.ToDouble(null)); + => Area.FromSquareKilometers(value.ToQuantityValue()); #endif - /// + /// public static Area SquareMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Area.FromSquareMeters(double.CreateChecked(value)); + => Area.FromSquareMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Area.FromSquareMeters(value.ToDouble(null)); + => Area.FromSquareMeters(value.ToQuantityValue()); #endif - /// + /// public static Area SquareMicrometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Area.FromSquareMicrometers(double.CreateChecked(value)); + => Area.FromSquareMicrometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => Area.FromSquareMicrometers(value.ToDouble(null)); + => Area.FromSquareMicrometers(value.ToQuantityValue()); #endif - /// + /// public static Area SquareMiles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Area.FromSquareMiles(double.CreateChecked(value)); + => Area.FromSquareMiles(QuantityValue.CreateChecked(value)); #else , IConvertible - => Area.FromSquareMiles(value.ToDouble(null)); + => Area.FromSquareMiles(value.ToQuantityValue()); #endif - /// + /// public static Area SquareMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Area.FromSquareMillimeters(double.CreateChecked(value)); + => Area.FromSquareMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Area.FromSquareMillimeters(value.ToDouble(null)); + => Area.FromSquareMillimeters(value.ToQuantityValue()); #endif - /// + /// public static Area SquareNauticalMiles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Area.FromSquareNauticalMiles(double.CreateChecked(value)); + => Area.FromSquareNauticalMiles(QuantityValue.CreateChecked(value)); #else , IConvertible - => Area.FromSquareNauticalMiles(value.ToDouble(null)); + => Area.FromSquareNauticalMiles(value.ToQuantityValue()); #endif - /// + /// public static Area SquareYards(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Area.FromSquareYards(double.CreateChecked(value)); + => Area.FromSquareYards(QuantityValue.CreateChecked(value)); #else , IConvertible - => Area.FromSquareYards(value.ToDouble(null)); + => Area.FromSquareYards(value.ToQuantityValue()); #endif - /// + /// public static Area UsSurveySquareFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Area.FromUsSurveySquareFeet(double.CreateChecked(value)); + => Area.FromUsSurveySquareFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => Area.FromUsSurveySquareFeet(value.ToDouble(null)); + => Area.FromUsSurveySquareFeet(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToAreaMomentOfInertiaExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToAreaMomentOfInertiaExtensions.g.cs index b48728ea88..c330f50527 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToAreaMomentOfInertiaExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToAreaMomentOfInertiaExtensions.g.cs @@ -32,70 +32,70 @@ namespace UnitsNet.NumberExtensions.NumberToAreaMomentOfInertia /// public static class NumberToAreaMomentOfInertiaExtensions { - /// + /// public static AreaMomentOfInertia CentimetersToTheFourth(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AreaMomentOfInertia.FromCentimetersToTheFourth(double.CreateChecked(value)); + => AreaMomentOfInertia.FromCentimetersToTheFourth(QuantityValue.CreateChecked(value)); #else , IConvertible - => AreaMomentOfInertia.FromCentimetersToTheFourth(value.ToDouble(null)); + => AreaMomentOfInertia.FromCentimetersToTheFourth(value.ToQuantityValue()); #endif - /// + /// public static AreaMomentOfInertia DecimetersToTheFourth(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AreaMomentOfInertia.FromDecimetersToTheFourth(double.CreateChecked(value)); + => AreaMomentOfInertia.FromDecimetersToTheFourth(QuantityValue.CreateChecked(value)); #else , IConvertible - => AreaMomentOfInertia.FromDecimetersToTheFourth(value.ToDouble(null)); + => AreaMomentOfInertia.FromDecimetersToTheFourth(value.ToQuantityValue()); #endif - /// + /// public static AreaMomentOfInertia FeetToTheFourth(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AreaMomentOfInertia.FromFeetToTheFourth(double.CreateChecked(value)); + => AreaMomentOfInertia.FromFeetToTheFourth(QuantityValue.CreateChecked(value)); #else , IConvertible - => AreaMomentOfInertia.FromFeetToTheFourth(value.ToDouble(null)); + => AreaMomentOfInertia.FromFeetToTheFourth(value.ToQuantityValue()); #endif - /// + /// public static AreaMomentOfInertia InchesToTheFourth(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AreaMomentOfInertia.FromInchesToTheFourth(double.CreateChecked(value)); + => AreaMomentOfInertia.FromInchesToTheFourth(QuantityValue.CreateChecked(value)); #else , IConvertible - => AreaMomentOfInertia.FromInchesToTheFourth(value.ToDouble(null)); + => AreaMomentOfInertia.FromInchesToTheFourth(value.ToQuantityValue()); #endif - /// + /// public static AreaMomentOfInertia MetersToTheFourth(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AreaMomentOfInertia.FromMetersToTheFourth(double.CreateChecked(value)); + => AreaMomentOfInertia.FromMetersToTheFourth(QuantityValue.CreateChecked(value)); #else , IConvertible - => AreaMomentOfInertia.FromMetersToTheFourth(value.ToDouble(null)); + => AreaMomentOfInertia.FromMetersToTheFourth(value.ToQuantityValue()); #endif - /// + /// public static AreaMomentOfInertia MillimetersToTheFourth(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => AreaMomentOfInertia.FromMillimetersToTheFourth(double.CreateChecked(value)); + => AreaMomentOfInertia.FromMillimetersToTheFourth(QuantityValue.CreateChecked(value)); #else , IConvertible - => AreaMomentOfInertia.FromMillimetersToTheFourth(value.ToDouble(null)); + => AreaMomentOfInertia.FromMillimetersToTheFourth(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToBitRateExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToBitRateExtensions.g.cs index e747c0aef6..1a742798fa 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToBitRateExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToBitRateExtensions.g.cs @@ -32,433 +32,433 @@ namespace UnitsNet.NumberExtensions.NumberToBitRate /// public static class NumberToBitRateExtensions { - /// + /// public static BitRate BitsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromBitsPerSecond(double.CreateChecked(value)); + => BitRate.FromBitsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromBitsPerSecond(value.ToDouble(null)); + => BitRate.FromBitsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate BytesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromBytesPerSecond(double.CreateChecked(value)); + => BitRate.FromBytesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromBytesPerSecond(value.ToDouble(null)); + => BitRate.FromBytesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate ExabitsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromExabitsPerSecond(double.CreateChecked(value)); + => BitRate.FromExabitsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromExabitsPerSecond(value.ToDouble(null)); + => BitRate.FromExabitsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate ExabytesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromExabytesPerSecond(double.CreateChecked(value)); + => BitRate.FromExabytesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromExabytesPerSecond(value.ToDouble(null)); + => BitRate.FromExabytesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate ExaoctetsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromExaoctetsPerSecond(double.CreateChecked(value)); + => BitRate.FromExaoctetsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromExaoctetsPerSecond(value.ToDouble(null)); + => BitRate.FromExaoctetsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate ExbibitsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromExbibitsPerSecond(double.CreateChecked(value)); + => BitRate.FromExbibitsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromExbibitsPerSecond(value.ToDouble(null)); + => BitRate.FromExbibitsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate ExbibytesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromExbibytesPerSecond(double.CreateChecked(value)); + => BitRate.FromExbibytesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromExbibytesPerSecond(value.ToDouble(null)); + => BitRate.FromExbibytesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate ExbioctetsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromExbioctetsPerSecond(double.CreateChecked(value)); + => BitRate.FromExbioctetsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromExbioctetsPerSecond(value.ToDouble(null)); + => BitRate.FromExbioctetsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate GibibitsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromGibibitsPerSecond(double.CreateChecked(value)); + => BitRate.FromGibibitsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromGibibitsPerSecond(value.ToDouble(null)); + => BitRate.FromGibibitsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate GibibytesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromGibibytesPerSecond(double.CreateChecked(value)); + => BitRate.FromGibibytesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromGibibytesPerSecond(value.ToDouble(null)); + => BitRate.FromGibibytesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate GibioctetsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromGibioctetsPerSecond(double.CreateChecked(value)); + => BitRate.FromGibioctetsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromGibioctetsPerSecond(value.ToDouble(null)); + => BitRate.FromGibioctetsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate GigabitsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromGigabitsPerSecond(double.CreateChecked(value)); + => BitRate.FromGigabitsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromGigabitsPerSecond(value.ToDouble(null)); + => BitRate.FromGigabitsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate GigabytesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromGigabytesPerSecond(double.CreateChecked(value)); + => BitRate.FromGigabytesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromGigabytesPerSecond(value.ToDouble(null)); + => BitRate.FromGigabytesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate GigaoctetsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromGigaoctetsPerSecond(double.CreateChecked(value)); + => BitRate.FromGigaoctetsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromGigaoctetsPerSecond(value.ToDouble(null)); + => BitRate.FromGigaoctetsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate KibibitsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromKibibitsPerSecond(double.CreateChecked(value)); + => BitRate.FromKibibitsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromKibibitsPerSecond(value.ToDouble(null)); + => BitRate.FromKibibitsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate KibibytesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromKibibytesPerSecond(double.CreateChecked(value)); + => BitRate.FromKibibytesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromKibibytesPerSecond(value.ToDouble(null)); + => BitRate.FromKibibytesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate KibioctetsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromKibioctetsPerSecond(double.CreateChecked(value)); + => BitRate.FromKibioctetsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromKibioctetsPerSecond(value.ToDouble(null)); + => BitRate.FromKibioctetsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate KilobitsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromKilobitsPerSecond(double.CreateChecked(value)); + => BitRate.FromKilobitsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromKilobitsPerSecond(value.ToDouble(null)); + => BitRate.FromKilobitsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate KilobytesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromKilobytesPerSecond(double.CreateChecked(value)); + => BitRate.FromKilobytesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromKilobytesPerSecond(value.ToDouble(null)); + => BitRate.FromKilobytesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate KilooctetsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromKilooctetsPerSecond(double.CreateChecked(value)); + => BitRate.FromKilooctetsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromKilooctetsPerSecond(value.ToDouble(null)); + => BitRate.FromKilooctetsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate MebibitsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromMebibitsPerSecond(double.CreateChecked(value)); + => BitRate.FromMebibitsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromMebibitsPerSecond(value.ToDouble(null)); + => BitRate.FromMebibitsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate MebibytesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromMebibytesPerSecond(double.CreateChecked(value)); + => BitRate.FromMebibytesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromMebibytesPerSecond(value.ToDouble(null)); + => BitRate.FromMebibytesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate MebioctetsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromMebioctetsPerSecond(double.CreateChecked(value)); + => BitRate.FromMebioctetsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromMebioctetsPerSecond(value.ToDouble(null)); + => BitRate.FromMebioctetsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate MegabitsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromMegabitsPerSecond(double.CreateChecked(value)); + => BitRate.FromMegabitsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromMegabitsPerSecond(value.ToDouble(null)); + => BitRate.FromMegabitsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate MegabytesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromMegabytesPerSecond(double.CreateChecked(value)); + => BitRate.FromMegabytesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromMegabytesPerSecond(value.ToDouble(null)); + => BitRate.FromMegabytesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate MegaoctetsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromMegaoctetsPerSecond(double.CreateChecked(value)); + => BitRate.FromMegaoctetsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromMegaoctetsPerSecond(value.ToDouble(null)); + => BitRate.FromMegaoctetsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate OctetsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromOctetsPerSecond(double.CreateChecked(value)); + => BitRate.FromOctetsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromOctetsPerSecond(value.ToDouble(null)); + => BitRate.FromOctetsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate PebibitsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromPebibitsPerSecond(double.CreateChecked(value)); + => BitRate.FromPebibitsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromPebibitsPerSecond(value.ToDouble(null)); + => BitRate.FromPebibitsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate PebibytesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromPebibytesPerSecond(double.CreateChecked(value)); + => BitRate.FromPebibytesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromPebibytesPerSecond(value.ToDouble(null)); + => BitRate.FromPebibytesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate PebioctetsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromPebioctetsPerSecond(double.CreateChecked(value)); + => BitRate.FromPebioctetsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromPebioctetsPerSecond(value.ToDouble(null)); + => BitRate.FromPebioctetsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate PetabitsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromPetabitsPerSecond(double.CreateChecked(value)); + => BitRate.FromPetabitsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromPetabitsPerSecond(value.ToDouble(null)); + => BitRate.FromPetabitsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate PetabytesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromPetabytesPerSecond(double.CreateChecked(value)); + => BitRate.FromPetabytesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromPetabytesPerSecond(value.ToDouble(null)); + => BitRate.FromPetabytesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate PetaoctetsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromPetaoctetsPerSecond(double.CreateChecked(value)); + => BitRate.FromPetaoctetsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromPetaoctetsPerSecond(value.ToDouble(null)); + => BitRate.FromPetaoctetsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate TebibitsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromTebibitsPerSecond(double.CreateChecked(value)); + => BitRate.FromTebibitsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromTebibitsPerSecond(value.ToDouble(null)); + => BitRate.FromTebibitsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate TebibytesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromTebibytesPerSecond(double.CreateChecked(value)); + => BitRate.FromTebibytesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromTebibytesPerSecond(value.ToDouble(null)); + => BitRate.FromTebibytesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate TebioctetsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromTebioctetsPerSecond(double.CreateChecked(value)); + => BitRate.FromTebioctetsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromTebioctetsPerSecond(value.ToDouble(null)); + => BitRate.FromTebioctetsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate TerabitsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromTerabitsPerSecond(double.CreateChecked(value)); + => BitRate.FromTerabitsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromTerabitsPerSecond(value.ToDouble(null)); + => BitRate.FromTerabitsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate TerabytesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromTerabytesPerSecond(double.CreateChecked(value)); + => BitRate.FromTerabytesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromTerabytesPerSecond(value.ToDouble(null)); + => BitRate.FromTerabytesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static BitRate TeraoctetsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BitRate.FromTeraoctetsPerSecond(double.CreateChecked(value)); + => BitRate.FromTeraoctetsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => BitRate.FromTeraoctetsPerSecond(value.ToDouble(null)); + => BitRate.FromTeraoctetsPerSecond(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToBrakeSpecificFuelConsumptionExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToBrakeSpecificFuelConsumptionExtensions.g.cs index 6881a06193..6c275fa041 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToBrakeSpecificFuelConsumptionExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToBrakeSpecificFuelConsumptionExtensions.g.cs @@ -32,37 +32,37 @@ namespace UnitsNet.NumberExtensions.NumberToBrakeSpecificFuelConsumption /// public static class NumberToBrakeSpecificFuelConsumptionExtensions { - /// + /// public static BrakeSpecificFuelConsumption GramsPerKiloWattHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(double.CreateChecked(value)); + => BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(value.ToDouble(null)); + => BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(value.ToQuantityValue()); #endif - /// + /// public static BrakeSpecificFuelConsumption KilogramsPerJoule(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BrakeSpecificFuelConsumption.FromKilogramsPerJoule(double.CreateChecked(value)); + => BrakeSpecificFuelConsumption.FromKilogramsPerJoule(QuantityValue.CreateChecked(value)); #else , IConvertible - => BrakeSpecificFuelConsumption.FromKilogramsPerJoule(value.ToDouble(null)); + => BrakeSpecificFuelConsumption.FromKilogramsPerJoule(value.ToQuantityValue()); #endif - /// + /// public static BrakeSpecificFuelConsumption PoundsPerMechanicalHorsepowerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => BrakeSpecificFuelConsumption.FromPoundsPerMechanicalHorsepowerHour(double.CreateChecked(value)); + => BrakeSpecificFuelConsumption.FromPoundsPerMechanicalHorsepowerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => BrakeSpecificFuelConsumption.FromPoundsPerMechanicalHorsepowerHour(value.ToDouble(null)); + => BrakeSpecificFuelConsumption.FromPoundsPerMechanicalHorsepowerHour(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToCoefficientOfThermalExpansionExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToCoefficientOfThermalExpansionExtensions.g.cs index 93f1ba1af7..1ca4c4ea56 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToCoefficientOfThermalExpansionExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToCoefficientOfThermalExpansionExtensions.g.cs @@ -32,70 +32,70 @@ namespace UnitsNet.NumberExtensions.NumberToCoefficientOfThermalExpansion /// public static class NumberToCoefficientOfThermalExpansionExtensions { - /// + /// public static CoefficientOfThermalExpansion PerDegreeCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => CoefficientOfThermalExpansion.FromPerDegreeCelsius(double.CreateChecked(value)); + => CoefficientOfThermalExpansion.FromPerDegreeCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => CoefficientOfThermalExpansion.FromPerDegreeCelsius(value.ToDouble(null)); + => CoefficientOfThermalExpansion.FromPerDegreeCelsius(value.ToQuantityValue()); #endif - /// + /// public static CoefficientOfThermalExpansion PerDegreeFahrenheit(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => CoefficientOfThermalExpansion.FromPerDegreeFahrenheit(double.CreateChecked(value)); + => CoefficientOfThermalExpansion.FromPerDegreeFahrenheit(QuantityValue.CreateChecked(value)); #else , IConvertible - => CoefficientOfThermalExpansion.FromPerDegreeFahrenheit(value.ToDouble(null)); + => CoefficientOfThermalExpansion.FromPerDegreeFahrenheit(value.ToQuantityValue()); #endif - /// + /// public static CoefficientOfThermalExpansion PerKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => CoefficientOfThermalExpansion.FromPerKelvin(double.CreateChecked(value)); + => CoefficientOfThermalExpansion.FromPerKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => CoefficientOfThermalExpansion.FromPerKelvin(value.ToDouble(null)); + => CoefficientOfThermalExpansion.FromPerKelvin(value.ToQuantityValue()); #endif - /// + /// public static CoefficientOfThermalExpansion PpmPerDegreeCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => CoefficientOfThermalExpansion.FromPpmPerDegreeCelsius(double.CreateChecked(value)); + => CoefficientOfThermalExpansion.FromPpmPerDegreeCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => CoefficientOfThermalExpansion.FromPpmPerDegreeCelsius(value.ToDouble(null)); + => CoefficientOfThermalExpansion.FromPpmPerDegreeCelsius(value.ToQuantityValue()); #endif - /// + /// public static CoefficientOfThermalExpansion PpmPerDegreeFahrenheit(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => CoefficientOfThermalExpansion.FromPpmPerDegreeFahrenheit(double.CreateChecked(value)); + => CoefficientOfThermalExpansion.FromPpmPerDegreeFahrenheit(QuantityValue.CreateChecked(value)); #else , IConvertible - => CoefficientOfThermalExpansion.FromPpmPerDegreeFahrenheit(value.ToDouble(null)); + => CoefficientOfThermalExpansion.FromPpmPerDegreeFahrenheit(value.ToQuantityValue()); #endif - /// + /// public static CoefficientOfThermalExpansion PpmPerKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => CoefficientOfThermalExpansion.FromPpmPerKelvin(double.CreateChecked(value)); + => CoefficientOfThermalExpansion.FromPpmPerKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => CoefficientOfThermalExpansion.FromPpmPerKelvin(value.ToDouble(null)); + => CoefficientOfThermalExpansion.FromPpmPerKelvin(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToCompressibilityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToCompressibilityExtensions.g.cs index d5d03e5737..5c261502b1 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToCompressibilityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToCompressibilityExtensions.g.cs @@ -32,81 +32,81 @@ namespace UnitsNet.NumberExtensions.NumberToCompressibility /// public static class NumberToCompressibilityExtensions { - /// + /// public static Compressibility InverseAtmospheres(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Compressibility.FromInverseAtmospheres(double.CreateChecked(value)); + => Compressibility.FromInverseAtmospheres(QuantityValue.CreateChecked(value)); #else , IConvertible - => Compressibility.FromInverseAtmospheres(value.ToDouble(null)); + => Compressibility.FromInverseAtmospheres(value.ToQuantityValue()); #endif - /// + /// public static Compressibility InverseBars(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Compressibility.FromInverseBars(double.CreateChecked(value)); + => Compressibility.FromInverseBars(QuantityValue.CreateChecked(value)); #else , IConvertible - => Compressibility.FromInverseBars(value.ToDouble(null)); + => Compressibility.FromInverseBars(value.ToQuantityValue()); #endif - /// + /// public static Compressibility InverseKilopascals(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Compressibility.FromInverseKilopascals(double.CreateChecked(value)); + => Compressibility.FromInverseKilopascals(QuantityValue.CreateChecked(value)); #else , IConvertible - => Compressibility.FromInverseKilopascals(value.ToDouble(null)); + => Compressibility.FromInverseKilopascals(value.ToQuantityValue()); #endif - /// + /// public static Compressibility InverseMegapascals(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Compressibility.FromInverseMegapascals(double.CreateChecked(value)); + => Compressibility.FromInverseMegapascals(QuantityValue.CreateChecked(value)); #else , IConvertible - => Compressibility.FromInverseMegapascals(value.ToDouble(null)); + => Compressibility.FromInverseMegapascals(value.ToQuantityValue()); #endif - /// + /// public static Compressibility InverseMillibars(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Compressibility.FromInverseMillibars(double.CreateChecked(value)); + => Compressibility.FromInverseMillibars(QuantityValue.CreateChecked(value)); #else , IConvertible - => Compressibility.FromInverseMillibars(value.ToDouble(null)); + => Compressibility.FromInverseMillibars(value.ToQuantityValue()); #endif - /// + /// public static Compressibility InversePascals(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Compressibility.FromInversePascals(double.CreateChecked(value)); + => Compressibility.FromInversePascals(QuantityValue.CreateChecked(value)); #else , IConvertible - => Compressibility.FromInversePascals(value.ToDouble(null)); + => Compressibility.FromInversePascals(value.ToQuantityValue()); #endif - /// + /// public static Compressibility InversePoundsForcePerSquareInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Compressibility.FromInversePoundsForcePerSquareInch(double.CreateChecked(value)); + => Compressibility.FromInversePoundsForcePerSquareInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => Compressibility.FromInversePoundsForcePerSquareInch(value.ToDouble(null)); + => Compressibility.FromInversePoundsForcePerSquareInch(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToDensityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToDensityExtensions.g.cs index 41e548ce0c..b32202283f 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToDensityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToDensityExtensions.g.cs @@ -32,620 +32,620 @@ namespace UnitsNet.NumberExtensions.NumberToDensity /// public static class NumberToDensityExtensions { - /// + /// public static Density CentigramsPerDeciliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromCentigramsPerDeciliter(double.CreateChecked(value)); + => Density.FromCentigramsPerDeciliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromCentigramsPerDeciliter(value.ToDouble(null)); + => Density.FromCentigramsPerDeciliter(value.ToQuantityValue()); #endif - /// + /// public static Density CentigramsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromCentigramsPerLiter(double.CreateChecked(value)); + => Density.FromCentigramsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromCentigramsPerLiter(value.ToDouble(null)); + => Density.FromCentigramsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static Density CentigramsPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromCentigramsPerMilliliter(double.CreateChecked(value)); + => Density.FromCentigramsPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromCentigramsPerMilliliter(value.ToDouble(null)); + => Density.FromCentigramsPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static Density DecigramsPerDeciliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromDecigramsPerDeciliter(double.CreateChecked(value)); + => Density.FromDecigramsPerDeciliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromDecigramsPerDeciliter(value.ToDouble(null)); + => Density.FromDecigramsPerDeciliter(value.ToQuantityValue()); #endif - /// + /// public static Density DecigramsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromDecigramsPerLiter(double.CreateChecked(value)); + => Density.FromDecigramsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromDecigramsPerLiter(value.ToDouble(null)); + => Density.FromDecigramsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static Density DecigramsPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromDecigramsPerMilliliter(double.CreateChecked(value)); + => Density.FromDecigramsPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromDecigramsPerMilliliter(value.ToDouble(null)); + => Density.FromDecigramsPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static Density FemtogramsPerDeciliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromFemtogramsPerDeciliter(double.CreateChecked(value)); + => Density.FromFemtogramsPerDeciliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromFemtogramsPerDeciliter(value.ToDouble(null)); + => Density.FromFemtogramsPerDeciliter(value.ToQuantityValue()); #endif - /// + /// public static Density FemtogramsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromFemtogramsPerLiter(double.CreateChecked(value)); + => Density.FromFemtogramsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromFemtogramsPerLiter(value.ToDouble(null)); + => Density.FromFemtogramsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static Density FemtogramsPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromFemtogramsPerMilliliter(double.CreateChecked(value)); + => Density.FromFemtogramsPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromFemtogramsPerMilliliter(value.ToDouble(null)); + => Density.FromFemtogramsPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static Density GramsPerCubicCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromGramsPerCubicCentimeter(double.CreateChecked(value)); + => Density.FromGramsPerCubicCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromGramsPerCubicCentimeter(value.ToDouble(null)); + => Density.FromGramsPerCubicCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Density GramsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromGramsPerCubicFoot(double.CreateChecked(value)); + => Density.FromGramsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromGramsPerCubicFoot(value.ToDouble(null)); + => Density.FromGramsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static Density GramsPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromGramsPerCubicInch(double.CreateChecked(value)); + => Density.FromGramsPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromGramsPerCubicInch(value.ToDouble(null)); + => Density.FromGramsPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static Density GramsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromGramsPerCubicMeter(double.CreateChecked(value)); + => Density.FromGramsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromGramsPerCubicMeter(value.ToDouble(null)); + => Density.FromGramsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static Density GramsPerCubicMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromGramsPerCubicMillimeter(double.CreateChecked(value)); + => Density.FromGramsPerCubicMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromGramsPerCubicMillimeter(value.ToDouble(null)); + => Density.FromGramsPerCubicMillimeter(value.ToQuantityValue()); #endif - /// + /// public static Density GramsPerDeciliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromGramsPerDeciliter(double.CreateChecked(value)); + => Density.FromGramsPerDeciliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromGramsPerDeciliter(value.ToDouble(null)); + => Density.FromGramsPerDeciliter(value.ToQuantityValue()); #endif - /// + /// public static Density GramsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromGramsPerLiter(double.CreateChecked(value)); + => Density.FromGramsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromGramsPerLiter(value.ToDouble(null)); + => Density.FromGramsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static Density GramsPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromGramsPerMilliliter(double.CreateChecked(value)); + => Density.FromGramsPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromGramsPerMilliliter(value.ToDouble(null)); + => Density.FromGramsPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static Density KilogramsPerCubicCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromKilogramsPerCubicCentimeter(double.CreateChecked(value)); + => Density.FromKilogramsPerCubicCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromKilogramsPerCubicCentimeter(value.ToDouble(null)); + => Density.FromKilogramsPerCubicCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Density KilogramsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromKilogramsPerCubicMeter(double.CreateChecked(value)); + => Density.FromKilogramsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromKilogramsPerCubicMeter(value.ToDouble(null)); + => Density.FromKilogramsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static Density KilogramsPerCubicMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromKilogramsPerCubicMillimeter(double.CreateChecked(value)); + => Density.FromKilogramsPerCubicMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromKilogramsPerCubicMillimeter(value.ToDouble(null)); + => Density.FromKilogramsPerCubicMillimeter(value.ToQuantityValue()); #endif - /// + /// public static Density KilogramsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromKilogramsPerLiter(double.CreateChecked(value)); + => Density.FromKilogramsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromKilogramsPerLiter(value.ToDouble(null)); + => Density.FromKilogramsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static Density KilopoundsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromKilopoundsPerCubicFoot(double.CreateChecked(value)); + => Density.FromKilopoundsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromKilopoundsPerCubicFoot(value.ToDouble(null)); + => Density.FromKilopoundsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static Density KilopoundsPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromKilopoundsPerCubicInch(double.CreateChecked(value)); + => Density.FromKilopoundsPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromKilopoundsPerCubicInch(value.ToDouble(null)); + => Density.FromKilopoundsPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static Density KilopoundsPerCubicYard(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromKilopoundsPerCubicYard(double.CreateChecked(value)); + => Density.FromKilopoundsPerCubicYard(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromKilopoundsPerCubicYard(value.ToDouble(null)); + => Density.FromKilopoundsPerCubicYard(value.ToQuantityValue()); #endif - /// + /// public static Density MicrogramsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromMicrogramsPerCubicMeter(double.CreateChecked(value)); + => Density.FromMicrogramsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromMicrogramsPerCubicMeter(value.ToDouble(null)); + => Density.FromMicrogramsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static Density MicrogramsPerDeciliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromMicrogramsPerDeciliter(double.CreateChecked(value)); + => Density.FromMicrogramsPerDeciliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromMicrogramsPerDeciliter(value.ToDouble(null)); + => Density.FromMicrogramsPerDeciliter(value.ToQuantityValue()); #endif - /// + /// public static Density MicrogramsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromMicrogramsPerLiter(double.CreateChecked(value)); + => Density.FromMicrogramsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromMicrogramsPerLiter(value.ToDouble(null)); + => Density.FromMicrogramsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static Density MicrogramsPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromMicrogramsPerMilliliter(double.CreateChecked(value)); + => Density.FromMicrogramsPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromMicrogramsPerMilliliter(value.ToDouble(null)); + => Density.FromMicrogramsPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static Density MilligramsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromMilligramsPerCubicMeter(double.CreateChecked(value)); + => Density.FromMilligramsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromMilligramsPerCubicMeter(value.ToDouble(null)); + => Density.FromMilligramsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static Density MilligramsPerDeciliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromMilligramsPerDeciliter(double.CreateChecked(value)); + => Density.FromMilligramsPerDeciliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromMilligramsPerDeciliter(value.ToDouble(null)); + => Density.FromMilligramsPerDeciliter(value.ToQuantityValue()); #endif - /// + /// public static Density MilligramsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromMilligramsPerLiter(double.CreateChecked(value)); + => Density.FromMilligramsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromMilligramsPerLiter(value.ToDouble(null)); + => Density.FromMilligramsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static Density MilligramsPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromMilligramsPerMilliliter(double.CreateChecked(value)); + => Density.FromMilligramsPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromMilligramsPerMilliliter(value.ToDouble(null)); + => Density.FromMilligramsPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static Density NanogramsPerDeciliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromNanogramsPerDeciliter(double.CreateChecked(value)); + => Density.FromNanogramsPerDeciliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromNanogramsPerDeciliter(value.ToDouble(null)); + => Density.FromNanogramsPerDeciliter(value.ToQuantityValue()); #endif - /// + /// public static Density NanogramsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromNanogramsPerLiter(double.CreateChecked(value)); + => Density.FromNanogramsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromNanogramsPerLiter(value.ToDouble(null)); + => Density.FromNanogramsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static Density NanogramsPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromNanogramsPerMilliliter(double.CreateChecked(value)); + => Density.FromNanogramsPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromNanogramsPerMilliliter(value.ToDouble(null)); + => Density.FromNanogramsPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static Density PicogramsPerDeciliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromPicogramsPerDeciliter(double.CreateChecked(value)); + => Density.FromPicogramsPerDeciliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromPicogramsPerDeciliter(value.ToDouble(null)); + => Density.FromPicogramsPerDeciliter(value.ToQuantityValue()); #endif - /// + /// public static Density PicogramsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromPicogramsPerLiter(double.CreateChecked(value)); + => Density.FromPicogramsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromPicogramsPerLiter(value.ToDouble(null)); + => Density.FromPicogramsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static Density PicogramsPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromPicogramsPerMilliliter(double.CreateChecked(value)); + => Density.FromPicogramsPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromPicogramsPerMilliliter(value.ToDouble(null)); + => Density.FromPicogramsPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static Density PoundsPerCubicCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromPoundsPerCubicCentimeter(double.CreateChecked(value)); + => Density.FromPoundsPerCubicCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromPoundsPerCubicCentimeter(value.ToDouble(null)); + => Density.FromPoundsPerCubicCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Density PoundsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromPoundsPerCubicFoot(double.CreateChecked(value)); + => Density.FromPoundsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromPoundsPerCubicFoot(value.ToDouble(null)); + => Density.FromPoundsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static Density PoundsPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromPoundsPerCubicInch(double.CreateChecked(value)); + => Density.FromPoundsPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromPoundsPerCubicInch(value.ToDouble(null)); + => Density.FromPoundsPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static Density PoundsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromPoundsPerCubicMeter(double.CreateChecked(value)); + => Density.FromPoundsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromPoundsPerCubicMeter(value.ToDouble(null)); + => Density.FromPoundsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static Density PoundsPerCubicMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromPoundsPerCubicMillimeter(double.CreateChecked(value)); + => Density.FromPoundsPerCubicMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromPoundsPerCubicMillimeter(value.ToDouble(null)); + => Density.FromPoundsPerCubicMillimeter(value.ToQuantityValue()); #endif - /// + /// public static Density PoundsPerCubicYard(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromPoundsPerCubicYard(double.CreateChecked(value)); + => Density.FromPoundsPerCubicYard(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromPoundsPerCubicYard(value.ToDouble(null)); + => Density.FromPoundsPerCubicYard(value.ToQuantityValue()); #endif - /// + /// public static Density PoundsPerImperialGallon(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromPoundsPerImperialGallon(double.CreateChecked(value)); + => Density.FromPoundsPerImperialGallon(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromPoundsPerImperialGallon(value.ToDouble(null)); + => Density.FromPoundsPerImperialGallon(value.ToQuantityValue()); #endif - /// + /// public static Density PoundsPerUSGallon(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromPoundsPerUSGallon(double.CreateChecked(value)); + => Density.FromPoundsPerUSGallon(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromPoundsPerUSGallon(value.ToDouble(null)); + => Density.FromPoundsPerUSGallon(value.ToQuantityValue()); #endif - /// + /// public static Density SlugsPerCubicCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromSlugsPerCubicCentimeter(double.CreateChecked(value)); + => Density.FromSlugsPerCubicCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromSlugsPerCubicCentimeter(value.ToDouble(null)); + => Density.FromSlugsPerCubicCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Density SlugsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromSlugsPerCubicFoot(double.CreateChecked(value)); + => Density.FromSlugsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromSlugsPerCubicFoot(value.ToDouble(null)); + => Density.FromSlugsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static Density SlugsPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromSlugsPerCubicInch(double.CreateChecked(value)); + => Density.FromSlugsPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromSlugsPerCubicInch(value.ToDouble(null)); + => Density.FromSlugsPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static Density SlugsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromSlugsPerCubicMeter(double.CreateChecked(value)); + => Density.FromSlugsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromSlugsPerCubicMeter(value.ToDouble(null)); + => Density.FromSlugsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static Density SlugsPerCubicMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromSlugsPerCubicMillimeter(double.CreateChecked(value)); + => Density.FromSlugsPerCubicMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromSlugsPerCubicMillimeter(value.ToDouble(null)); + => Density.FromSlugsPerCubicMillimeter(value.ToQuantityValue()); #endif - /// + /// public static Density TonnesPerCubicCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromTonnesPerCubicCentimeter(double.CreateChecked(value)); + => Density.FromTonnesPerCubicCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromTonnesPerCubicCentimeter(value.ToDouble(null)); + => Density.FromTonnesPerCubicCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Density TonnesPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromTonnesPerCubicFoot(double.CreateChecked(value)); + => Density.FromTonnesPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromTonnesPerCubicFoot(value.ToDouble(null)); + => Density.FromTonnesPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static Density TonnesPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromTonnesPerCubicInch(double.CreateChecked(value)); + => Density.FromTonnesPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromTonnesPerCubicInch(value.ToDouble(null)); + => Density.FromTonnesPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static Density TonnesPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromTonnesPerCubicMeter(double.CreateChecked(value)); + => Density.FromTonnesPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromTonnesPerCubicMeter(value.ToDouble(null)); + => Density.FromTonnesPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static Density TonnesPerCubicMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Density.FromTonnesPerCubicMillimeter(double.CreateChecked(value)); + => Density.FromTonnesPerCubicMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Density.FromTonnesPerCubicMillimeter(value.ToDouble(null)); + => Density.FromTonnesPerCubicMillimeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToDoseAreaProductExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToDoseAreaProductExtensions.g.cs index b0a770e93d..87715fc479 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToDoseAreaProductExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToDoseAreaProductExtensions.g.cs @@ -32,279 +32,279 @@ namespace UnitsNet.NumberExtensions.NumberToDoseAreaProduct /// public static class NumberToDoseAreaProductExtensions { - /// + /// public static DoseAreaProduct CentigraySquareCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromCentigraySquareCentimeters(double.CreateChecked(value)); + => DoseAreaProduct.FromCentigraySquareCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromCentigraySquareCentimeters(value.ToDouble(null)); + => DoseAreaProduct.FromCentigraySquareCentimeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct CentigraySquareDecimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromCentigraySquareDecimeters(double.CreateChecked(value)); + => DoseAreaProduct.FromCentigraySquareDecimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromCentigraySquareDecimeters(value.ToDouble(null)); + => DoseAreaProduct.FromCentigraySquareDecimeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct CentigraySquareMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromCentigraySquareMeters(double.CreateChecked(value)); + => DoseAreaProduct.FromCentigraySquareMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromCentigraySquareMeters(value.ToDouble(null)); + => DoseAreaProduct.FromCentigraySquareMeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct CentigraySquareMicrometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromCentigraySquareMicrometers(double.CreateChecked(value)); + => DoseAreaProduct.FromCentigraySquareMicrometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromCentigraySquareMicrometers(value.ToDouble(null)); + => DoseAreaProduct.FromCentigraySquareMicrometers(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct CentigraySquareMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromCentigraySquareMillimeters(double.CreateChecked(value)); + => DoseAreaProduct.FromCentigraySquareMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromCentigraySquareMillimeters(value.ToDouble(null)); + => DoseAreaProduct.FromCentigraySquareMillimeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct DecigraySquareCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromDecigraySquareCentimeters(double.CreateChecked(value)); + => DoseAreaProduct.FromDecigraySquareCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromDecigraySquareCentimeters(value.ToDouble(null)); + => DoseAreaProduct.FromDecigraySquareCentimeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct DecigraySquareDecimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromDecigraySquareDecimeters(double.CreateChecked(value)); + => DoseAreaProduct.FromDecigraySquareDecimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromDecigraySquareDecimeters(value.ToDouble(null)); + => DoseAreaProduct.FromDecigraySquareDecimeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct DecigraySquareMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromDecigraySquareMeters(double.CreateChecked(value)); + => DoseAreaProduct.FromDecigraySquareMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromDecigraySquareMeters(value.ToDouble(null)); + => DoseAreaProduct.FromDecigraySquareMeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct DecigraySquareMicrometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromDecigraySquareMicrometers(double.CreateChecked(value)); + => DoseAreaProduct.FromDecigraySquareMicrometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromDecigraySquareMicrometers(value.ToDouble(null)); + => DoseAreaProduct.FromDecigraySquareMicrometers(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct DecigraySquareMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromDecigraySquareMillimeters(double.CreateChecked(value)); + => DoseAreaProduct.FromDecigraySquareMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromDecigraySquareMillimeters(value.ToDouble(null)); + => DoseAreaProduct.FromDecigraySquareMillimeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct GraySquareCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromGraySquareCentimeters(double.CreateChecked(value)); + => DoseAreaProduct.FromGraySquareCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromGraySquareCentimeters(value.ToDouble(null)); + => DoseAreaProduct.FromGraySquareCentimeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct GraySquareDecimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromGraySquareDecimeters(double.CreateChecked(value)); + => DoseAreaProduct.FromGraySquareDecimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromGraySquareDecimeters(value.ToDouble(null)); + => DoseAreaProduct.FromGraySquareDecimeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct GraySquareMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromGraySquareMeters(double.CreateChecked(value)); + => DoseAreaProduct.FromGraySquareMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromGraySquareMeters(value.ToDouble(null)); + => DoseAreaProduct.FromGraySquareMeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct GraySquareMicrometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromGraySquareMicrometers(double.CreateChecked(value)); + => DoseAreaProduct.FromGraySquareMicrometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromGraySquareMicrometers(value.ToDouble(null)); + => DoseAreaProduct.FromGraySquareMicrometers(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct GraySquareMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromGraySquareMillimeters(double.CreateChecked(value)); + => DoseAreaProduct.FromGraySquareMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromGraySquareMillimeters(value.ToDouble(null)); + => DoseAreaProduct.FromGraySquareMillimeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct MicrograySquareCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromMicrograySquareCentimeters(double.CreateChecked(value)); + => DoseAreaProduct.FromMicrograySquareCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromMicrograySquareCentimeters(value.ToDouble(null)); + => DoseAreaProduct.FromMicrograySquareCentimeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct MicrograySquareDecimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromMicrograySquareDecimeters(double.CreateChecked(value)); + => DoseAreaProduct.FromMicrograySquareDecimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromMicrograySquareDecimeters(value.ToDouble(null)); + => DoseAreaProduct.FromMicrograySquareDecimeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct MicrograySquareMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromMicrograySquareMeters(double.CreateChecked(value)); + => DoseAreaProduct.FromMicrograySquareMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromMicrograySquareMeters(value.ToDouble(null)); + => DoseAreaProduct.FromMicrograySquareMeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct MicrograySquareMicrometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromMicrograySquareMicrometers(double.CreateChecked(value)); + => DoseAreaProduct.FromMicrograySquareMicrometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromMicrograySquareMicrometers(value.ToDouble(null)); + => DoseAreaProduct.FromMicrograySquareMicrometers(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct MicrograySquareMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromMicrograySquareMillimeters(double.CreateChecked(value)); + => DoseAreaProduct.FromMicrograySquareMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromMicrograySquareMillimeters(value.ToDouble(null)); + => DoseAreaProduct.FromMicrograySquareMillimeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct MilligraySquareCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromMilligraySquareCentimeters(double.CreateChecked(value)); + => DoseAreaProduct.FromMilligraySquareCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromMilligraySquareCentimeters(value.ToDouble(null)); + => DoseAreaProduct.FromMilligraySquareCentimeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct MilligraySquareDecimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromMilligraySquareDecimeters(double.CreateChecked(value)); + => DoseAreaProduct.FromMilligraySquareDecimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromMilligraySquareDecimeters(value.ToDouble(null)); + => DoseAreaProduct.FromMilligraySquareDecimeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct MilligraySquareMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromMilligraySquareMeters(double.CreateChecked(value)); + => DoseAreaProduct.FromMilligraySquareMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromMilligraySquareMeters(value.ToDouble(null)); + => DoseAreaProduct.FromMilligraySquareMeters(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct MilligraySquareMicrometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromMilligraySquareMicrometers(double.CreateChecked(value)); + => DoseAreaProduct.FromMilligraySquareMicrometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromMilligraySquareMicrometers(value.ToDouble(null)); + => DoseAreaProduct.FromMilligraySquareMicrometers(value.ToQuantityValue()); #endif - /// + /// public static DoseAreaProduct MilligraySquareMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DoseAreaProduct.FromMilligraySquareMillimeters(double.CreateChecked(value)); + => DoseAreaProduct.FromMilligraySquareMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => DoseAreaProduct.FromMilligraySquareMillimeters(value.ToDouble(null)); + => DoseAreaProduct.FromMilligraySquareMillimeters(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToDurationExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToDurationExtensions.g.cs index 55aa0a6a3a..a5758fbfea 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToDurationExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToDurationExtensions.g.cs @@ -32,147 +32,147 @@ namespace UnitsNet.NumberExtensions.NumberToDuration /// public static class NumberToDurationExtensions { - /// + /// public static Duration Days(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Duration.FromDays(double.CreateChecked(value)); + => Duration.FromDays(QuantityValue.CreateChecked(value)); #else , IConvertible - => Duration.FromDays(value.ToDouble(null)); + => Duration.FromDays(value.ToQuantityValue()); #endif - /// + /// public static Duration Hours(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Duration.FromHours(double.CreateChecked(value)); + => Duration.FromHours(QuantityValue.CreateChecked(value)); #else , IConvertible - => Duration.FromHours(value.ToDouble(null)); + => Duration.FromHours(value.ToQuantityValue()); #endif - /// + /// public static Duration JulianYears(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Duration.FromJulianYears(double.CreateChecked(value)); + => Duration.FromJulianYears(QuantityValue.CreateChecked(value)); #else , IConvertible - => Duration.FromJulianYears(value.ToDouble(null)); + => Duration.FromJulianYears(value.ToQuantityValue()); #endif - /// + /// public static Duration Microseconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Duration.FromMicroseconds(double.CreateChecked(value)); + => Duration.FromMicroseconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Duration.FromMicroseconds(value.ToDouble(null)); + => Duration.FromMicroseconds(value.ToQuantityValue()); #endif - /// + /// public static Duration Milliseconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Duration.FromMilliseconds(double.CreateChecked(value)); + => Duration.FromMilliseconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Duration.FromMilliseconds(value.ToDouble(null)); + => Duration.FromMilliseconds(value.ToQuantityValue()); #endif - /// + /// public static Duration Minutes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Duration.FromMinutes(double.CreateChecked(value)); + => Duration.FromMinutes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Duration.FromMinutes(value.ToDouble(null)); + => Duration.FromMinutes(value.ToQuantityValue()); #endif - /// + /// public static Duration Months30(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Duration.FromMonths30(double.CreateChecked(value)); + => Duration.FromMonths30(QuantityValue.CreateChecked(value)); #else , IConvertible - => Duration.FromMonths30(value.ToDouble(null)); + => Duration.FromMonths30(value.ToQuantityValue()); #endif - /// + /// public static Duration Nanoseconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Duration.FromNanoseconds(double.CreateChecked(value)); + => Duration.FromNanoseconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Duration.FromNanoseconds(value.ToDouble(null)); + => Duration.FromNanoseconds(value.ToQuantityValue()); #endif - /// + /// public static Duration Picoseconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Duration.FromPicoseconds(double.CreateChecked(value)); + => Duration.FromPicoseconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Duration.FromPicoseconds(value.ToDouble(null)); + => Duration.FromPicoseconds(value.ToQuantityValue()); #endif - /// + /// public static Duration Seconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Duration.FromSeconds(double.CreateChecked(value)); + => Duration.FromSeconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Duration.FromSeconds(value.ToDouble(null)); + => Duration.FromSeconds(value.ToQuantityValue()); #endif - /// + /// public static Duration Sols(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Duration.FromSols(double.CreateChecked(value)); + => Duration.FromSols(QuantityValue.CreateChecked(value)); #else , IConvertible - => Duration.FromSols(value.ToDouble(null)); + => Duration.FromSols(value.ToQuantityValue()); #endif - /// + /// public static Duration Weeks(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Duration.FromWeeks(double.CreateChecked(value)); + => Duration.FromWeeks(QuantityValue.CreateChecked(value)); #else , IConvertible - => Duration.FromWeeks(value.ToDouble(null)); + => Duration.FromWeeks(value.ToQuantityValue()); #endif - /// + /// public static Duration Years365(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Duration.FromYears365(double.CreateChecked(value)); + => Duration.FromYears365(QuantityValue.CreateChecked(value)); #else , IConvertible - => Duration.FromYears365(value.ToDouble(null)); + => Duration.FromYears365(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToDynamicViscosityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToDynamicViscosityExtensions.g.cs index 037a0eaf3a..a5a5b0fd37 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToDynamicViscosityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToDynamicViscosityExtensions.g.cs @@ -32,114 +32,114 @@ namespace UnitsNet.NumberExtensions.NumberToDynamicViscosity /// public static class NumberToDynamicViscosityExtensions { - /// + /// public static DynamicViscosity Centipoise(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DynamicViscosity.FromCentipoise(double.CreateChecked(value)); + => DynamicViscosity.FromCentipoise(QuantityValue.CreateChecked(value)); #else , IConvertible - => DynamicViscosity.FromCentipoise(value.ToDouble(null)); + => DynamicViscosity.FromCentipoise(value.ToQuantityValue()); #endif - /// + /// public static DynamicViscosity MicropascalSeconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DynamicViscosity.FromMicropascalSeconds(double.CreateChecked(value)); + => DynamicViscosity.FromMicropascalSeconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => DynamicViscosity.FromMicropascalSeconds(value.ToDouble(null)); + => DynamicViscosity.FromMicropascalSeconds(value.ToQuantityValue()); #endif - /// + /// public static DynamicViscosity MillipascalSeconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DynamicViscosity.FromMillipascalSeconds(double.CreateChecked(value)); + => DynamicViscosity.FromMillipascalSeconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => DynamicViscosity.FromMillipascalSeconds(value.ToDouble(null)); + => DynamicViscosity.FromMillipascalSeconds(value.ToQuantityValue()); #endif - /// + /// public static DynamicViscosity NewtonSecondsPerMeterSquared(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DynamicViscosity.FromNewtonSecondsPerMeterSquared(double.CreateChecked(value)); + => DynamicViscosity.FromNewtonSecondsPerMeterSquared(QuantityValue.CreateChecked(value)); #else , IConvertible - => DynamicViscosity.FromNewtonSecondsPerMeterSquared(value.ToDouble(null)); + => DynamicViscosity.FromNewtonSecondsPerMeterSquared(value.ToQuantityValue()); #endif - /// + /// public static DynamicViscosity PascalSeconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DynamicViscosity.FromPascalSeconds(double.CreateChecked(value)); + => DynamicViscosity.FromPascalSeconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => DynamicViscosity.FromPascalSeconds(value.ToDouble(null)); + => DynamicViscosity.FromPascalSeconds(value.ToQuantityValue()); #endif - /// + /// public static DynamicViscosity Poise(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DynamicViscosity.FromPoise(double.CreateChecked(value)); + => DynamicViscosity.FromPoise(QuantityValue.CreateChecked(value)); #else , IConvertible - => DynamicViscosity.FromPoise(value.ToDouble(null)); + => DynamicViscosity.FromPoise(value.ToQuantityValue()); #endif - /// + /// public static DynamicViscosity PoundsForceSecondPerSquareFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DynamicViscosity.FromPoundsForceSecondPerSquareFoot(double.CreateChecked(value)); + => DynamicViscosity.FromPoundsForceSecondPerSquareFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => DynamicViscosity.FromPoundsForceSecondPerSquareFoot(value.ToDouble(null)); + => DynamicViscosity.FromPoundsForceSecondPerSquareFoot(value.ToQuantityValue()); #endif - /// + /// public static DynamicViscosity PoundsForceSecondPerSquareInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DynamicViscosity.FromPoundsForceSecondPerSquareInch(double.CreateChecked(value)); + => DynamicViscosity.FromPoundsForceSecondPerSquareInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => DynamicViscosity.FromPoundsForceSecondPerSquareInch(value.ToDouble(null)); + => DynamicViscosity.FromPoundsForceSecondPerSquareInch(value.ToQuantityValue()); #endif - /// + /// public static DynamicViscosity PoundsPerFootSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DynamicViscosity.FromPoundsPerFootSecond(double.CreateChecked(value)); + => DynamicViscosity.FromPoundsPerFootSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => DynamicViscosity.FromPoundsPerFootSecond(value.ToDouble(null)); + => DynamicViscosity.FromPoundsPerFootSecond(value.ToQuantityValue()); #endif - /// + /// public static DynamicViscosity Reyns(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => DynamicViscosity.FromReyns(double.CreateChecked(value)); + => DynamicViscosity.FromReyns(QuantityValue.CreateChecked(value)); #else , IConvertible - => DynamicViscosity.FromReyns(value.ToDouble(null)); + => DynamicViscosity.FromReyns(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricAdmittanceExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricAdmittanceExtensions.g.cs index c8ec024579..9bfd71cc75 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricAdmittanceExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricAdmittanceExtensions.g.cs @@ -33,196 +33,196 @@ namespace UnitsNet.NumberExtensions.NumberToElectricAdmittance [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] public static class NumberToElectricAdmittanceExtensions { - /// + /// [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] public static ElectricAdmittance Gigamhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricAdmittance.FromGigamhos(double.CreateChecked(value)); + => ElectricAdmittance.FromGigamhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricAdmittance.FromGigamhos(value.ToDouble(null)); + => ElectricAdmittance.FromGigamhos(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] public static ElectricAdmittance Gigasiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricAdmittance.FromGigasiemens(double.CreateChecked(value)); + => ElectricAdmittance.FromGigasiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricAdmittance.FromGigasiemens(value.ToDouble(null)); + => ElectricAdmittance.FromGigasiemens(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] public static ElectricAdmittance Kilomhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricAdmittance.FromKilomhos(double.CreateChecked(value)); + => ElectricAdmittance.FromKilomhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricAdmittance.FromKilomhos(value.ToDouble(null)); + => ElectricAdmittance.FromKilomhos(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] public static ElectricAdmittance Kilosiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricAdmittance.FromKilosiemens(double.CreateChecked(value)); + => ElectricAdmittance.FromKilosiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricAdmittance.FromKilosiemens(value.ToDouble(null)); + => ElectricAdmittance.FromKilosiemens(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] public static ElectricAdmittance Megamhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricAdmittance.FromMegamhos(double.CreateChecked(value)); + => ElectricAdmittance.FromMegamhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricAdmittance.FromMegamhos(value.ToDouble(null)); + => ElectricAdmittance.FromMegamhos(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] public static ElectricAdmittance Megasiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricAdmittance.FromMegasiemens(double.CreateChecked(value)); + => ElectricAdmittance.FromMegasiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricAdmittance.FromMegasiemens(value.ToDouble(null)); + => ElectricAdmittance.FromMegasiemens(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] public static ElectricAdmittance Mhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricAdmittance.FromMhos(double.CreateChecked(value)); + => ElectricAdmittance.FromMhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricAdmittance.FromMhos(value.ToDouble(null)); + => ElectricAdmittance.FromMhos(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] public static ElectricAdmittance Micromhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricAdmittance.FromMicromhos(double.CreateChecked(value)); + => ElectricAdmittance.FromMicromhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricAdmittance.FromMicromhos(value.ToDouble(null)); + => ElectricAdmittance.FromMicromhos(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] public static ElectricAdmittance Microsiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricAdmittance.FromMicrosiemens(double.CreateChecked(value)); + => ElectricAdmittance.FromMicrosiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricAdmittance.FromMicrosiemens(value.ToDouble(null)); + => ElectricAdmittance.FromMicrosiemens(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] public static ElectricAdmittance Millimhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricAdmittance.FromMillimhos(double.CreateChecked(value)); + => ElectricAdmittance.FromMillimhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricAdmittance.FromMillimhos(value.ToDouble(null)); + => ElectricAdmittance.FromMillimhos(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] public static ElectricAdmittance Millisiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricAdmittance.FromMillisiemens(double.CreateChecked(value)); + => ElectricAdmittance.FromMillisiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricAdmittance.FromMillisiemens(value.ToDouble(null)); + => ElectricAdmittance.FromMillisiemens(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] public static ElectricAdmittance Nanomhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricAdmittance.FromNanomhos(double.CreateChecked(value)); + => ElectricAdmittance.FromNanomhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricAdmittance.FromNanomhos(value.ToDouble(null)); + => ElectricAdmittance.FromNanomhos(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] public static ElectricAdmittance Nanosiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricAdmittance.FromNanosiemens(double.CreateChecked(value)); + => ElectricAdmittance.FromNanosiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricAdmittance.FromNanosiemens(value.ToDouble(null)); + => ElectricAdmittance.FromNanosiemens(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] public static ElectricAdmittance Siemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricAdmittance.FromSiemens(double.CreateChecked(value)); + => ElectricAdmittance.FromSiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricAdmittance.FromSiemens(value.ToDouble(null)); + => ElectricAdmittance.FromSiemens(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] public static ElectricAdmittance Teramhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricAdmittance.FromTeramhos(double.CreateChecked(value)); + => ElectricAdmittance.FromTeramhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricAdmittance.FromTeramhos(value.ToDouble(null)); + => ElectricAdmittance.FromTeramhos(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] public static ElectricAdmittance Terasiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricAdmittance.FromTerasiemens(double.CreateChecked(value)); + => ElectricAdmittance.FromTerasiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricAdmittance.FromTerasiemens(value.ToDouble(null)); + => ElectricAdmittance.FromTerasiemens(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricApparentEnergyExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricApparentEnergyExtensions.g.cs index 68150d2888..6d5c3d32b2 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricApparentEnergyExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricApparentEnergyExtensions.g.cs @@ -32,37 +32,37 @@ namespace UnitsNet.NumberExtensions.NumberToElectricApparentEnergy /// public static class NumberToElectricApparentEnergyExtensions { - /// + /// public static ElectricApparentEnergy KilovoltampereHours(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricApparentEnergy.FromKilovoltampereHours(double.CreateChecked(value)); + => ElectricApparentEnergy.FromKilovoltampereHours(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricApparentEnergy.FromKilovoltampereHours(value.ToDouble(null)); + => ElectricApparentEnergy.FromKilovoltampereHours(value.ToQuantityValue()); #endif - /// + /// public static ElectricApparentEnergy MegavoltampereHours(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricApparentEnergy.FromMegavoltampereHours(double.CreateChecked(value)); + => ElectricApparentEnergy.FromMegavoltampereHours(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricApparentEnergy.FromMegavoltampereHours(value.ToDouble(null)); + => ElectricApparentEnergy.FromMegavoltampereHours(value.ToQuantityValue()); #endif - /// + /// public static ElectricApparentEnergy VoltampereHours(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricApparentEnergy.FromVoltampereHours(double.CreateChecked(value)); + => ElectricApparentEnergy.FromVoltampereHours(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricApparentEnergy.FromVoltampereHours(value.ToDouble(null)); + => ElectricApparentEnergy.FromVoltampereHours(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricApparentPowerExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricApparentPowerExtensions.g.cs index 239697de4b..5d37bc497d 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricApparentPowerExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricApparentPowerExtensions.g.cs @@ -32,70 +32,70 @@ namespace UnitsNet.NumberExtensions.NumberToElectricApparentPower /// public static class NumberToElectricApparentPowerExtensions { - /// + /// public static ElectricApparentPower Gigavoltamperes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricApparentPower.FromGigavoltamperes(double.CreateChecked(value)); + => ElectricApparentPower.FromGigavoltamperes(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricApparentPower.FromGigavoltamperes(value.ToDouble(null)); + => ElectricApparentPower.FromGigavoltamperes(value.ToQuantityValue()); #endif - /// + /// public static ElectricApparentPower Kilovoltamperes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricApparentPower.FromKilovoltamperes(double.CreateChecked(value)); + => ElectricApparentPower.FromKilovoltamperes(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricApparentPower.FromKilovoltamperes(value.ToDouble(null)); + => ElectricApparentPower.FromKilovoltamperes(value.ToQuantityValue()); #endif - /// + /// public static ElectricApparentPower Megavoltamperes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricApparentPower.FromMegavoltamperes(double.CreateChecked(value)); + => ElectricApparentPower.FromMegavoltamperes(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricApparentPower.FromMegavoltamperes(value.ToDouble(null)); + => ElectricApparentPower.FromMegavoltamperes(value.ToQuantityValue()); #endif - /// + /// public static ElectricApparentPower Microvoltamperes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricApparentPower.FromMicrovoltamperes(double.CreateChecked(value)); + => ElectricApparentPower.FromMicrovoltamperes(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricApparentPower.FromMicrovoltamperes(value.ToDouble(null)); + => ElectricApparentPower.FromMicrovoltamperes(value.ToQuantityValue()); #endif - /// + /// public static ElectricApparentPower Millivoltamperes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricApparentPower.FromMillivoltamperes(double.CreateChecked(value)); + => ElectricApparentPower.FromMillivoltamperes(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricApparentPower.FromMillivoltamperes(value.ToDouble(null)); + => ElectricApparentPower.FromMillivoltamperes(value.ToQuantityValue()); #endif - /// + /// public static ElectricApparentPower Voltamperes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricApparentPower.FromVoltamperes(double.CreateChecked(value)); + => ElectricApparentPower.FromVoltamperes(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricApparentPower.FromVoltamperes(value.ToDouble(null)); + => ElectricApparentPower.FromVoltamperes(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricCapacitanceExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricCapacitanceExtensions.g.cs index 314ba14684..94789bcd8c 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricCapacitanceExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricCapacitanceExtensions.g.cs @@ -32,81 +32,81 @@ namespace UnitsNet.NumberExtensions.NumberToElectricCapacitance /// public static class NumberToElectricCapacitanceExtensions { - /// + /// public static ElectricCapacitance Farads(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCapacitance.FromFarads(double.CreateChecked(value)); + => ElectricCapacitance.FromFarads(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCapacitance.FromFarads(value.ToDouble(null)); + => ElectricCapacitance.FromFarads(value.ToQuantityValue()); #endif - /// + /// public static ElectricCapacitance Kilofarads(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCapacitance.FromKilofarads(double.CreateChecked(value)); + => ElectricCapacitance.FromKilofarads(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCapacitance.FromKilofarads(value.ToDouble(null)); + => ElectricCapacitance.FromKilofarads(value.ToQuantityValue()); #endif - /// + /// public static ElectricCapacitance Megafarads(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCapacitance.FromMegafarads(double.CreateChecked(value)); + => ElectricCapacitance.FromMegafarads(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCapacitance.FromMegafarads(value.ToDouble(null)); + => ElectricCapacitance.FromMegafarads(value.ToQuantityValue()); #endif - /// + /// public static ElectricCapacitance Microfarads(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCapacitance.FromMicrofarads(double.CreateChecked(value)); + => ElectricCapacitance.FromMicrofarads(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCapacitance.FromMicrofarads(value.ToDouble(null)); + => ElectricCapacitance.FromMicrofarads(value.ToQuantityValue()); #endif - /// + /// public static ElectricCapacitance Millifarads(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCapacitance.FromMillifarads(double.CreateChecked(value)); + => ElectricCapacitance.FromMillifarads(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCapacitance.FromMillifarads(value.ToDouble(null)); + => ElectricCapacitance.FromMillifarads(value.ToQuantityValue()); #endif - /// + /// public static ElectricCapacitance Nanofarads(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCapacitance.FromNanofarads(double.CreateChecked(value)); + => ElectricCapacitance.FromNanofarads(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCapacitance.FromNanofarads(value.ToDouble(null)); + => ElectricCapacitance.FromNanofarads(value.ToQuantityValue()); #endif - /// + /// public static ElectricCapacitance Picofarads(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCapacitance.FromPicofarads(double.CreateChecked(value)); + => ElectricCapacitance.FromPicofarads(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCapacitance.FromPicofarads(value.ToDouble(null)); + => ElectricCapacitance.FromPicofarads(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricChargeDensityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricChargeDensityExtensions.g.cs index 18614db17a..7bcb06e2c5 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricChargeDensityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricChargeDensityExtensions.g.cs @@ -32,15 +32,15 @@ namespace UnitsNet.NumberExtensions.NumberToElectricChargeDensity /// public static class NumberToElectricChargeDensityExtensions { - /// + /// public static ElectricChargeDensity CoulombsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricChargeDensity.FromCoulombsPerCubicMeter(double.CreateChecked(value)); + => ElectricChargeDensity.FromCoulombsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricChargeDensity.FromCoulombsPerCubicMeter(value.ToDouble(null)); + => ElectricChargeDensity.FromCoulombsPerCubicMeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricChargeExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricChargeExtensions.g.cs index 65081e701a..7a1fe00300 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricChargeExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricChargeExtensions.g.cs @@ -32,125 +32,125 @@ namespace UnitsNet.NumberExtensions.NumberToElectricCharge /// public static class NumberToElectricChargeExtensions { - /// + /// public static ElectricCharge AmpereHours(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCharge.FromAmpereHours(double.CreateChecked(value)); + => ElectricCharge.FromAmpereHours(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCharge.FromAmpereHours(value.ToDouble(null)); + => ElectricCharge.FromAmpereHours(value.ToQuantityValue()); #endif - /// + /// public static ElectricCharge Coulombs(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCharge.FromCoulombs(double.CreateChecked(value)); + => ElectricCharge.FromCoulombs(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCharge.FromCoulombs(value.ToDouble(null)); + => ElectricCharge.FromCoulombs(value.ToQuantityValue()); #endif - /// + /// public static ElectricCharge KiloampereHours(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCharge.FromKiloampereHours(double.CreateChecked(value)); + => ElectricCharge.FromKiloampereHours(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCharge.FromKiloampereHours(value.ToDouble(null)); + => ElectricCharge.FromKiloampereHours(value.ToQuantityValue()); #endif - /// + /// public static ElectricCharge Kilocoulombs(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCharge.FromKilocoulombs(double.CreateChecked(value)); + => ElectricCharge.FromKilocoulombs(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCharge.FromKilocoulombs(value.ToDouble(null)); + => ElectricCharge.FromKilocoulombs(value.ToQuantityValue()); #endif - /// + /// public static ElectricCharge MegaampereHours(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCharge.FromMegaampereHours(double.CreateChecked(value)); + => ElectricCharge.FromMegaampereHours(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCharge.FromMegaampereHours(value.ToDouble(null)); + => ElectricCharge.FromMegaampereHours(value.ToQuantityValue()); #endif - /// + /// public static ElectricCharge Megacoulombs(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCharge.FromMegacoulombs(double.CreateChecked(value)); + => ElectricCharge.FromMegacoulombs(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCharge.FromMegacoulombs(value.ToDouble(null)); + => ElectricCharge.FromMegacoulombs(value.ToQuantityValue()); #endif - /// + /// public static ElectricCharge Microcoulombs(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCharge.FromMicrocoulombs(double.CreateChecked(value)); + => ElectricCharge.FromMicrocoulombs(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCharge.FromMicrocoulombs(value.ToDouble(null)); + => ElectricCharge.FromMicrocoulombs(value.ToQuantityValue()); #endif - /// + /// public static ElectricCharge MilliampereHours(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCharge.FromMilliampereHours(double.CreateChecked(value)); + => ElectricCharge.FromMilliampereHours(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCharge.FromMilliampereHours(value.ToDouble(null)); + => ElectricCharge.FromMilliampereHours(value.ToQuantityValue()); #endif - /// + /// public static ElectricCharge Millicoulombs(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCharge.FromMillicoulombs(double.CreateChecked(value)); + => ElectricCharge.FromMillicoulombs(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCharge.FromMillicoulombs(value.ToDouble(null)); + => ElectricCharge.FromMillicoulombs(value.ToQuantityValue()); #endif - /// + /// public static ElectricCharge Nanocoulombs(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCharge.FromNanocoulombs(double.CreateChecked(value)); + => ElectricCharge.FromNanocoulombs(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCharge.FromNanocoulombs(value.ToDouble(null)); + => ElectricCharge.FromNanocoulombs(value.ToQuantityValue()); #endif - /// + /// public static ElectricCharge Picocoulombs(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCharge.FromPicocoulombs(double.CreateChecked(value)); + => ElectricCharge.FromPicocoulombs(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCharge.FromPicocoulombs(value.ToDouble(null)); + => ElectricCharge.FromPicocoulombs(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricConductanceExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricConductanceExtensions.g.cs index 1ceafdf1c5..547d61a075 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricConductanceExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricConductanceExtensions.g.cs @@ -32,180 +32,180 @@ namespace UnitsNet.NumberExtensions.NumberToElectricConductance /// public static class NumberToElectricConductanceExtensions { - /// + /// public static ElectricConductance Gigamhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductance.FromGigamhos(double.CreateChecked(value)); + => ElectricConductance.FromGigamhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductance.FromGigamhos(value.ToDouble(null)); + => ElectricConductance.FromGigamhos(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductance Gigasiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductance.FromGigasiemens(double.CreateChecked(value)); + => ElectricConductance.FromGigasiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductance.FromGigasiemens(value.ToDouble(null)); + => ElectricConductance.FromGigasiemens(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductance Kilomhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductance.FromKilomhos(double.CreateChecked(value)); + => ElectricConductance.FromKilomhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductance.FromKilomhos(value.ToDouble(null)); + => ElectricConductance.FromKilomhos(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductance Kilosiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductance.FromKilosiemens(double.CreateChecked(value)); + => ElectricConductance.FromKilosiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductance.FromKilosiemens(value.ToDouble(null)); + => ElectricConductance.FromKilosiemens(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductance Megamhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductance.FromMegamhos(double.CreateChecked(value)); + => ElectricConductance.FromMegamhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductance.FromMegamhos(value.ToDouble(null)); + => ElectricConductance.FromMegamhos(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductance Megasiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductance.FromMegasiemens(double.CreateChecked(value)); + => ElectricConductance.FromMegasiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductance.FromMegasiemens(value.ToDouble(null)); + => ElectricConductance.FromMegasiemens(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductance Mhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductance.FromMhos(double.CreateChecked(value)); + => ElectricConductance.FromMhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductance.FromMhos(value.ToDouble(null)); + => ElectricConductance.FromMhos(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductance Micromhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductance.FromMicromhos(double.CreateChecked(value)); + => ElectricConductance.FromMicromhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductance.FromMicromhos(value.ToDouble(null)); + => ElectricConductance.FromMicromhos(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductance Microsiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductance.FromMicrosiemens(double.CreateChecked(value)); + => ElectricConductance.FromMicrosiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductance.FromMicrosiemens(value.ToDouble(null)); + => ElectricConductance.FromMicrosiemens(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductance Millimhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductance.FromMillimhos(double.CreateChecked(value)); + => ElectricConductance.FromMillimhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductance.FromMillimhos(value.ToDouble(null)); + => ElectricConductance.FromMillimhos(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductance Millisiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductance.FromMillisiemens(double.CreateChecked(value)); + => ElectricConductance.FromMillisiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductance.FromMillisiemens(value.ToDouble(null)); + => ElectricConductance.FromMillisiemens(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductance Nanomhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductance.FromNanomhos(double.CreateChecked(value)); + => ElectricConductance.FromNanomhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductance.FromNanomhos(value.ToDouble(null)); + => ElectricConductance.FromNanomhos(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductance Nanosiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductance.FromNanosiemens(double.CreateChecked(value)); + => ElectricConductance.FromNanosiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductance.FromNanosiemens(value.ToDouble(null)); + => ElectricConductance.FromNanosiemens(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductance Siemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductance.FromSiemens(double.CreateChecked(value)); + => ElectricConductance.FromSiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductance.FromSiemens(value.ToDouble(null)); + => ElectricConductance.FromSiemens(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductance Teramhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductance.FromTeramhos(double.CreateChecked(value)); + => ElectricConductance.FromTeramhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductance.FromTeramhos(value.ToDouble(null)); + => ElectricConductance.FromTeramhos(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductance Terasiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductance.FromTerasiemens(double.CreateChecked(value)); + => ElectricConductance.FromTerasiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductance.FromTerasiemens(value.ToDouble(null)); + => ElectricConductance.FromTerasiemens(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricConductivityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricConductivityExtensions.g.cs index a9e1dbd9c0..b12f9623f2 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricConductivityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricConductivityExtensions.g.cs @@ -32,70 +32,70 @@ namespace UnitsNet.NumberExtensions.NumberToElectricConductivity /// public static class NumberToElectricConductivityExtensions { - /// + /// public static ElectricConductivity MicrosiemensPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductivity.FromMicrosiemensPerCentimeter(double.CreateChecked(value)); + => ElectricConductivity.FromMicrosiemensPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductivity.FromMicrosiemensPerCentimeter(value.ToDouble(null)); + => ElectricConductivity.FromMicrosiemensPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductivity MillisiemensPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductivity.FromMillisiemensPerCentimeter(double.CreateChecked(value)); + => ElectricConductivity.FromMillisiemensPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductivity.FromMillisiemensPerCentimeter(value.ToDouble(null)); + => ElectricConductivity.FromMillisiemensPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductivity SiemensPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductivity.FromSiemensPerCentimeter(double.CreateChecked(value)); + => ElectricConductivity.FromSiemensPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductivity.FromSiemensPerCentimeter(value.ToDouble(null)); + => ElectricConductivity.FromSiemensPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductivity SiemensPerFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductivity.FromSiemensPerFoot(double.CreateChecked(value)); + => ElectricConductivity.FromSiemensPerFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductivity.FromSiemensPerFoot(value.ToDouble(null)); + => ElectricConductivity.FromSiemensPerFoot(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductivity SiemensPerInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductivity.FromSiemensPerInch(double.CreateChecked(value)); + => ElectricConductivity.FromSiemensPerInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductivity.FromSiemensPerInch(value.ToDouble(null)); + => ElectricConductivity.FromSiemensPerInch(value.ToQuantityValue()); #endif - /// + /// public static ElectricConductivity SiemensPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricConductivity.FromSiemensPerMeter(double.CreateChecked(value)); + => ElectricConductivity.FromSiemensPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricConductivity.FromSiemensPerMeter(value.ToDouble(null)); + => ElectricConductivity.FromSiemensPerMeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricCurrentDensityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricCurrentDensityExtensions.g.cs index c617a38750..87548fcb22 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricCurrentDensityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricCurrentDensityExtensions.g.cs @@ -32,37 +32,37 @@ namespace UnitsNet.NumberExtensions.NumberToElectricCurrentDensity /// public static class NumberToElectricCurrentDensityExtensions { - /// + /// public static ElectricCurrentDensity AmperesPerSquareFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrentDensity.FromAmperesPerSquareFoot(double.CreateChecked(value)); + => ElectricCurrentDensity.FromAmperesPerSquareFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrentDensity.FromAmperesPerSquareFoot(value.ToDouble(null)); + => ElectricCurrentDensity.FromAmperesPerSquareFoot(value.ToQuantityValue()); #endif - /// + /// public static ElectricCurrentDensity AmperesPerSquareInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrentDensity.FromAmperesPerSquareInch(double.CreateChecked(value)); + => ElectricCurrentDensity.FromAmperesPerSquareInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrentDensity.FromAmperesPerSquareInch(value.ToDouble(null)); + => ElectricCurrentDensity.FromAmperesPerSquareInch(value.ToQuantityValue()); #endif - /// + /// public static ElectricCurrentDensity AmperesPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrentDensity.FromAmperesPerSquareMeter(double.CreateChecked(value)); + => ElectricCurrentDensity.FromAmperesPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrentDensity.FromAmperesPerSquareMeter(value.ToDouble(null)); + => ElectricCurrentDensity.FromAmperesPerSquareMeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricCurrentExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricCurrentExtensions.g.cs index adb8a09db7..2a220ee58c 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricCurrentExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricCurrentExtensions.g.cs @@ -32,103 +32,103 @@ namespace UnitsNet.NumberExtensions.NumberToElectricCurrent /// public static class NumberToElectricCurrentExtensions { - /// + /// public static ElectricCurrent Amperes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrent.FromAmperes(double.CreateChecked(value)); + => ElectricCurrent.FromAmperes(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrent.FromAmperes(value.ToDouble(null)); + => ElectricCurrent.FromAmperes(value.ToQuantityValue()); #endif - /// + /// public static ElectricCurrent Centiamperes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrent.FromCentiamperes(double.CreateChecked(value)); + => ElectricCurrent.FromCentiamperes(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrent.FromCentiamperes(value.ToDouble(null)); + => ElectricCurrent.FromCentiamperes(value.ToQuantityValue()); #endif - /// + /// public static ElectricCurrent Femtoamperes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrent.FromFemtoamperes(double.CreateChecked(value)); + => ElectricCurrent.FromFemtoamperes(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrent.FromFemtoamperes(value.ToDouble(null)); + => ElectricCurrent.FromFemtoamperes(value.ToQuantityValue()); #endif - /// + /// public static ElectricCurrent Kiloamperes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrent.FromKiloamperes(double.CreateChecked(value)); + => ElectricCurrent.FromKiloamperes(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrent.FromKiloamperes(value.ToDouble(null)); + => ElectricCurrent.FromKiloamperes(value.ToQuantityValue()); #endif - /// + /// public static ElectricCurrent Megaamperes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrent.FromMegaamperes(double.CreateChecked(value)); + => ElectricCurrent.FromMegaamperes(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrent.FromMegaamperes(value.ToDouble(null)); + => ElectricCurrent.FromMegaamperes(value.ToQuantityValue()); #endif - /// + /// public static ElectricCurrent Microamperes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrent.FromMicroamperes(double.CreateChecked(value)); + => ElectricCurrent.FromMicroamperes(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrent.FromMicroamperes(value.ToDouble(null)); + => ElectricCurrent.FromMicroamperes(value.ToQuantityValue()); #endif - /// + /// public static ElectricCurrent Milliamperes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrent.FromMilliamperes(double.CreateChecked(value)); + => ElectricCurrent.FromMilliamperes(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrent.FromMilliamperes(value.ToDouble(null)); + => ElectricCurrent.FromMilliamperes(value.ToQuantityValue()); #endif - /// + /// public static ElectricCurrent Nanoamperes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrent.FromNanoamperes(double.CreateChecked(value)); + => ElectricCurrent.FromNanoamperes(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrent.FromNanoamperes(value.ToDouble(null)); + => ElectricCurrent.FromNanoamperes(value.ToQuantityValue()); #endif - /// + /// public static ElectricCurrent Picoamperes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrent.FromPicoamperes(double.CreateChecked(value)); + => ElectricCurrent.FromPicoamperes(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrent.FromPicoamperes(value.ToDouble(null)); + => ElectricCurrent.FromPicoamperes(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricCurrentGradientExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricCurrentGradientExtensions.g.cs index ac56dc17e0..69f7580d1e 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricCurrentGradientExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricCurrentGradientExtensions.g.cs @@ -32,81 +32,81 @@ namespace UnitsNet.NumberExtensions.NumberToElectricCurrentGradient /// public static class NumberToElectricCurrentGradientExtensions { - /// + /// public static ElectricCurrentGradient AmperesPerMicrosecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrentGradient.FromAmperesPerMicrosecond(double.CreateChecked(value)); + => ElectricCurrentGradient.FromAmperesPerMicrosecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrentGradient.FromAmperesPerMicrosecond(value.ToDouble(null)); + => ElectricCurrentGradient.FromAmperesPerMicrosecond(value.ToQuantityValue()); #endif - /// + /// public static ElectricCurrentGradient AmperesPerMillisecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrentGradient.FromAmperesPerMillisecond(double.CreateChecked(value)); + => ElectricCurrentGradient.FromAmperesPerMillisecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrentGradient.FromAmperesPerMillisecond(value.ToDouble(null)); + => ElectricCurrentGradient.FromAmperesPerMillisecond(value.ToQuantityValue()); #endif - /// + /// public static ElectricCurrentGradient AmperesPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrentGradient.FromAmperesPerMinute(double.CreateChecked(value)); + => ElectricCurrentGradient.FromAmperesPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrentGradient.FromAmperesPerMinute(value.ToDouble(null)); + => ElectricCurrentGradient.FromAmperesPerMinute(value.ToQuantityValue()); #endif - /// + /// public static ElectricCurrentGradient AmperesPerNanosecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrentGradient.FromAmperesPerNanosecond(double.CreateChecked(value)); + => ElectricCurrentGradient.FromAmperesPerNanosecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrentGradient.FromAmperesPerNanosecond(value.ToDouble(null)); + => ElectricCurrentGradient.FromAmperesPerNanosecond(value.ToQuantityValue()); #endif - /// + /// public static ElectricCurrentGradient AmperesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrentGradient.FromAmperesPerSecond(double.CreateChecked(value)); + => ElectricCurrentGradient.FromAmperesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrentGradient.FromAmperesPerSecond(value.ToDouble(null)); + => ElectricCurrentGradient.FromAmperesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static ElectricCurrentGradient MilliamperesPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrentGradient.FromMilliamperesPerMinute(double.CreateChecked(value)); + => ElectricCurrentGradient.FromMilliamperesPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrentGradient.FromMilliamperesPerMinute(value.ToDouble(null)); + => ElectricCurrentGradient.FromMilliamperesPerMinute(value.ToQuantityValue()); #endif - /// + /// public static ElectricCurrentGradient MilliamperesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricCurrentGradient.FromMilliamperesPerSecond(double.CreateChecked(value)); + => ElectricCurrentGradient.FromMilliamperesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricCurrentGradient.FromMilliamperesPerSecond(value.ToDouble(null)); + => ElectricCurrentGradient.FromMilliamperesPerSecond(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricFieldExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricFieldExtensions.g.cs index 05c1a8de62..8f9406a1a5 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricFieldExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricFieldExtensions.g.cs @@ -32,15 +32,15 @@ namespace UnitsNet.NumberExtensions.NumberToElectricField /// public static class NumberToElectricFieldExtensions { - /// + /// public static ElectricField VoltsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricField.FromVoltsPerMeter(double.CreateChecked(value)); + => ElectricField.FromVoltsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricField.FromVoltsPerMeter(value.ToDouble(null)); + => ElectricField.FromVoltsPerMeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricImpedanceExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricImpedanceExtensions.g.cs index b3b2a9ba52..7b61247548 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricImpedanceExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricImpedanceExtensions.g.cs @@ -33,100 +33,100 @@ namespace UnitsNet.NumberExtensions.NumberToElectricImpedance [Obsolete("Impedance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricResistance or ElectricReactance instead.")] public static class NumberToElectricImpedanceExtensions { - /// + /// [Obsolete("Impedance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricResistance or ElectricReactance instead.")] public static ElectricImpedance Gigaohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricImpedance.FromGigaohms(double.CreateChecked(value)); + => ElectricImpedance.FromGigaohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricImpedance.FromGigaohms(value.ToDouble(null)); + => ElectricImpedance.FromGigaohms(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Impedance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricResistance or ElectricReactance instead.")] public static ElectricImpedance Kiloohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricImpedance.FromKiloohms(double.CreateChecked(value)); + => ElectricImpedance.FromKiloohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricImpedance.FromKiloohms(value.ToDouble(null)); + => ElectricImpedance.FromKiloohms(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Impedance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricResistance or ElectricReactance instead.")] public static ElectricImpedance Megaohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricImpedance.FromMegaohms(double.CreateChecked(value)); + => ElectricImpedance.FromMegaohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricImpedance.FromMegaohms(value.ToDouble(null)); + => ElectricImpedance.FromMegaohms(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Impedance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricResistance or ElectricReactance instead.")] public static ElectricImpedance Microohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricImpedance.FromMicroohms(double.CreateChecked(value)); + => ElectricImpedance.FromMicroohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricImpedance.FromMicroohms(value.ToDouble(null)); + => ElectricImpedance.FromMicroohms(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Impedance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricResistance or ElectricReactance instead.")] public static ElectricImpedance Milliohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricImpedance.FromMilliohms(double.CreateChecked(value)); + => ElectricImpedance.FromMilliohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricImpedance.FromMilliohms(value.ToDouble(null)); + => ElectricImpedance.FromMilliohms(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Impedance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricResistance or ElectricReactance instead.")] public static ElectricImpedance Nanoohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricImpedance.FromNanoohms(double.CreateChecked(value)); + => ElectricImpedance.FromNanoohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricImpedance.FromNanoohms(value.ToDouble(null)); + => ElectricImpedance.FromNanoohms(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Impedance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricResistance or ElectricReactance instead.")] public static ElectricImpedance Ohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricImpedance.FromOhms(double.CreateChecked(value)); + => ElectricImpedance.FromOhms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricImpedance.FromOhms(value.ToDouble(null)); + => ElectricImpedance.FromOhms(value.ToQuantityValue()); #endif - /// + /// [Obsolete("Impedance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricResistance or ElectricReactance instead.")] public static ElectricImpedance Teraohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricImpedance.FromTeraohms(double.CreateChecked(value)); + => ElectricImpedance.FromTeraohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricImpedance.FromTeraohms(value.ToDouble(null)); + => ElectricImpedance.FromTeraohms(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricInductanceExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricInductanceExtensions.g.cs index bc0ce716f4..c239b5044d 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricInductanceExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricInductanceExtensions.g.cs @@ -32,59 +32,59 @@ namespace UnitsNet.NumberExtensions.NumberToElectricInductance /// public static class NumberToElectricInductanceExtensions { - /// + /// public static ElectricInductance Henries(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricInductance.FromHenries(double.CreateChecked(value)); + => ElectricInductance.FromHenries(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricInductance.FromHenries(value.ToDouble(null)); + => ElectricInductance.FromHenries(value.ToQuantityValue()); #endif - /// + /// public static ElectricInductance Microhenries(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricInductance.FromMicrohenries(double.CreateChecked(value)); + => ElectricInductance.FromMicrohenries(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricInductance.FromMicrohenries(value.ToDouble(null)); + => ElectricInductance.FromMicrohenries(value.ToQuantityValue()); #endif - /// + /// public static ElectricInductance Millihenries(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricInductance.FromMillihenries(double.CreateChecked(value)); + => ElectricInductance.FromMillihenries(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricInductance.FromMillihenries(value.ToDouble(null)); + => ElectricInductance.FromMillihenries(value.ToQuantityValue()); #endif - /// + /// public static ElectricInductance Nanohenries(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricInductance.FromNanohenries(double.CreateChecked(value)); + => ElectricInductance.FromNanohenries(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricInductance.FromNanohenries(value.ToDouble(null)); + => ElectricInductance.FromNanohenries(value.ToQuantityValue()); #endif - /// + /// public static ElectricInductance Picohenries(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricInductance.FromPicohenries(double.CreateChecked(value)); + => ElectricInductance.FromPicohenries(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricInductance.FromPicohenries(value.ToDouble(null)); + => ElectricInductance.FromPicohenries(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricPotentialChangeRateExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricPotentialChangeRateExtensions.g.cs index ae7d19c814..a8f0933f2c 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricPotentialChangeRateExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricPotentialChangeRateExtensions.g.cs @@ -32,224 +32,224 @@ namespace UnitsNet.NumberExtensions.NumberToElectricPotentialChangeRate /// public static class NumberToElectricPotentialChangeRateExtensions { - /// + /// public static ElectricPotentialChangeRate KilovoltsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromKilovoltsPerHour(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromKilovoltsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromKilovoltsPerHour(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromKilovoltsPerHour(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate KilovoltsPerMicrosecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromKilovoltsPerMicrosecond(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromKilovoltsPerMicrosecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromKilovoltsPerMicrosecond(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromKilovoltsPerMicrosecond(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate KilovoltsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromKilovoltsPerMinute(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromKilovoltsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromKilovoltsPerMinute(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromKilovoltsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate KilovoltsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromKilovoltsPerSecond(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromKilovoltsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromKilovoltsPerSecond(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromKilovoltsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate MegavoltsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromMegavoltsPerHour(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromMegavoltsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromMegavoltsPerHour(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromMegavoltsPerHour(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate MegavoltsPerMicrosecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromMegavoltsPerMicrosecond(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromMegavoltsPerMicrosecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromMegavoltsPerMicrosecond(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromMegavoltsPerMicrosecond(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate MegavoltsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromMegavoltsPerMinute(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromMegavoltsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromMegavoltsPerMinute(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromMegavoltsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate MegavoltsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromMegavoltsPerSecond(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromMegavoltsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromMegavoltsPerSecond(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromMegavoltsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate MicrovoltsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromMicrovoltsPerHour(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromMicrovoltsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromMicrovoltsPerHour(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromMicrovoltsPerHour(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate MicrovoltsPerMicrosecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromMicrovoltsPerMicrosecond(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromMicrovoltsPerMicrosecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromMicrovoltsPerMicrosecond(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromMicrovoltsPerMicrosecond(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate MicrovoltsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromMicrovoltsPerMinute(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromMicrovoltsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromMicrovoltsPerMinute(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromMicrovoltsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate MicrovoltsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromMicrovoltsPerSecond(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromMicrovoltsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromMicrovoltsPerSecond(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromMicrovoltsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate MillivoltsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromMillivoltsPerHour(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromMillivoltsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromMillivoltsPerHour(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromMillivoltsPerHour(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate MillivoltsPerMicrosecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromMillivoltsPerMicrosecond(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromMillivoltsPerMicrosecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromMillivoltsPerMicrosecond(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromMillivoltsPerMicrosecond(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate MillivoltsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromMillivoltsPerMinute(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromMillivoltsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromMillivoltsPerMinute(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromMillivoltsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate MillivoltsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromMillivoltsPerSecond(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromMillivoltsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromMillivoltsPerSecond(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromMillivoltsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate VoltsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromVoltsPerHour(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromVoltsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromVoltsPerHour(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromVoltsPerHour(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate VoltsPerMicrosecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromVoltsPerMicrosecond(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromVoltsPerMicrosecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromVoltsPerMicrosecond(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromVoltsPerMicrosecond(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate VoltsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromVoltsPerMinute(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromVoltsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromVoltsPerMinute(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromVoltsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotentialChangeRate VoltsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotentialChangeRate.FromVoltsPerSecond(double.CreateChecked(value)); + => ElectricPotentialChangeRate.FromVoltsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotentialChangeRate.FromVoltsPerSecond(value.ToDouble(null)); + => ElectricPotentialChangeRate.FromVoltsPerSecond(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricPotentialExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricPotentialExtensions.g.cs index 4f1cb041b0..26001885bc 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricPotentialExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricPotentialExtensions.g.cs @@ -32,70 +32,70 @@ namespace UnitsNet.NumberExtensions.NumberToElectricPotential /// public static class NumberToElectricPotentialExtensions { - /// + /// public static ElectricPotential Kilovolts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotential.FromKilovolts(double.CreateChecked(value)); + => ElectricPotential.FromKilovolts(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotential.FromKilovolts(value.ToDouble(null)); + => ElectricPotential.FromKilovolts(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotential Megavolts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotential.FromMegavolts(double.CreateChecked(value)); + => ElectricPotential.FromMegavolts(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotential.FromMegavolts(value.ToDouble(null)); + => ElectricPotential.FromMegavolts(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotential Microvolts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotential.FromMicrovolts(double.CreateChecked(value)); + => ElectricPotential.FromMicrovolts(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotential.FromMicrovolts(value.ToDouble(null)); + => ElectricPotential.FromMicrovolts(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotential Millivolts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotential.FromMillivolts(double.CreateChecked(value)); + => ElectricPotential.FromMillivolts(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotential.FromMillivolts(value.ToDouble(null)); + => ElectricPotential.FromMillivolts(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotential Nanovolts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotential.FromNanovolts(double.CreateChecked(value)); + => ElectricPotential.FromNanovolts(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotential.FromNanovolts(value.ToDouble(null)); + => ElectricPotential.FromNanovolts(value.ToQuantityValue()); #endif - /// + /// public static ElectricPotential Volts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricPotential.FromVolts(double.CreateChecked(value)); + => ElectricPotential.FromVolts(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricPotential.FromVolts(value.ToDouble(null)); + => ElectricPotential.FromVolts(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricReactanceExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricReactanceExtensions.g.cs index 3aee4ab12f..f6ec657790 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricReactanceExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricReactanceExtensions.g.cs @@ -32,92 +32,92 @@ namespace UnitsNet.NumberExtensions.NumberToElectricReactance /// public static class NumberToElectricReactanceExtensions { - /// + /// public static ElectricReactance Gigaohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricReactance.FromGigaohms(double.CreateChecked(value)); + => ElectricReactance.FromGigaohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricReactance.FromGigaohms(value.ToDouble(null)); + => ElectricReactance.FromGigaohms(value.ToQuantityValue()); #endif - /// + /// public static ElectricReactance Kiloohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricReactance.FromKiloohms(double.CreateChecked(value)); + => ElectricReactance.FromKiloohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricReactance.FromKiloohms(value.ToDouble(null)); + => ElectricReactance.FromKiloohms(value.ToQuantityValue()); #endif - /// + /// public static ElectricReactance Megaohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricReactance.FromMegaohms(double.CreateChecked(value)); + => ElectricReactance.FromMegaohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricReactance.FromMegaohms(value.ToDouble(null)); + => ElectricReactance.FromMegaohms(value.ToQuantityValue()); #endif - /// + /// public static ElectricReactance Microohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricReactance.FromMicroohms(double.CreateChecked(value)); + => ElectricReactance.FromMicroohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricReactance.FromMicroohms(value.ToDouble(null)); + => ElectricReactance.FromMicroohms(value.ToQuantityValue()); #endif - /// + /// public static ElectricReactance Milliohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricReactance.FromMilliohms(double.CreateChecked(value)); + => ElectricReactance.FromMilliohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricReactance.FromMilliohms(value.ToDouble(null)); + => ElectricReactance.FromMilliohms(value.ToQuantityValue()); #endif - /// + /// public static ElectricReactance Nanoohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricReactance.FromNanoohms(double.CreateChecked(value)); + => ElectricReactance.FromNanoohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricReactance.FromNanoohms(value.ToDouble(null)); + => ElectricReactance.FromNanoohms(value.ToQuantityValue()); #endif - /// + /// public static ElectricReactance Ohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricReactance.FromOhms(double.CreateChecked(value)); + => ElectricReactance.FromOhms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricReactance.FromOhms(value.ToDouble(null)); + => ElectricReactance.FromOhms(value.ToQuantityValue()); #endif - /// + /// public static ElectricReactance Teraohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricReactance.FromTeraohms(double.CreateChecked(value)); + => ElectricReactance.FromTeraohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricReactance.FromTeraohms(value.ToDouble(null)); + => ElectricReactance.FromTeraohms(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricReactiveEnergyExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricReactiveEnergyExtensions.g.cs index 402ab24ed2..d4acf99ac1 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricReactiveEnergyExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricReactiveEnergyExtensions.g.cs @@ -32,37 +32,37 @@ namespace UnitsNet.NumberExtensions.NumberToElectricReactiveEnergy /// public static class NumberToElectricReactiveEnergyExtensions { - /// + /// public static ElectricReactiveEnergy KilovoltampereReactiveHours(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricReactiveEnergy.FromKilovoltampereReactiveHours(double.CreateChecked(value)); + => ElectricReactiveEnergy.FromKilovoltampereReactiveHours(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricReactiveEnergy.FromKilovoltampereReactiveHours(value.ToDouble(null)); + => ElectricReactiveEnergy.FromKilovoltampereReactiveHours(value.ToQuantityValue()); #endif - /// + /// public static ElectricReactiveEnergy MegavoltampereReactiveHours(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricReactiveEnergy.FromMegavoltampereReactiveHours(double.CreateChecked(value)); + => ElectricReactiveEnergy.FromMegavoltampereReactiveHours(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricReactiveEnergy.FromMegavoltampereReactiveHours(value.ToDouble(null)); + => ElectricReactiveEnergy.FromMegavoltampereReactiveHours(value.ToQuantityValue()); #endif - /// + /// public static ElectricReactiveEnergy VoltampereReactiveHours(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricReactiveEnergy.FromVoltampereReactiveHours(double.CreateChecked(value)); + => ElectricReactiveEnergy.FromVoltampereReactiveHours(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricReactiveEnergy.FromVoltampereReactiveHours(value.ToDouble(null)); + => ElectricReactiveEnergy.FromVoltampereReactiveHours(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricReactivePowerExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricReactivePowerExtensions.g.cs index 0ad77fa1f1..651c311725 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricReactivePowerExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricReactivePowerExtensions.g.cs @@ -32,48 +32,48 @@ namespace UnitsNet.NumberExtensions.NumberToElectricReactivePower /// public static class NumberToElectricReactivePowerExtensions { - /// + /// public static ElectricReactivePower GigavoltamperesReactive(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricReactivePower.FromGigavoltamperesReactive(double.CreateChecked(value)); + => ElectricReactivePower.FromGigavoltamperesReactive(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricReactivePower.FromGigavoltamperesReactive(value.ToDouble(null)); + => ElectricReactivePower.FromGigavoltamperesReactive(value.ToQuantityValue()); #endif - /// + /// public static ElectricReactivePower KilovoltamperesReactive(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricReactivePower.FromKilovoltamperesReactive(double.CreateChecked(value)); + => ElectricReactivePower.FromKilovoltamperesReactive(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricReactivePower.FromKilovoltamperesReactive(value.ToDouble(null)); + => ElectricReactivePower.FromKilovoltamperesReactive(value.ToQuantityValue()); #endif - /// + /// public static ElectricReactivePower MegavoltamperesReactive(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricReactivePower.FromMegavoltamperesReactive(double.CreateChecked(value)); + => ElectricReactivePower.FromMegavoltamperesReactive(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricReactivePower.FromMegavoltamperesReactive(value.ToDouble(null)); + => ElectricReactivePower.FromMegavoltamperesReactive(value.ToQuantityValue()); #endif - /// + /// public static ElectricReactivePower VoltamperesReactive(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricReactivePower.FromVoltamperesReactive(double.CreateChecked(value)); + => ElectricReactivePower.FromVoltamperesReactive(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricReactivePower.FromVoltamperesReactive(value.ToDouble(null)); + => ElectricReactivePower.FromVoltamperesReactive(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricResistanceExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricResistanceExtensions.g.cs index 2d1953bf75..fb0737a4e6 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricResistanceExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricResistanceExtensions.g.cs @@ -32,92 +32,92 @@ namespace UnitsNet.NumberExtensions.NumberToElectricResistance /// public static class NumberToElectricResistanceExtensions { - /// + /// public static ElectricResistance Gigaohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistance.FromGigaohms(double.CreateChecked(value)); + => ElectricResistance.FromGigaohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistance.FromGigaohms(value.ToDouble(null)); + => ElectricResistance.FromGigaohms(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistance Kiloohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistance.FromKiloohms(double.CreateChecked(value)); + => ElectricResistance.FromKiloohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistance.FromKiloohms(value.ToDouble(null)); + => ElectricResistance.FromKiloohms(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistance Megaohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistance.FromMegaohms(double.CreateChecked(value)); + => ElectricResistance.FromMegaohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistance.FromMegaohms(value.ToDouble(null)); + => ElectricResistance.FromMegaohms(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistance Microohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistance.FromMicroohms(double.CreateChecked(value)); + => ElectricResistance.FromMicroohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistance.FromMicroohms(value.ToDouble(null)); + => ElectricResistance.FromMicroohms(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistance Milliohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistance.FromMilliohms(double.CreateChecked(value)); + => ElectricResistance.FromMilliohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistance.FromMilliohms(value.ToDouble(null)); + => ElectricResistance.FromMilliohms(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistance Nanoohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistance.FromNanoohms(double.CreateChecked(value)); + => ElectricResistance.FromNanoohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistance.FromNanoohms(value.ToDouble(null)); + => ElectricResistance.FromNanoohms(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistance Ohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistance.FromOhms(double.CreateChecked(value)); + => ElectricResistance.FromOhms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistance.FromOhms(value.ToDouble(null)); + => ElectricResistance.FromOhms(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistance Teraohms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistance.FromTeraohms(double.CreateChecked(value)); + => ElectricResistance.FromTeraohms(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistance.FromTeraohms(value.ToDouble(null)); + => ElectricResistance.FromTeraohms(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricResistivityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricResistivityExtensions.g.cs index 558fc64eb2..68334bf74f 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricResistivityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricResistivityExtensions.g.cs @@ -32,158 +32,158 @@ namespace UnitsNet.NumberExtensions.NumberToElectricResistivity /// public static class NumberToElectricResistivityExtensions { - /// + /// public static ElectricResistivity KiloohmsCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistivity.FromKiloohmsCentimeter(double.CreateChecked(value)); + => ElectricResistivity.FromKiloohmsCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistivity.FromKiloohmsCentimeter(value.ToDouble(null)); + => ElectricResistivity.FromKiloohmsCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistivity KiloohmMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistivity.FromKiloohmMeters(double.CreateChecked(value)); + => ElectricResistivity.FromKiloohmMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistivity.FromKiloohmMeters(value.ToDouble(null)); + => ElectricResistivity.FromKiloohmMeters(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistivity MegaohmsCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistivity.FromMegaohmsCentimeter(double.CreateChecked(value)); + => ElectricResistivity.FromMegaohmsCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistivity.FromMegaohmsCentimeter(value.ToDouble(null)); + => ElectricResistivity.FromMegaohmsCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistivity MegaohmMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistivity.FromMegaohmMeters(double.CreateChecked(value)); + => ElectricResistivity.FromMegaohmMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistivity.FromMegaohmMeters(value.ToDouble(null)); + => ElectricResistivity.FromMegaohmMeters(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistivity MicroohmsCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistivity.FromMicroohmsCentimeter(double.CreateChecked(value)); + => ElectricResistivity.FromMicroohmsCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistivity.FromMicroohmsCentimeter(value.ToDouble(null)); + => ElectricResistivity.FromMicroohmsCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistivity MicroohmMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistivity.FromMicroohmMeters(double.CreateChecked(value)); + => ElectricResistivity.FromMicroohmMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistivity.FromMicroohmMeters(value.ToDouble(null)); + => ElectricResistivity.FromMicroohmMeters(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistivity MilliohmsCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistivity.FromMilliohmsCentimeter(double.CreateChecked(value)); + => ElectricResistivity.FromMilliohmsCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistivity.FromMilliohmsCentimeter(value.ToDouble(null)); + => ElectricResistivity.FromMilliohmsCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistivity MilliohmMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistivity.FromMilliohmMeters(double.CreateChecked(value)); + => ElectricResistivity.FromMilliohmMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistivity.FromMilliohmMeters(value.ToDouble(null)); + => ElectricResistivity.FromMilliohmMeters(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistivity NanoohmsCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistivity.FromNanoohmsCentimeter(double.CreateChecked(value)); + => ElectricResistivity.FromNanoohmsCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistivity.FromNanoohmsCentimeter(value.ToDouble(null)); + => ElectricResistivity.FromNanoohmsCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistivity NanoohmMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistivity.FromNanoohmMeters(double.CreateChecked(value)); + => ElectricResistivity.FromNanoohmMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistivity.FromNanoohmMeters(value.ToDouble(null)); + => ElectricResistivity.FromNanoohmMeters(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistivity OhmsCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistivity.FromOhmsCentimeter(double.CreateChecked(value)); + => ElectricResistivity.FromOhmsCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistivity.FromOhmsCentimeter(value.ToDouble(null)); + => ElectricResistivity.FromOhmsCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistivity OhmMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistivity.FromOhmMeters(double.CreateChecked(value)); + => ElectricResistivity.FromOhmMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistivity.FromOhmMeters(value.ToDouble(null)); + => ElectricResistivity.FromOhmMeters(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistivity PicoohmsCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistivity.FromPicoohmsCentimeter(double.CreateChecked(value)); + => ElectricResistivity.FromPicoohmsCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistivity.FromPicoohmsCentimeter(value.ToDouble(null)); + => ElectricResistivity.FromPicoohmsCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ElectricResistivity PicoohmMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricResistivity.FromPicoohmMeters(double.CreateChecked(value)); + => ElectricResistivity.FromPicoohmMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricResistivity.FromPicoohmMeters(value.ToDouble(null)); + => ElectricResistivity.FromPicoohmMeters(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricSurfaceChargeDensityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricSurfaceChargeDensityExtensions.g.cs index d28a14e8af..3f1edac0b2 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricSurfaceChargeDensityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricSurfaceChargeDensityExtensions.g.cs @@ -32,37 +32,37 @@ namespace UnitsNet.NumberExtensions.NumberToElectricSurfaceChargeDensity /// public static class NumberToElectricSurfaceChargeDensityExtensions { - /// + /// public static ElectricSurfaceChargeDensity CoulombsPerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSurfaceChargeDensity.FromCoulombsPerSquareCentimeter(double.CreateChecked(value)); + => ElectricSurfaceChargeDensity.FromCoulombsPerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSurfaceChargeDensity.FromCoulombsPerSquareCentimeter(value.ToDouble(null)); + => ElectricSurfaceChargeDensity.FromCoulombsPerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ElectricSurfaceChargeDensity CoulombsPerSquareInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSurfaceChargeDensity.FromCoulombsPerSquareInch(double.CreateChecked(value)); + => ElectricSurfaceChargeDensity.FromCoulombsPerSquareInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSurfaceChargeDensity.FromCoulombsPerSquareInch(value.ToDouble(null)); + => ElectricSurfaceChargeDensity.FromCoulombsPerSquareInch(value.ToQuantityValue()); #endif - /// + /// public static ElectricSurfaceChargeDensity CoulombsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(double.CreateChecked(value)); + => ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(value.ToDouble(null)); + => ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricSusceptanceExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricSusceptanceExtensions.g.cs index db36d33d50..ca94d5c3d7 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricSusceptanceExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToElectricSusceptanceExtensions.g.cs @@ -32,180 +32,180 @@ namespace UnitsNet.NumberExtensions.NumberToElectricSusceptance /// public static class NumberToElectricSusceptanceExtensions { - /// + /// public static ElectricSusceptance Gigamhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSusceptance.FromGigamhos(double.CreateChecked(value)); + => ElectricSusceptance.FromGigamhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSusceptance.FromGigamhos(value.ToDouble(null)); + => ElectricSusceptance.FromGigamhos(value.ToQuantityValue()); #endif - /// + /// public static ElectricSusceptance Gigasiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSusceptance.FromGigasiemens(double.CreateChecked(value)); + => ElectricSusceptance.FromGigasiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSusceptance.FromGigasiemens(value.ToDouble(null)); + => ElectricSusceptance.FromGigasiemens(value.ToQuantityValue()); #endif - /// + /// public static ElectricSusceptance Kilomhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSusceptance.FromKilomhos(double.CreateChecked(value)); + => ElectricSusceptance.FromKilomhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSusceptance.FromKilomhos(value.ToDouble(null)); + => ElectricSusceptance.FromKilomhos(value.ToQuantityValue()); #endif - /// + /// public static ElectricSusceptance Kilosiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSusceptance.FromKilosiemens(double.CreateChecked(value)); + => ElectricSusceptance.FromKilosiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSusceptance.FromKilosiemens(value.ToDouble(null)); + => ElectricSusceptance.FromKilosiemens(value.ToQuantityValue()); #endif - /// + /// public static ElectricSusceptance Megamhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSusceptance.FromMegamhos(double.CreateChecked(value)); + => ElectricSusceptance.FromMegamhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSusceptance.FromMegamhos(value.ToDouble(null)); + => ElectricSusceptance.FromMegamhos(value.ToQuantityValue()); #endif - /// + /// public static ElectricSusceptance Megasiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSusceptance.FromMegasiemens(double.CreateChecked(value)); + => ElectricSusceptance.FromMegasiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSusceptance.FromMegasiemens(value.ToDouble(null)); + => ElectricSusceptance.FromMegasiemens(value.ToQuantityValue()); #endif - /// + /// public static ElectricSusceptance Mhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSusceptance.FromMhos(double.CreateChecked(value)); + => ElectricSusceptance.FromMhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSusceptance.FromMhos(value.ToDouble(null)); + => ElectricSusceptance.FromMhos(value.ToQuantityValue()); #endif - /// + /// public static ElectricSusceptance Micromhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSusceptance.FromMicromhos(double.CreateChecked(value)); + => ElectricSusceptance.FromMicromhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSusceptance.FromMicromhos(value.ToDouble(null)); + => ElectricSusceptance.FromMicromhos(value.ToQuantityValue()); #endif - /// + /// public static ElectricSusceptance Microsiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSusceptance.FromMicrosiemens(double.CreateChecked(value)); + => ElectricSusceptance.FromMicrosiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSusceptance.FromMicrosiemens(value.ToDouble(null)); + => ElectricSusceptance.FromMicrosiemens(value.ToQuantityValue()); #endif - /// + /// public static ElectricSusceptance Millimhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSusceptance.FromMillimhos(double.CreateChecked(value)); + => ElectricSusceptance.FromMillimhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSusceptance.FromMillimhos(value.ToDouble(null)); + => ElectricSusceptance.FromMillimhos(value.ToQuantityValue()); #endif - /// + /// public static ElectricSusceptance Millisiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSusceptance.FromMillisiemens(double.CreateChecked(value)); + => ElectricSusceptance.FromMillisiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSusceptance.FromMillisiemens(value.ToDouble(null)); + => ElectricSusceptance.FromMillisiemens(value.ToQuantityValue()); #endif - /// + /// public static ElectricSusceptance Nanomhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSusceptance.FromNanomhos(double.CreateChecked(value)); + => ElectricSusceptance.FromNanomhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSusceptance.FromNanomhos(value.ToDouble(null)); + => ElectricSusceptance.FromNanomhos(value.ToQuantityValue()); #endif - /// + /// public static ElectricSusceptance Nanosiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSusceptance.FromNanosiemens(double.CreateChecked(value)); + => ElectricSusceptance.FromNanosiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSusceptance.FromNanosiemens(value.ToDouble(null)); + => ElectricSusceptance.FromNanosiemens(value.ToQuantityValue()); #endif - /// + /// public static ElectricSusceptance Siemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSusceptance.FromSiemens(double.CreateChecked(value)); + => ElectricSusceptance.FromSiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSusceptance.FromSiemens(value.ToDouble(null)); + => ElectricSusceptance.FromSiemens(value.ToQuantityValue()); #endif - /// + /// public static ElectricSusceptance Teramhos(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSusceptance.FromTeramhos(double.CreateChecked(value)); + => ElectricSusceptance.FromTeramhos(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSusceptance.FromTeramhos(value.ToDouble(null)); + => ElectricSusceptance.FromTeramhos(value.ToQuantityValue()); #endif - /// + /// public static ElectricSusceptance Terasiemens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ElectricSusceptance.FromTerasiemens(double.CreateChecked(value)); + => ElectricSusceptance.FromTerasiemens(QuantityValue.CreateChecked(value)); #else , IConvertible - => ElectricSusceptance.FromTerasiemens(value.ToDouble(null)); + => ElectricSusceptance.FromTerasiemens(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToEnergyDensityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToEnergyDensityExtensions.g.cs index 24007897fa..f54dea1f03 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToEnergyDensityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToEnergyDensityExtensions.g.cs @@ -32,136 +32,136 @@ namespace UnitsNet.NumberExtensions.NumberToEnergyDensity /// public static class NumberToEnergyDensityExtensions { - /// + /// public static EnergyDensity GigajoulesPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => EnergyDensity.FromGigajoulesPerCubicMeter(double.CreateChecked(value)); + => EnergyDensity.FromGigajoulesPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => EnergyDensity.FromGigajoulesPerCubicMeter(value.ToDouble(null)); + => EnergyDensity.FromGigajoulesPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static EnergyDensity GigawattHoursPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => EnergyDensity.FromGigawattHoursPerCubicMeter(double.CreateChecked(value)); + => EnergyDensity.FromGigawattHoursPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => EnergyDensity.FromGigawattHoursPerCubicMeter(value.ToDouble(null)); + => EnergyDensity.FromGigawattHoursPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static EnergyDensity JoulesPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => EnergyDensity.FromJoulesPerCubicMeter(double.CreateChecked(value)); + => EnergyDensity.FromJoulesPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => EnergyDensity.FromJoulesPerCubicMeter(value.ToDouble(null)); + => EnergyDensity.FromJoulesPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static EnergyDensity KilojoulesPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => EnergyDensity.FromKilojoulesPerCubicMeter(double.CreateChecked(value)); + => EnergyDensity.FromKilojoulesPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => EnergyDensity.FromKilojoulesPerCubicMeter(value.ToDouble(null)); + => EnergyDensity.FromKilojoulesPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static EnergyDensity KilowattHoursPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => EnergyDensity.FromKilowattHoursPerCubicMeter(double.CreateChecked(value)); + => EnergyDensity.FromKilowattHoursPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => EnergyDensity.FromKilowattHoursPerCubicMeter(value.ToDouble(null)); + => EnergyDensity.FromKilowattHoursPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static EnergyDensity MegajoulesPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => EnergyDensity.FromMegajoulesPerCubicMeter(double.CreateChecked(value)); + => EnergyDensity.FromMegajoulesPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => EnergyDensity.FromMegajoulesPerCubicMeter(value.ToDouble(null)); + => EnergyDensity.FromMegajoulesPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static EnergyDensity MegawattHoursPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => EnergyDensity.FromMegawattHoursPerCubicMeter(double.CreateChecked(value)); + => EnergyDensity.FromMegawattHoursPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => EnergyDensity.FromMegawattHoursPerCubicMeter(value.ToDouble(null)); + => EnergyDensity.FromMegawattHoursPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static EnergyDensity PetajoulesPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => EnergyDensity.FromPetajoulesPerCubicMeter(double.CreateChecked(value)); + => EnergyDensity.FromPetajoulesPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => EnergyDensity.FromPetajoulesPerCubicMeter(value.ToDouble(null)); + => EnergyDensity.FromPetajoulesPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static EnergyDensity PetawattHoursPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => EnergyDensity.FromPetawattHoursPerCubicMeter(double.CreateChecked(value)); + => EnergyDensity.FromPetawattHoursPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => EnergyDensity.FromPetawattHoursPerCubicMeter(value.ToDouble(null)); + => EnergyDensity.FromPetawattHoursPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static EnergyDensity TerajoulesPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => EnergyDensity.FromTerajoulesPerCubicMeter(double.CreateChecked(value)); + => EnergyDensity.FromTerajoulesPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => EnergyDensity.FromTerajoulesPerCubicMeter(value.ToDouble(null)); + => EnergyDensity.FromTerajoulesPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static EnergyDensity TerawattHoursPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => EnergyDensity.FromTerawattHoursPerCubicMeter(double.CreateChecked(value)); + => EnergyDensity.FromTerawattHoursPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => EnergyDensity.FromTerawattHoursPerCubicMeter(value.ToDouble(null)); + => EnergyDensity.FromTerawattHoursPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static EnergyDensity WattHoursPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => EnergyDensity.FromWattHoursPerCubicMeter(double.CreateChecked(value)); + => EnergyDensity.FromWattHoursPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => EnergyDensity.FromWattHoursPerCubicMeter(value.ToDouble(null)); + => EnergyDensity.FromWattHoursPerCubicMeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToEnergyExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToEnergyExtensions.g.cs index 50db7a9579..1cec063180 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToEnergyExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToEnergyExtensions.g.cs @@ -32,444 +32,444 @@ namespace UnitsNet.NumberExtensions.NumberToEnergy /// public static class NumberToEnergyExtensions { - /// + /// public static Energy BritishThermalUnits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromBritishThermalUnits(double.CreateChecked(value)); + => Energy.FromBritishThermalUnits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromBritishThermalUnits(value.ToDouble(null)); + => Energy.FromBritishThermalUnits(value.ToQuantityValue()); #endif - /// + /// public static Energy Calories(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromCalories(double.CreateChecked(value)); + => Energy.FromCalories(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromCalories(value.ToDouble(null)); + => Energy.FromCalories(value.ToQuantityValue()); #endif - /// + /// public static Energy DecathermsEc(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromDecathermsEc(double.CreateChecked(value)); + => Energy.FromDecathermsEc(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromDecathermsEc(value.ToDouble(null)); + => Energy.FromDecathermsEc(value.ToQuantityValue()); #endif - /// + /// public static Energy DecathermsImperial(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromDecathermsImperial(double.CreateChecked(value)); + => Energy.FromDecathermsImperial(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromDecathermsImperial(value.ToDouble(null)); + => Energy.FromDecathermsImperial(value.ToQuantityValue()); #endif - /// + /// public static Energy DecathermsUs(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromDecathermsUs(double.CreateChecked(value)); + => Energy.FromDecathermsUs(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromDecathermsUs(value.ToDouble(null)); + => Energy.FromDecathermsUs(value.ToQuantityValue()); #endif - /// + /// public static Energy ElectronVolts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromElectronVolts(double.CreateChecked(value)); + => Energy.FromElectronVolts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromElectronVolts(value.ToDouble(null)); + => Energy.FromElectronVolts(value.ToQuantityValue()); #endif - /// + /// public static Energy Ergs(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromErgs(double.CreateChecked(value)); + => Energy.FromErgs(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromErgs(value.ToDouble(null)); + => Energy.FromErgs(value.ToQuantityValue()); #endif - /// + /// public static Energy FootPounds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromFootPounds(double.CreateChecked(value)); + => Energy.FromFootPounds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromFootPounds(value.ToDouble(null)); + => Energy.FromFootPounds(value.ToQuantityValue()); #endif - /// + /// public static Energy GigabritishThermalUnits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromGigabritishThermalUnits(double.CreateChecked(value)); + => Energy.FromGigabritishThermalUnits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromGigabritishThermalUnits(value.ToDouble(null)); + => Energy.FromGigabritishThermalUnits(value.ToQuantityValue()); #endif - /// + /// public static Energy GigaelectronVolts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromGigaelectronVolts(double.CreateChecked(value)); + => Energy.FromGigaelectronVolts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromGigaelectronVolts(value.ToDouble(null)); + => Energy.FromGigaelectronVolts(value.ToQuantityValue()); #endif - /// + /// public static Energy Gigajoules(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromGigajoules(double.CreateChecked(value)); + => Energy.FromGigajoules(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromGigajoules(value.ToDouble(null)); + => Energy.FromGigajoules(value.ToQuantityValue()); #endif - /// + /// public static Energy GigawattDays(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromGigawattDays(double.CreateChecked(value)); + => Energy.FromGigawattDays(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromGigawattDays(value.ToDouble(null)); + => Energy.FromGigawattDays(value.ToQuantityValue()); #endif - /// + /// public static Energy GigawattHours(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromGigawattHours(double.CreateChecked(value)); + => Energy.FromGigawattHours(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromGigawattHours(value.ToDouble(null)); + => Energy.FromGigawattHours(value.ToQuantityValue()); #endif - /// + /// public static Energy HorsepowerHours(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromHorsepowerHours(double.CreateChecked(value)); + => Energy.FromHorsepowerHours(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromHorsepowerHours(value.ToDouble(null)); + => Energy.FromHorsepowerHours(value.ToQuantityValue()); #endif - /// + /// public static Energy Joules(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromJoules(double.CreateChecked(value)); + => Energy.FromJoules(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromJoules(value.ToDouble(null)); + => Energy.FromJoules(value.ToQuantityValue()); #endif - /// + /// public static Energy KilobritishThermalUnits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromKilobritishThermalUnits(double.CreateChecked(value)); + => Energy.FromKilobritishThermalUnits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromKilobritishThermalUnits(value.ToDouble(null)); + => Energy.FromKilobritishThermalUnits(value.ToQuantityValue()); #endif - /// + /// public static Energy Kilocalories(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromKilocalories(double.CreateChecked(value)); + => Energy.FromKilocalories(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromKilocalories(value.ToDouble(null)); + => Energy.FromKilocalories(value.ToQuantityValue()); #endif - /// + /// public static Energy KiloelectronVolts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromKiloelectronVolts(double.CreateChecked(value)); + => Energy.FromKiloelectronVolts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromKiloelectronVolts(value.ToDouble(null)); + => Energy.FromKiloelectronVolts(value.ToQuantityValue()); #endif - /// + /// public static Energy Kilojoules(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromKilojoules(double.CreateChecked(value)); + => Energy.FromKilojoules(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromKilojoules(value.ToDouble(null)); + => Energy.FromKilojoules(value.ToQuantityValue()); #endif - /// + /// public static Energy KilowattDays(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromKilowattDays(double.CreateChecked(value)); + => Energy.FromKilowattDays(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromKilowattDays(value.ToDouble(null)); + => Energy.FromKilowattDays(value.ToQuantityValue()); #endif - /// + /// public static Energy KilowattHours(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromKilowattHours(double.CreateChecked(value)); + => Energy.FromKilowattHours(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromKilowattHours(value.ToDouble(null)); + => Energy.FromKilowattHours(value.ToQuantityValue()); #endif - /// + /// public static Energy MegabritishThermalUnits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromMegabritishThermalUnits(double.CreateChecked(value)); + => Energy.FromMegabritishThermalUnits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromMegabritishThermalUnits(value.ToDouble(null)); + => Energy.FromMegabritishThermalUnits(value.ToQuantityValue()); #endif - /// + /// public static Energy Megacalories(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromMegacalories(double.CreateChecked(value)); + => Energy.FromMegacalories(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromMegacalories(value.ToDouble(null)); + => Energy.FromMegacalories(value.ToQuantityValue()); #endif - /// + /// public static Energy MegaelectronVolts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromMegaelectronVolts(double.CreateChecked(value)); + => Energy.FromMegaelectronVolts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromMegaelectronVolts(value.ToDouble(null)); + => Energy.FromMegaelectronVolts(value.ToQuantityValue()); #endif - /// + /// public static Energy Megajoules(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromMegajoules(double.CreateChecked(value)); + => Energy.FromMegajoules(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromMegajoules(value.ToDouble(null)); + => Energy.FromMegajoules(value.ToQuantityValue()); #endif - /// + /// public static Energy MegawattDays(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromMegawattDays(double.CreateChecked(value)); + => Energy.FromMegawattDays(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromMegawattDays(value.ToDouble(null)); + => Energy.FromMegawattDays(value.ToQuantityValue()); #endif - /// + /// public static Energy MegawattHours(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromMegawattHours(double.CreateChecked(value)); + => Energy.FromMegawattHours(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromMegawattHours(value.ToDouble(null)); + => Energy.FromMegawattHours(value.ToQuantityValue()); #endif - /// + /// public static Energy Microjoules(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromMicrojoules(double.CreateChecked(value)); + => Energy.FromMicrojoules(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromMicrojoules(value.ToDouble(null)); + => Energy.FromMicrojoules(value.ToQuantityValue()); #endif - /// + /// public static Energy Millijoules(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromMillijoules(double.CreateChecked(value)); + => Energy.FromMillijoules(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromMillijoules(value.ToDouble(null)); + => Energy.FromMillijoules(value.ToQuantityValue()); #endif - /// + /// public static Energy Nanojoules(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromNanojoules(double.CreateChecked(value)); + => Energy.FromNanojoules(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromNanojoules(value.ToDouble(null)); + => Energy.FromNanojoules(value.ToQuantityValue()); #endif - /// + /// public static Energy Petajoules(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromPetajoules(double.CreateChecked(value)); + => Energy.FromPetajoules(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromPetajoules(value.ToDouble(null)); + => Energy.FromPetajoules(value.ToQuantityValue()); #endif - /// + /// public static Energy TeraelectronVolts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromTeraelectronVolts(double.CreateChecked(value)); + => Energy.FromTeraelectronVolts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromTeraelectronVolts(value.ToDouble(null)); + => Energy.FromTeraelectronVolts(value.ToQuantityValue()); #endif - /// + /// public static Energy Terajoules(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromTerajoules(double.CreateChecked(value)); + => Energy.FromTerajoules(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromTerajoules(value.ToDouble(null)); + => Energy.FromTerajoules(value.ToQuantityValue()); #endif - /// + /// public static Energy TerawattDays(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromTerawattDays(double.CreateChecked(value)); + => Energy.FromTerawattDays(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromTerawattDays(value.ToDouble(null)); + => Energy.FromTerawattDays(value.ToQuantityValue()); #endif - /// + /// public static Energy TerawattHours(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromTerawattHours(double.CreateChecked(value)); + => Energy.FromTerawattHours(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromTerawattHours(value.ToDouble(null)); + => Energy.FromTerawattHours(value.ToQuantityValue()); #endif - /// + /// public static Energy ThermsEc(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromThermsEc(double.CreateChecked(value)); + => Energy.FromThermsEc(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromThermsEc(value.ToDouble(null)); + => Energy.FromThermsEc(value.ToQuantityValue()); #endif - /// + /// public static Energy ThermsImperial(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromThermsImperial(double.CreateChecked(value)); + => Energy.FromThermsImperial(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromThermsImperial(value.ToDouble(null)); + => Energy.FromThermsImperial(value.ToQuantityValue()); #endif - /// + /// public static Energy ThermsUs(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromThermsUs(double.CreateChecked(value)); + => Energy.FromThermsUs(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromThermsUs(value.ToDouble(null)); + => Energy.FromThermsUs(value.ToQuantityValue()); #endif - /// + /// public static Energy WattDays(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromWattDays(double.CreateChecked(value)); + => Energy.FromWattDays(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromWattDays(value.ToDouble(null)); + => Energy.FromWattDays(value.ToQuantityValue()); #endif - /// + /// public static Energy WattHours(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Energy.FromWattHours(double.CreateChecked(value)); + => Energy.FromWattHours(QuantityValue.CreateChecked(value)); #else , IConvertible - => Energy.FromWattHours(value.ToDouble(null)); + => Energy.FromWattHours(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToEntropyExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToEntropyExtensions.g.cs index 7eb721f455..175c6c6c00 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToEntropyExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToEntropyExtensions.g.cs @@ -32,81 +32,81 @@ namespace UnitsNet.NumberExtensions.NumberToEntropy /// public static class NumberToEntropyExtensions { - /// + /// public static Entropy CaloriesPerKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Entropy.FromCaloriesPerKelvin(double.CreateChecked(value)); + => Entropy.FromCaloriesPerKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => Entropy.FromCaloriesPerKelvin(value.ToDouble(null)); + => Entropy.FromCaloriesPerKelvin(value.ToQuantityValue()); #endif - /// + /// public static Entropy JoulesPerDegreeCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Entropy.FromJoulesPerDegreeCelsius(double.CreateChecked(value)); + => Entropy.FromJoulesPerDegreeCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => Entropy.FromJoulesPerDegreeCelsius(value.ToDouble(null)); + => Entropy.FromJoulesPerDegreeCelsius(value.ToQuantityValue()); #endif - /// + /// public static Entropy JoulesPerKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Entropy.FromJoulesPerKelvin(double.CreateChecked(value)); + => Entropy.FromJoulesPerKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => Entropy.FromJoulesPerKelvin(value.ToDouble(null)); + => Entropy.FromJoulesPerKelvin(value.ToQuantityValue()); #endif - /// + /// public static Entropy KilocaloriesPerKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Entropy.FromKilocaloriesPerKelvin(double.CreateChecked(value)); + => Entropy.FromKilocaloriesPerKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => Entropy.FromKilocaloriesPerKelvin(value.ToDouble(null)); + => Entropy.FromKilocaloriesPerKelvin(value.ToQuantityValue()); #endif - /// + /// public static Entropy KilojoulesPerDegreeCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Entropy.FromKilojoulesPerDegreeCelsius(double.CreateChecked(value)); + => Entropy.FromKilojoulesPerDegreeCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => Entropy.FromKilojoulesPerDegreeCelsius(value.ToDouble(null)); + => Entropy.FromKilojoulesPerDegreeCelsius(value.ToQuantityValue()); #endif - /// + /// public static Entropy KilojoulesPerKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Entropy.FromKilojoulesPerKelvin(double.CreateChecked(value)); + => Entropy.FromKilojoulesPerKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => Entropy.FromKilojoulesPerKelvin(value.ToDouble(null)); + => Entropy.FromKilojoulesPerKelvin(value.ToQuantityValue()); #endif - /// + /// public static Entropy MegajoulesPerKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Entropy.FromMegajoulesPerKelvin(double.CreateChecked(value)); + => Entropy.FromMegajoulesPerKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => Entropy.FromMegajoulesPerKelvin(value.ToDouble(null)); + => Entropy.FromMegajoulesPerKelvin(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToFluidResistanceExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToFluidResistanceExtensions.g.cs index 3e8fc2ad46..22c74d7bf4 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToFluidResistanceExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToFluidResistanceExtensions.g.cs @@ -32,213 +32,213 @@ namespace UnitsNet.NumberExtensions.NumberToFluidResistance /// public static class NumberToFluidResistanceExtensions { - /// + /// public static FluidResistance DyneSecondsPerCentimeterToTheFifth(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromDyneSecondsPerCentimeterToTheFifth(double.CreateChecked(value)); + => FluidResistance.FromDyneSecondsPerCentimeterToTheFifth(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromDyneSecondsPerCentimeterToTheFifth(value.ToDouble(null)); + => FluidResistance.FromDyneSecondsPerCentimeterToTheFifth(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance MegapascalSecondsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromMegapascalSecondsPerCubicMeter(double.CreateChecked(value)); + => FluidResistance.FromMegapascalSecondsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromMegapascalSecondsPerCubicMeter(value.ToDouble(null)); + => FluidResistance.FromMegapascalSecondsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance MillimeterMercuryMinutesPerCubicCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromMillimeterMercuryMinutesPerCubicCentimeter(double.CreateChecked(value)); + => FluidResistance.FromMillimeterMercuryMinutesPerCubicCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromMillimeterMercuryMinutesPerCubicCentimeter(value.ToDouble(null)); + => FluidResistance.FromMillimeterMercuryMinutesPerCubicCentimeter(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance MillimeterMercuryMinutesPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromMillimeterMercuryMinutesPerCubicMeter(double.CreateChecked(value)); + => FluidResistance.FromMillimeterMercuryMinutesPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromMillimeterMercuryMinutesPerCubicMeter(value.ToDouble(null)); + => FluidResistance.FromMillimeterMercuryMinutesPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance MillimeterMercuryMinutesPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromMillimeterMercuryMinutesPerLiter(double.CreateChecked(value)); + => FluidResistance.FromMillimeterMercuryMinutesPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromMillimeterMercuryMinutesPerLiter(value.ToDouble(null)); + => FluidResistance.FromMillimeterMercuryMinutesPerLiter(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance MillimeterMercuryMinutesPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromMillimeterMercuryMinutesPerMilliliter(double.CreateChecked(value)); + => FluidResistance.FromMillimeterMercuryMinutesPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromMillimeterMercuryMinutesPerMilliliter(value.ToDouble(null)); + => FluidResistance.FromMillimeterMercuryMinutesPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance MillimeterMercurySecondsPerCubicCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromMillimeterMercurySecondsPerCubicCentimeter(double.CreateChecked(value)); + => FluidResistance.FromMillimeterMercurySecondsPerCubicCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromMillimeterMercurySecondsPerCubicCentimeter(value.ToDouble(null)); + => FluidResistance.FromMillimeterMercurySecondsPerCubicCentimeter(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance MillimeterMercurySecondsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromMillimeterMercurySecondsPerCubicMeter(double.CreateChecked(value)); + => FluidResistance.FromMillimeterMercurySecondsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromMillimeterMercurySecondsPerCubicMeter(value.ToDouble(null)); + => FluidResistance.FromMillimeterMercurySecondsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance MillimeterMercurySecondsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromMillimeterMercurySecondsPerLiter(double.CreateChecked(value)); + => FluidResistance.FromMillimeterMercurySecondsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromMillimeterMercurySecondsPerLiter(value.ToDouble(null)); + => FluidResistance.FromMillimeterMercurySecondsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance MillimeterMercurySecondsPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromMillimeterMercurySecondsPerMilliliter(double.CreateChecked(value)); + => FluidResistance.FromMillimeterMercurySecondsPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromMillimeterMercurySecondsPerMilliliter(value.ToDouble(null)); + => FluidResistance.FromMillimeterMercurySecondsPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance PascalMinutesPerCubicCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromPascalMinutesPerCubicCentimeter(double.CreateChecked(value)); + => FluidResistance.FromPascalMinutesPerCubicCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromPascalMinutesPerCubicCentimeter(value.ToDouble(null)); + => FluidResistance.FromPascalMinutesPerCubicCentimeter(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance PascalMinutesPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromPascalMinutesPerCubicMeter(double.CreateChecked(value)); + => FluidResistance.FromPascalMinutesPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromPascalMinutesPerCubicMeter(value.ToDouble(null)); + => FluidResistance.FromPascalMinutesPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance PascalMinutesPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromPascalMinutesPerLiter(double.CreateChecked(value)); + => FluidResistance.FromPascalMinutesPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromPascalMinutesPerLiter(value.ToDouble(null)); + => FluidResistance.FromPascalMinutesPerLiter(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance PascalMinutesPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromPascalMinutesPerMilliliter(double.CreateChecked(value)); + => FluidResistance.FromPascalMinutesPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromPascalMinutesPerMilliliter(value.ToDouble(null)); + => FluidResistance.FromPascalMinutesPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance PascalSecondsPerCubicCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromPascalSecondsPerCubicCentimeter(double.CreateChecked(value)); + => FluidResistance.FromPascalSecondsPerCubicCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromPascalSecondsPerCubicCentimeter(value.ToDouble(null)); + => FluidResistance.FromPascalSecondsPerCubicCentimeter(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance PascalSecondsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromPascalSecondsPerCubicMeter(double.CreateChecked(value)); + => FluidResistance.FromPascalSecondsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromPascalSecondsPerCubicMeter(value.ToDouble(null)); + => FluidResistance.FromPascalSecondsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance PascalSecondsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromPascalSecondsPerLiter(double.CreateChecked(value)); + => FluidResistance.FromPascalSecondsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromPascalSecondsPerLiter(value.ToDouble(null)); + => FluidResistance.FromPascalSecondsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance PascalSecondsPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromPascalSecondsPerMilliliter(double.CreateChecked(value)); + => FluidResistance.FromPascalSecondsPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromPascalSecondsPerMilliliter(value.ToDouble(null)); + => FluidResistance.FromPascalSecondsPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static FluidResistance WoodUnits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FluidResistance.FromWoodUnits(double.CreateChecked(value)); + => FluidResistance.FromWoodUnits(QuantityValue.CreateChecked(value)); #else , IConvertible - => FluidResistance.FromWoodUnits(value.ToDouble(null)); + => FluidResistance.FromWoodUnits(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToForceChangeRateExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToForceChangeRateExtensions.g.cs index 667a6aa8eb..f1baf49edf 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToForceChangeRateExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToForceChangeRateExtensions.g.cs @@ -32,169 +32,169 @@ namespace UnitsNet.NumberExtensions.NumberToForceChangeRate /// public static class NumberToForceChangeRateExtensions { - /// + /// public static ForceChangeRate CentinewtonsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForceChangeRate.FromCentinewtonsPerSecond(double.CreateChecked(value)); + => ForceChangeRate.FromCentinewtonsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForceChangeRate.FromCentinewtonsPerSecond(value.ToDouble(null)); + => ForceChangeRate.FromCentinewtonsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static ForceChangeRate DecanewtonsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForceChangeRate.FromDecanewtonsPerMinute(double.CreateChecked(value)); + => ForceChangeRate.FromDecanewtonsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForceChangeRate.FromDecanewtonsPerMinute(value.ToDouble(null)); + => ForceChangeRate.FromDecanewtonsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static ForceChangeRate DecanewtonsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForceChangeRate.FromDecanewtonsPerSecond(double.CreateChecked(value)); + => ForceChangeRate.FromDecanewtonsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForceChangeRate.FromDecanewtonsPerSecond(value.ToDouble(null)); + => ForceChangeRate.FromDecanewtonsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static ForceChangeRate DecinewtonsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForceChangeRate.FromDecinewtonsPerSecond(double.CreateChecked(value)); + => ForceChangeRate.FromDecinewtonsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForceChangeRate.FromDecinewtonsPerSecond(value.ToDouble(null)); + => ForceChangeRate.FromDecinewtonsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static ForceChangeRate KilonewtonsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForceChangeRate.FromKilonewtonsPerMinute(double.CreateChecked(value)); + => ForceChangeRate.FromKilonewtonsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForceChangeRate.FromKilonewtonsPerMinute(value.ToDouble(null)); + => ForceChangeRate.FromKilonewtonsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static ForceChangeRate KilonewtonsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForceChangeRate.FromKilonewtonsPerSecond(double.CreateChecked(value)); + => ForceChangeRate.FromKilonewtonsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForceChangeRate.FromKilonewtonsPerSecond(value.ToDouble(null)); + => ForceChangeRate.FromKilonewtonsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static ForceChangeRate KilopoundsForcePerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForceChangeRate.FromKilopoundsForcePerMinute(double.CreateChecked(value)); + => ForceChangeRate.FromKilopoundsForcePerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForceChangeRate.FromKilopoundsForcePerMinute(value.ToDouble(null)); + => ForceChangeRate.FromKilopoundsForcePerMinute(value.ToQuantityValue()); #endif - /// + /// public static ForceChangeRate KilopoundsForcePerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForceChangeRate.FromKilopoundsForcePerSecond(double.CreateChecked(value)); + => ForceChangeRate.FromKilopoundsForcePerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForceChangeRate.FromKilopoundsForcePerSecond(value.ToDouble(null)); + => ForceChangeRate.FromKilopoundsForcePerSecond(value.ToQuantityValue()); #endif - /// + /// public static ForceChangeRate MicronewtonsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForceChangeRate.FromMicronewtonsPerSecond(double.CreateChecked(value)); + => ForceChangeRate.FromMicronewtonsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForceChangeRate.FromMicronewtonsPerSecond(value.ToDouble(null)); + => ForceChangeRate.FromMicronewtonsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static ForceChangeRate MillinewtonsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForceChangeRate.FromMillinewtonsPerSecond(double.CreateChecked(value)); + => ForceChangeRate.FromMillinewtonsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForceChangeRate.FromMillinewtonsPerSecond(value.ToDouble(null)); + => ForceChangeRate.FromMillinewtonsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static ForceChangeRate NanonewtonsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForceChangeRate.FromNanonewtonsPerSecond(double.CreateChecked(value)); + => ForceChangeRate.FromNanonewtonsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForceChangeRate.FromNanonewtonsPerSecond(value.ToDouble(null)); + => ForceChangeRate.FromNanonewtonsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static ForceChangeRate NewtonsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForceChangeRate.FromNewtonsPerMinute(double.CreateChecked(value)); + => ForceChangeRate.FromNewtonsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForceChangeRate.FromNewtonsPerMinute(value.ToDouble(null)); + => ForceChangeRate.FromNewtonsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static ForceChangeRate NewtonsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForceChangeRate.FromNewtonsPerSecond(double.CreateChecked(value)); + => ForceChangeRate.FromNewtonsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForceChangeRate.FromNewtonsPerSecond(value.ToDouble(null)); + => ForceChangeRate.FromNewtonsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static ForceChangeRate PoundsForcePerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForceChangeRate.FromPoundsForcePerMinute(double.CreateChecked(value)); + => ForceChangeRate.FromPoundsForcePerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForceChangeRate.FromPoundsForcePerMinute(value.ToDouble(null)); + => ForceChangeRate.FromPoundsForcePerMinute(value.ToQuantityValue()); #endif - /// + /// public static ForceChangeRate PoundsForcePerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForceChangeRate.FromPoundsForcePerSecond(double.CreateChecked(value)); + => ForceChangeRate.FromPoundsForcePerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForceChangeRate.FromPoundsForcePerSecond(value.ToDouble(null)); + => ForceChangeRate.FromPoundsForcePerSecond(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToForceExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToForceExtensions.g.cs index 6b5a9cd2ae..0bdb9d947d 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToForceExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToForceExtensions.g.cs @@ -32,169 +32,169 @@ namespace UnitsNet.NumberExtensions.NumberToForce /// public static class NumberToForceExtensions { - /// + /// public static Force Decanewtons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Force.FromDecanewtons(double.CreateChecked(value)); + => Force.FromDecanewtons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Force.FromDecanewtons(value.ToDouble(null)); + => Force.FromDecanewtons(value.ToQuantityValue()); #endif - /// + /// public static Force Dyne(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Force.FromDyne(double.CreateChecked(value)); + => Force.FromDyne(QuantityValue.CreateChecked(value)); #else , IConvertible - => Force.FromDyne(value.ToDouble(null)); + => Force.FromDyne(value.ToQuantityValue()); #endif - /// + /// public static Force KilogramsForce(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Force.FromKilogramsForce(double.CreateChecked(value)); + => Force.FromKilogramsForce(QuantityValue.CreateChecked(value)); #else , IConvertible - => Force.FromKilogramsForce(value.ToDouble(null)); + => Force.FromKilogramsForce(value.ToQuantityValue()); #endif - /// + /// public static Force Kilonewtons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Force.FromKilonewtons(double.CreateChecked(value)); + => Force.FromKilonewtons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Force.FromKilonewtons(value.ToDouble(null)); + => Force.FromKilonewtons(value.ToQuantityValue()); #endif - /// + /// public static Force KiloPonds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Force.FromKiloPonds(double.CreateChecked(value)); + => Force.FromKiloPonds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Force.FromKiloPonds(value.ToDouble(null)); + => Force.FromKiloPonds(value.ToQuantityValue()); #endif - /// + /// public static Force KilopoundsForce(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Force.FromKilopoundsForce(double.CreateChecked(value)); + => Force.FromKilopoundsForce(QuantityValue.CreateChecked(value)); #else , IConvertible - => Force.FromKilopoundsForce(value.ToDouble(null)); + => Force.FromKilopoundsForce(value.ToQuantityValue()); #endif - /// + /// public static Force Meganewtons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Force.FromMeganewtons(double.CreateChecked(value)); + => Force.FromMeganewtons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Force.FromMeganewtons(value.ToDouble(null)); + => Force.FromMeganewtons(value.ToQuantityValue()); #endif - /// + /// public static Force Micronewtons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Force.FromMicronewtons(double.CreateChecked(value)); + => Force.FromMicronewtons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Force.FromMicronewtons(value.ToDouble(null)); + => Force.FromMicronewtons(value.ToQuantityValue()); #endif - /// + /// public static Force Millinewtons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Force.FromMillinewtons(double.CreateChecked(value)); + => Force.FromMillinewtons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Force.FromMillinewtons(value.ToDouble(null)); + => Force.FromMillinewtons(value.ToQuantityValue()); #endif - /// + /// public static Force Newtons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Force.FromNewtons(double.CreateChecked(value)); + => Force.FromNewtons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Force.FromNewtons(value.ToDouble(null)); + => Force.FromNewtons(value.ToQuantityValue()); #endif - /// + /// public static Force OunceForce(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Force.FromOunceForce(double.CreateChecked(value)); + => Force.FromOunceForce(QuantityValue.CreateChecked(value)); #else , IConvertible - => Force.FromOunceForce(value.ToDouble(null)); + => Force.FromOunceForce(value.ToQuantityValue()); #endif - /// + /// public static Force Poundals(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Force.FromPoundals(double.CreateChecked(value)); + => Force.FromPoundals(QuantityValue.CreateChecked(value)); #else , IConvertible - => Force.FromPoundals(value.ToDouble(null)); + => Force.FromPoundals(value.ToQuantityValue()); #endif - /// + /// public static Force PoundsForce(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Force.FromPoundsForce(double.CreateChecked(value)); + => Force.FromPoundsForce(QuantityValue.CreateChecked(value)); #else , IConvertible - => Force.FromPoundsForce(value.ToDouble(null)); + => Force.FromPoundsForce(value.ToQuantityValue()); #endif - /// + /// public static Force ShortTonsForce(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Force.FromShortTonsForce(double.CreateChecked(value)); + => Force.FromShortTonsForce(QuantityValue.CreateChecked(value)); #else , IConvertible - => Force.FromShortTonsForce(value.ToDouble(null)); + => Force.FromShortTonsForce(value.ToQuantityValue()); #endif - /// + /// public static Force TonnesForce(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Force.FromTonnesForce(double.CreateChecked(value)); + => Force.FromTonnesForce(QuantityValue.CreateChecked(value)); #else , IConvertible - => Force.FromTonnesForce(value.ToDouble(null)); + => Force.FromTonnesForce(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToForcePerLengthExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToForcePerLengthExtensions.g.cs index 001e77662f..9dcd094580 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToForcePerLengthExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToForcePerLengthExtensions.g.cs @@ -32,422 +32,422 @@ namespace UnitsNet.NumberExtensions.NumberToForcePerLength /// public static class NumberToForcePerLengthExtensions { - /// + /// public static ForcePerLength CentinewtonsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromCentinewtonsPerCentimeter(double.CreateChecked(value)); + => ForcePerLength.FromCentinewtonsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromCentinewtonsPerCentimeter(value.ToDouble(null)); + => ForcePerLength.FromCentinewtonsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength CentinewtonsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromCentinewtonsPerMeter(double.CreateChecked(value)); + => ForcePerLength.FromCentinewtonsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromCentinewtonsPerMeter(value.ToDouble(null)); + => ForcePerLength.FromCentinewtonsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength CentinewtonsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromCentinewtonsPerMillimeter(double.CreateChecked(value)); + => ForcePerLength.FromCentinewtonsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromCentinewtonsPerMillimeter(value.ToDouble(null)); + => ForcePerLength.FromCentinewtonsPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength DecanewtonsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromDecanewtonsPerCentimeter(double.CreateChecked(value)); + => ForcePerLength.FromDecanewtonsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromDecanewtonsPerCentimeter(value.ToDouble(null)); + => ForcePerLength.FromDecanewtonsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength DecanewtonsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromDecanewtonsPerMeter(double.CreateChecked(value)); + => ForcePerLength.FromDecanewtonsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromDecanewtonsPerMeter(value.ToDouble(null)); + => ForcePerLength.FromDecanewtonsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength DecanewtonsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromDecanewtonsPerMillimeter(double.CreateChecked(value)); + => ForcePerLength.FromDecanewtonsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromDecanewtonsPerMillimeter(value.ToDouble(null)); + => ForcePerLength.FromDecanewtonsPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength DecinewtonsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromDecinewtonsPerCentimeter(double.CreateChecked(value)); + => ForcePerLength.FromDecinewtonsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromDecinewtonsPerCentimeter(value.ToDouble(null)); + => ForcePerLength.FromDecinewtonsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength DecinewtonsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromDecinewtonsPerMeter(double.CreateChecked(value)); + => ForcePerLength.FromDecinewtonsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromDecinewtonsPerMeter(value.ToDouble(null)); + => ForcePerLength.FromDecinewtonsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength DecinewtonsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromDecinewtonsPerMillimeter(double.CreateChecked(value)); + => ForcePerLength.FromDecinewtonsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromDecinewtonsPerMillimeter(value.ToDouble(null)); + => ForcePerLength.FromDecinewtonsPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength KilogramsForcePerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromKilogramsForcePerCentimeter(double.CreateChecked(value)); + => ForcePerLength.FromKilogramsForcePerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromKilogramsForcePerCentimeter(value.ToDouble(null)); + => ForcePerLength.FromKilogramsForcePerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength KilogramsForcePerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromKilogramsForcePerMeter(double.CreateChecked(value)); + => ForcePerLength.FromKilogramsForcePerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromKilogramsForcePerMeter(value.ToDouble(null)); + => ForcePerLength.FromKilogramsForcePerMeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength KilogramsForcePerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromKilogramsForcePerMillimeter(double.CreateChecked(value)); + => ForcePerLength.FromKilogramsForcePerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromKilogramsForcePerMillimeter(value.ToDouble(null)); + => ForcePerLength.FromKilogramsForcePerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength KilonewtonsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromKilonewtonsPerCentimeter(double.CreateChecked(value)); + => ForcePerLength.FromKilonewtonsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromKilonewtonsPerCentimeter(value.ToDouble(null)); + => ForcePerLength.FromKilonewtonsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength KilonewtonsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromKilonewtonsPerMeter(double.CreateChecked(value)); + => ForcePerLength.FromKilonewtonsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromKilonewtonsPerMeter(value.ToDouble(null)); + => ForcePerLength.FromKilonewtonsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength KilonewtonsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromKilonewtonsPerMillimeter(double.CreateChecked(value)); + => ForcePerLength.FromKilonewtonsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromKilonewtonsPerMillimeter(value.ToDouble(null)); + => ForcePerLength.FromKilonewtonsPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength KilopoundsForcePerFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromKilopoundsForcePerFoot(double.CreateChecked(value)); + => ForcePerLength.FromKilopoundsForcePerFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromKilopoundsForcePerFoot(value.ToDouble(null)); + => ForcePerLength.FromKilopoundsForcePerFoot(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength KilopoundsForcePerInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromKilopoundsForcePerInch(double.CreateChecked(value)); + => ForcePerLength.FromKilopoundsForcePerInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromKilopoundsForcePerInch(value.ToDouble(null)); + => ForcePerLength.FromKilopoundsForcePerInch(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength MeganewtonsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromMeganewtonsPerCentimeter(double.CreateChecked(value)); + => ForcePerLength.FromMeganewtonsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromMeganewtonsPerCentimeter(value.ToDouble(null)); + => ForcePerLength.FromMeganewtonsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength MeganewtonsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromMeganewtonsPerMeter(double.CreateChecked(value)); + => ForcePerLength.FromMeganewtonsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromMeganewtonsPerMeter(value.ToDouble(null)); + => ForcePerLength.FromMeganewtonsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength MeganewtonsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromMeganewtonsPerMillimeter(double.CreateChecked(value)); + => ForcePerLength.FromMeganewtonsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromMeganewtonsPerMillimeter(value.ToDouble(null)); + => ForcePerLength.FromMeganewtonsPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength MicronewtonsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromMicronewtonsPerCentimeter(double.CreateChecked(value)); + => ForcePerLength.FromMicronewtonsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromMicronewtonsPerCentimeter(value.ToDouble(null)); + => ForcePerLength.FromMicronewtonsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength MicronewtonsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromMicronewtonsPerMeter(double.CreateChecked(value)); + => ForcePerLength.FromMicronewtonsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromMicronewtonsPerMeter(value.ToDouble(null)); + => ForcePerLength.FromMicronewtonsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength MicronewtonsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromMicronewtonsPerMillimeter(double.CreateChecked(value)); + => ForcePerLength.FromMicronewtonsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromMicronewtonsPerMillimeter(value.ToDouble(null)); + => ForcePerLength.FromMicronewtonsPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength MillinewtonsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromMillinewtonsPerCentimeter(double.CreateChecked(value)); + => ForcePerLength.FromMillinewtonsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromMillinewtonsPerCentimeter(value.ToDouble(null)); + => ForcePerLength.FromMillinewtonsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength MillinewtonsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromMillinewtonsPerMeter(double.CreateChecked(value)); + => ForcePerLength.FromMillinewtonsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromMillinewtonsPerMeter(value.ToDouble(null)); + => ForcePerLength.FromMillinewtonsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength MillinewtonsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromMillinewtonsPerMillimeter(double.CreateChecked(value)); + => ForcePerLength.FromMillinewtonsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromMillinewtonsPerMillimeter(value.ToDouble(null)); + => ForcePerLength.FromMillinewtonsPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength NanonewtonsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromNanonewtonsPerCentimeter(double.CreateChecked(value)); + => ForcePerLength.FromNanonewtonsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromNanonewtonsPerCentimeter(value.ToDouble(null)); + => ForcePerLength.FromNanonewtonsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength NanonewtonsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromNanonewtonsPerMeter(double.CreateChecked(value)); + => ForcePerLength.FromNanonewtonsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromNanonewtonsPerMeter(value.ToDouble(null)); + => ForcePerLength.FromNanonewtonsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength NanonewtonsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromNanonewtonsPerMillimeter(double.CreateChecked(value)); + => ForcePerLength.FromNanonewtonsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromNanonewtonsPerMillimeter(value.ToDouble(null)); + => ForcePerLength.FromNanonewtonsPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength NewtonsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromNewtonsPerCentimeter(double.CreateChecked(value)); + => ForcePerLength.FromNewtonsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromNewtonsPerCentimeter(value.ToDouble(null)); + => ForcePerLength.FromNewtonsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength NewtonsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromNewtonsPerMeter(double.CreateChecked(value)); + => ForcePerLength.FromNewtonsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromNewtonsPerMeter(value.ToDouble(null)); + => ForcePerLength.FromNewtonsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength NewtonsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromNewtonsPerMillimeter(double.CreateChecked(value)); + => ForcePerLength.FromNewtonsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromNewtonsPerMillimeter(value.ToDouble(null)); + => ForcePerLength.FromNewtonsPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength PoundsForcePerFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromPoundsForcePerFoot(double.CreateChecked(value)); + => ForcePerLength.FromPoundsForcePerFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromPoundsForcePerFoot(value.ToDouble(null)); + => ForcePerLength.FromPoundsForcePerFoot(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength PoundsForcePerInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromPoundsForcePerInch(double.CreateChecked(value)); + => ForcePerLength.FromPoundsForcePerInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromPoundsForcePerInch(value.ToDouble(null)); + => ForcePerLength.FromPoundsForcePerInch(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength PoundsForcePerYard(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromPoundsForcePerYard(double.CreateChecked(value)); + => ForcePerLength.FromPoundsForcePerYard(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromPoundsForcePerYard(value.ToDouble(null)); + => ForcePerLength.FromPoundsForcePerYard(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength TonnesForcePerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromTonnesForcePerCentimeter(double.CreateChecked(value)); + => ForcePerLength.FromTonnesForcePerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromTonnesForcePerCentimeter(value.ToDouble(null)); + => ForcePerLength.FromTonnesForcePerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength TonnesForcePerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromTonnesForcePerMeter(double.CreateChecked(value)); + => ForcePerLength.FromTonnesForcePerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromTonnesForcePerMeter(value.ToDouble(null)); + => ForcePerLength.FromTonnesForcePerMeter(value.ToQuantityValue()); #endif - /// + /// public static ForcePerLength TonnesForcePerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ForcePerLength.FromTonnesForcePerMillimeter(double.CreateChecked(value)); + => ForcePerLength.FromTonnesForcePerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => ForcePerLength.FromTonnesForcePerMillimeter(value.ToDouble(null)); + => ForcePerLength.FromTonnesForcePerMillimeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToFrequencyExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToFrequencyExtensions.g.cs index afc8943c39..b68cf5ad70 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToFrequencyExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToFrequencyExtensions.g.cs @@ -32,136 +32,136 @@ namespace UnitsNet.NumberExtensions.NumberToFrequency /// public static class NumberToFrequencyExtensions { - /// + /// public static Frequency BeatsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Frequency.FromBeatsPerMinute(double.CreateChecked(value)); + => Frequency.FromBeatsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => Frequency.FromBeatsPerMinute(value.ToDouble(null)); + => Frequency.FromBeatsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static Frequency CyclesPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Frequency.FromCyclesPerHour(double.CreateChecked(value)); + => Frequency.FromCyclesPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Frequency.FromCyclesPerHour(value.ToDouble(null)); + => Frequency.FromCyclesPerHour(value.ToQuantityValue()); #endif - /// + /// public static Frequency CyclesPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Frequency.FromCyclesPerMinute(double.CreateChecked(value)); + => Frequency.FromCyclesPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => Frequency.FromCyclesPerMinute(value.ToDouble(null)); + => Frequency.FromCyclesPerMinute(value.ToQuantityValue()); #endif - /// + /// public static Frequency Gigahertz(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Frequency.FromGigahertz(double.CreateChecked(value)); + => Frequency.FromGigahertz(QuantityValue.CreateChecked(value)); #else , IConvertible - => Frequency.FromGigahertz(value.ToDouble(null)); + => Frequency.FromGigahertz(value.ToQuantityValue()); #endif - /// + /// public static Frequency Hertz(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Frequency.FromHertz(double.CreateChecked(value)); + => Frequency.FromHertz(QuantityValue.CreateChecked(value)); #else , IConvertible - => Frequency.FromHertz(value.ToDouble(null)); + => Frequency.FromHertz(value.ToQuantityValue()); #endif - /// + /// public static Frequency Kilohertz(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Frequency.FromKilohertz(double.CreateChecked(value)); + => Frequency.FromKilohertz(QuantityValue.CreateChecked(value)); #else , IConvertible - => Frequency.FromKilohertz(value.ToDouble(null)); + => Frequency.FromKilohertz(value.ToQuantityValue()); #endif - /// + /// public static Frequency Megahertz(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Frequency.FromMegahertz(double.CreateChecked(value)); + => Frequency.FromMegahertz(QuantityValue.CreateChecked(value)); #else , IConvertible - => Frequency.FromMegahertz(value.ToDouble(null)); + => Frequency.FromMegahertz(value.ToQuantityValue()); #endif - /// + /// public static Frequency Microhertz(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Frequency.FromMicrohertz(double.CreateChecked(value)); + => Frequency.FromMicrohertz(QuantityValue.CreateChecked(value)); #else , IConvertible - => Frequency.FromMicrohertz(value.ToDouble(null)); + => Frequency.FromMicrohertz(value.ToQuantityValue()); #endif - /// + /// public static Frequency Millihertz(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Frequency.FromMillihertz(double.CreateChecked(value)); + => Frequency.FromMillihertz(QuantityValue.CreateChecked(value)); #else , IConvertible - => Frequency.FromMillihertz(value.ToDouble(null)); + => Frequency.FromMillihertz(value.ToQuantityValue()); #endif - /// + /// public static Frequency PerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Frequency.FromPerSecond(double.CreateChecked(value)); + => Frequency.FromPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Frequency.FromPerSecond(value.ToDouble(null)); + => Frequency.FromPerSecond(value.ToQuantityValue()); #endif - /// + /// public static Frequency RadiansPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Frequency.FromRadiansPerSecond(double.CreateChecked(value)); + => Frequency.FromRadiansPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Frequency.FromRadiansPerSecond(value.ToDouble(null)); + => Frequency.FromRadiansPerSecond(value.ToQuantityValue()); #endif - /// + /// public static Frequency Terahertz(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Frequency.FromTerahertz(double.CreateChecked(value)); + => Frequency.FromTerahertz(QuantityValue.CreateChecked(value)); #else , IConvertible - => Frequency.FromTerahertz(value.ToDouble(null)); + => Frequency.FromTerahertz(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToFuelEfficiencyExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToFuelEfficiencyExtensions.g.cs index dbe0748f54..5d715f4848 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToFuelEfficiencyExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToFuelEfficiencyExtensions.g.cs @@ -32,48 +32,48 @@ namespace UnitsNet.NumberExtensions.NumberToFuelEfficiency /// public static class NumberToFuelEfficiencyExtensions { - /// + /// public static FuelEfficiency KilometersPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FuelEfficiency.FromKilometersPerLiter(double.CreateChecked(value)); + => FuelEfficiency.FromKilometersPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => FuelEfficiency.FromKilometersPerLiter(value.ToDouble(null)); + => FuelEfficiency.FromKilometersPerLiter(value.ToQuantityValue()); #endif - /// + /// public static FuelEfficiency LitersPer100Kilometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FuelEfficiency.FromLitersPer100Kilometers(double.CreateChecked(value)); + => FuelEfficiency.FromLitersPer100Kilometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => FuelEfficiency.FromLitersPer100Kilometers(value.ToDouble(null)); + => FuelEfficiency.FromLitersPer100Kilometers(value.ToQuantityValue()); #endif - /// + /// public static FuelEfficiency MilesPerUkGallon(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FuelEfficiency.FromMilesPerUkGallon(double.CreateChecked(value)); + => FuelEfficiency.FromMilesPerUkGallon(QuantityValue.CreateChecked(value)); #else , IConvertible - => FuelEfficiency.FromMilesPerUkGallon(value.ToDouble(null)); + => FuelEfficiency.FromMilesPerUkGallon(value.ToQuantityValue()); #endif - /// + /// public static FuelEfficiency MilesPerUsGallon(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => FuelEfficiency.FromMilesPerUsGallon(double.CreateChecked(value)); + => FuelEfficiency.FromMilesPerUsGallon(QuantityValue.CreateChecked(value)); #else , IConvertible - => FuelEfficiency.FromMilesPerUsGallon(value.ToDouble(null)); + => FuelEfficiency.FromMilesPerUsGallon(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToHeatFluxExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToHeatFluxExtensions.g.cs index ac5855e7bf..c14470fb54 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToHeatFluxExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToHeatFluxExtensions.g.cs @@ -32,202 +32,202 @@ namespace UnitsNet.NumberExtensions.NumberToHeatFlux /// public static class NumberToHeatFluxExtensions { - /// + /// public static HeatFlux BtusPerHourSquareFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromBtusPerHourSquareFoot(double.CreateChecked(value)); + => HeatFlux.FromBtusPerHourSquareFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromBtusPerHourSquareFoot(value.ToDouble(null)); + => HeatFlux.FromBtusPerHourSquareFoot(value.ToQuantityValue()); #endif - /// + /// public static HeatFlux BtusPerMinuteSquareFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromBtusPerMinuteSquareFoot(double.CreateChecked(value)); + => HeatFlux.FromBtusPerMinuteSquareFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromBtusPerMinuteSquareFoot(value.ToDouble(null)); + => HeatFlux.FromBtusPerMinuteSquareFoot(value.ToQuantityValue()); #endif - /// + /// public static HeatFlux BtusPerSecondSquareFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromBtusPerSecondSquareFoot(double.CreateChecked(value)); + => HeatFlux.FromBtusPerSecondSquareFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromBtusPerSecondSquareFoot(value.ToDouble(null)); + => HeatFlux.FromBtusPerSecondSquareFoot(value.ToQuantityValue()); #endif - /// + /// public static HeatFlux BtusPerSecondSquareInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromBtusPerSecondSquareInch(double.CreateChecked(value)); + => HeatFlux.FromBtusPerSecondSquareInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromBtusPerSecondSquareInch(value.ToDouble(null)); + => HeatFlux.FromBtusPerSecondSquareInch(value.ToQuantityValue()); #endif - /// + /// public static HeatFlux CaloriesPerSecondSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromCaloriesPerSecondSquareCentimeter(double.CreateChecked(value)); + => HeatFlux.FromCaloriesPerSecondSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromCaloriesPerSecondSquareCentimeter(value.ToDouble(null)); + => HeatFlux.FromCaloriesPerSecondSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static HeatFlux CentiwattsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromCentiwattsPerSquareMeter(double.CreateChecked(value)); + => HeatFlux.FromCentiwattsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromCentiwattsPerSquareMeter(value.ToDouble(null)); + => HeatFlux.FromCentiwattsPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static HeatFlux DeciwattsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromDeciwattsPerSquareMeter(double.CreateChecked(value)); + => HeatFlux.FromDeciwattsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromDeciwattsPerSquareMeter(value.ToDouble(null)); + => HeatFlux.FromDeciwattsPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static HeatFlux KilocaloriesPerHourSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromKilocaloriesPerHourSquareMeter(double.CreateChecked(value)); + => HeatFlux.FromKilocaloriesPerHourSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromKilocaloriesPerHourSquareMeter(value.ToDouble(null)); + => HeatFlux.FromKilocaloriesPerHourSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static HeatFlux KilocaloriesPerSecondSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromKilocaloriesPerSecondSquareCentimeter(double.CreateChecked(value)); + => HeatFlux.FromKilocaloriesPerSecondSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromKilocaloriesPerSecondSquareCentimeter(value.ToDouble(null)); + => HeatFlux.FromKilocaloriesPerSecondSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static HeatFlux KilowattsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromKilowattsPerSquareMeter(double.CreateChecked(value)); + => HeatFlux.FromKilowattsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromKilowattsPerSquareMeter(value.ToDouble(null)); + => HeatFlux.FromKilowattsPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static HeatFlux MicrowattsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromMicrowattsPerSquareMeter(double.CreateChecked(value)); + => HeatFlux.FromMicrowattsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromMicrowattsPerSquareMeter(value.ToDouble(null)); + => HeatFlux.FromMicrowattsPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static HeatFlux MilliwattsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromMilliwattsPerSquareMeter(double.CreateChecked(value)); + => HeatFlux.FromMilliwattsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromMilliwattsPerSquareMeter(value.ToDouble(null)); + => HeatFlux.FromMilliwattsPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static HeatFlux NanowattsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromNanowattsPerSquareMeter(double.CreateChecked(value)); + => HeatFlux.FromNanowattsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromNanowattsPerSquareMeter(value.ToDouble(null)); + => HeatFlux.FromNanowattsPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static HeatFlux PoundsForcePerFootSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromPoundsForcePerFootSecond(double.CreateChecked(value)); + => HeatFlux.FromPoundsForcePerFootSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromPoundsForcePerFootSecond(value.ToDouble(null)); + => HeatFlux.FromPoundsForcePerFootSecond(value.ToQuantityValue()); #endif - /// + /// public static HeatFlux PoundsPerSecondCubed(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromPoundsPerSecondCubed(double.CreateChecked(value)); + => HeatFlux.FromPoundsPerSecondCubed(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromPoundsPerSecondCubed(value.ToDouble(null)); + => HeatFlux.FromPoundsPerSecondCubed(value.ToQuantityValue()); #endif - /// + /// public static HeatFlux WattsPerSquareFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromWattsPerSquareFoot(double.CreateChecked(value)); + => HeatFlux.FromWattsPerSquareFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromWattsPerSquareFoot(value.ToDouble(null)); + => HeatFlux.FromWattsPerSquareFoot(value.ToQuantityValue()); #endif - /// + /// public static HeatFlux WattsPerSquareInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromWattsPerSquareInch(double.CreateChecked(value)); + => HeatFlux.FromWattsPerSquareInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromWattsPerSquareInch(value.ToDouble(null)); + => HeatFlux.FromWattsPerSquareInch(value.ToQuantityValue()); #endif - /// + /// public static HeatFlux WattsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatFlux.FromWattsPerSquareMeter(double.CreateChecked(value)); + => HeatFlux.FromWattsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatFlux.FromWattsPerSquareMeter(value.ToDouble(null)); + => HeatFlux.FromWattsPerSquareMeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToHeatTransferCoefficientExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToHeatTransferCoefficientExtensions.g.cs index 9eb8e34d50..e038cb801b 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToHeatTransferCoefficientExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToHeatTransferCoefficientExtensions.g.cs @@ -32,59 +32,59 @@ namespace UnitsNet.NumberExtensions.NumberToHeatTransferCoefficient /// public static class NumberToHeatTransferCoefficientExtensions { - /// + /// public static HeatTransferCoefficient BtusPerHourSquareFootDegreeFahrenheit(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatTransferCoefficient.FromBtusPerHourSquareFootDegreeFahrenheit(double.CreateChecked(value)); + => HeatTransferCoefficient.FromBtusPerHourSquareFootDegreeFahrenheit(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatTransferCoefficient.FromBtusPerHourSquareFootDegreeFahrenheit(value.ToDouble(null)); + => HeatTransferCoefficient.FromBtusPerHourSquareFootDegreeFahrenheit(value.ToQuantityValue()); #endif - /// + /// public static HeatTransferCoefficient CaloriesPerHourSquareMeterDegreeCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatTransferCoefficient.FromCaloriesPerHourSquareMeterDegreeCelsius(double.CreateChecked(value)); + => HeatTransferCoefficient.FromCaloriesPerHourSquareMeterDegreeCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatTransferCoefficient.FromCaloriesPerHourSquareMeterDegreeCelsius(value.ToDouble(null)); + => HeatTransferCoefficient.FromCaloriesPerHourSquareMeterDegreeCelsius(value.ToQuantityValue()); #endif - /// + /// public static HeatTransferCoefficient KilocaloriesPerHourSquareMeterDegreeCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatTransferCoefficient.FromKilocaloriesPerHourSquareMeterDegreeCelsius(double.CreateChecked(value)); + => HeatTransferCoefficient.FromKilocaloriesPerHourSquareMeterDegreeCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatTransferCoefficient.FromKilocaloriesPerHourSquareMeterDegreeCelsius(value.ToDouble(null)); + => HeatTransferCoefficient.FromKilocaloriesPerHourSquareMeterDegreeCelsius(value.ToQuantityValue()); #endif - /// + /// public static HeatTransferCoefficient WattsPerSquareMeterCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatTransferCoefficient.FromWattsPerSquareMeterCelsius(double.CreateChecked(value)); + => HeatTransferCoefficient.FromWattsPerSquareMeterCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatTransferCoefficient.FromWattsPerSquareMeterCelsius(value.ToDouble(null)); + => HeatTransferCoefficient.FromWattsPerSquareMeterCelsius(value.ToQuantityValue()); #endif - /// + /// public static HeatTransferCoefficient WattsPerSquareMeterKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(double.CreateChecked(value)); + => HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(value.ToDouble(null)); + => HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToIlluminanceExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToIlluminanceExtensions.g.cs index 0367a8f14c..449169eda5 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToIlluminanceExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToIlluminanceExtensions.g.cs @@ -32,48 +32,48 @@ namespace UnitsNet.NumberExtensions.NumberToIlluminance /// public static class NumberToIlluminanceExtensions { - /// + /// public static Illuminance Kilolux(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Illuminance.FromKilolux(double.CreateChecked(value)); + => Illuminance.FromKilolux(QuantityValue.CreateChecked(value)); #else , IConvertible - => Illuminance.FromKilolux(value.ToDouble(null)); + => Illuminance.FromKilolux(value.ToQuantityValue()); #endif - /// + /// public static Illuminance Lux(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Illuminance.FromLux(double.CreateChecked(value)); + => Illuminance.FromLux(QuantityValue.CreateChecked(value)); #else , IConvertible - => Illuminance.FromLux(value.ToDouble(null)); + => Illuminance.FromLux(value.ToQuantityValue()); #endif - /// + /// public static Illuminance Megalux(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Illuminance.FromMegalux(double.CreateChecked(value)); + => Illuminance.FromMegalux(QuantityValue.CreateChecked(value)); #else , IConvertible - => Illuminance.FromMegalux(value.ToDouble(null)); + => Illuminance.FromMegalux(value.ToQuantityValue()); #endif - /// + /// public static Illuminance Millilux(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Illuminance.FromMillilux(double.CreateChecked(value)); + => Illuminance.FromMillilux(QuantityValue.CreateChecked(value)); #else , IConvertible - => Illuminance.FromMillilux(value.ToDouble(null)); + => Illuminance.FromMillilux(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToImpulseExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToImpulseExtensions.g.cs index 35cff39110..cacacb3bfc 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToImpulseExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToImpulseExtensions.g.cs @@ -32,147 +32,147 @@ namespace UnitsNet.NumberExtensions.NumberToImpulse /// public static class NumberToImpulseExtensions { - /// + /// public static Impulse CentinewtonSeconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Impulse.FromCentinewtonSeconds(double.CreateChecked(value)); + => Impulse.FromCentinewtonSeconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Impulse.FromCentinewtonSeconds(value.ToDouble(null)); + => Impulse.FromCentinewtonSeconds(value.ToQuantityValue()); #endif - /// + /// public static Impulse DecanewtonSeconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Impulse.FromDecanewtonSeconds(double.CreateChecked(value)); + => Impulse.FromDecanewtonSeconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Impulse.FromDecanewtonSeconds(value.ToDouble(null)); + => Impulse.FromDecanewtonSeconds(value.ToQuantityValue()); #endif - /// + /// public static Impulse DecinewtonSeconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Impulse.FromDecinewtonSeconds(double.CreateChecked(value)); + => Impulse.FromDecinewtonSeconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Impulse.FromDecinewtonSeconds(value.ToDouble(null)); + => Impulse.FromDecinewtonSeconds(value.ToQuantityValue()); #endif - /// + /// public static Impulse KilogramMetersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Impulse.FromKilogramMetersPerSecond(double.CreateChecked(value)); + => Impulse.FromKilogramMetersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Impulse.FromKilogramMetersPerSecond(value.ToDouble(null)); + => Impulse.FromKilogramMetersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static Impulse KilonewtonSeconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Impulse.FromKilonewtonSeconds(double.CreateChecked(value)); + => Impulse.FromKilonewtonSeconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Impulse.FromKilonewtonSeconds(value.ToDouble(null)); + => Impulse.FromKilonewtonSeconds(value.ToQuantityValue()); #endif - /// + /// public static Impulse MeganewtonSeconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Impulse.FromMeganewtonSeconds(double.CreateChecked(value)); + => Impulse.FromMeganewtonSeconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Impulse.FromMeganewtonSeconds(value.ToDouble(null)); + => Impulse.FromMeganewtonSeconds(value.ToQuantityValue()); #endif - /// + /// public static Impulse MicronewtonSeconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Impulse.FromMicronewtonSeconds(double.CreateChecked(value)); + => Impulse.FromMicronewtonSeconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Impulse.FromMicronewtonSeconds(value.ToDouble(null)); + => Impulse.FromMicronewtonSeconds(value.ToQuantityValue()); #endif - /// + /// public static Impulse MillinewtonSeconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Impulse.FromMillinewtonSeconds(double.CreateChecked(value)); + => Impulse.FromMillinewtonSeconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Impulse.FromMillinewtonSeconds(value.ToDouble(null)); + => Impulse.FromMillinewtonSeconds(value.ToQuantityValue()); #endif - /// + /// public static Impulse NanonewtonSeconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Impulse.FromNanonewtonSeconds(double.CreateChecked(value)); + => Impulse.FromNanonewtonSeconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Impulse.FromNanonewtonSeconds(value.ToDouble(null)); + => Impulse.FromNanonewtonSeconds(value.ToQuantityValue()); #endif - /// + /// public static Impulse NewtonSeconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Impulse.FromNewtonSeconds(double.CreateChecked(value)); + => Impulse.FromNewtonSeconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Impulse.FromNewtonSeconds(value.ToDouble(null)); + => Impulse.FromNewtonSeconds(value.ToQuantityValue()); #endif - /// + /// public static Impulse PoundFeetPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Impulse.FromPoundFeetPerSecond(double.CreateChecked(value)); + => Impulse.FromPoundFeetPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Impulse.FromPoundFeetPerSecond(value.ToDouble(null)); + => Impulse.FromPoundFeetPerSecond(value.ToQuantityValue()); #endif - /// + /// public static Impulse PoundForceSeconds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Impulse.FromPoundForceSeconds(double.CreateChecked(value)); + => Impulse.FromPoundForceSeconds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Impulse.FromPoundForceSeconds(value.ToDouble(null)); + => Impulse.FromPoundForceSeconds(value.ToQuantityValue()); #endif - /// + /// public static Impulse SlugFeetPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Impulse.FromSlugFeetPerSecond(double.CreateChecked(value)); + => Impulse.FromSlugFeetPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Impulse.FromSlugFeetPerSecond(value.ToDouble(null)); + => Impulse.FromSlugFeetPerSecond(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToInformationExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToInformationExtensions.g.cs index 3158412758..ea679fa744 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToInformationExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToInformationExtensions.g.cs @@ -32,433 +32,433 @@ namespace UnitsNet.NumberExtensions.NumberToInformation /// public static class NumberToInformationExtensions { - /// + /// public static Information Bits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromBits(double.CreateChecked(value)); + => Information.FromBits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromBits(value.ToDouble(null)); + => Information.FromBits(value.ToQuantityValue()); #endif - /// + /// public static Information Bytes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromBytes(double.CreateChecked(value)); + => Information.FromBytes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromBytes(value.ToDouble(null)); + => Information.FromBytes(value.ToQuantityValue()); #endif - /// + /// public static Information Exabits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromExabits(double.CreateChecked(value)); + => Information.FromExabits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromExabits(value.ToDouble(null)); + => Information.FromExabits(value.ToQuantityValue()); #endif - /// + /// public static Information Exabytes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromExabytes(double.CreateChecked(value)); + => Information.FromExabytes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromExabytes(value.ToDouble(null)); + => Information.FromExabytes(value.ToQuantityValue()); #endif - /// + /// public static Information Exaoctets(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromExaoctets(double.CreateChecked(value)); + => Information.FromExaoctets(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromExaoctets(value.ToDouble(null)); + => Information.FromExaoctets(value.ToQuantityValue()); #endif - /// + /// public static Information Exbibits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromExbibits(double.CreateChecked(value)); + => Information.FromExbibits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromExbibits(value.ToDouble(null)); + => Information.FromExbibits(value.ToQuantityValue()); #endif - /// + /// public static Information Exbibytes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromExbibytes(double.CreateChecked(value)); + => Information.FromExbibytes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromExbibytes(value.ToDouble(null)); + => Information.FromExbibytes(value.ToQuantityValue()); #endif - /// + /// public static Information Exbioctets(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromExbioctets(double.CreateChecked(value)); + => Information.FromExbioctets(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromExbioctets(value.ToDouble(null)); + => Information.FromExbioctets(value.ToQuantityValue()); #endif - /// + /// public static Information Gibibits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromGibibits(double.CreateChecked(value)); + => Information.FromGibibits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromGibibits(value.ToDouble(null)); + => Information.FromGibibits(value.ToQuantityValue()); #endif - /// + /// public static Information Gibibytes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromGibibytes(double.CreateChecked(value)); + => Information.FromGibibytes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromGibibytes(value.ToDouble(null)); + => Information.FromGibibytes(value.ToQuantityValue()); #endif - /// + /// public static Information Gibioctets(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromGibioctets(double.CreateChecked(value)); + => Information.FromGibioctets(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromGibioctets(value.ToDouble(null)); + => Information.FromGibioctets(value.ToQuantityValue()); #endif - /// + /// public static Information Gigabits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromGigabits(double.CreateChecked(value)); + => Information.FromGigabits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromGigabits(value.ToDouble(null)); + => Information.FromGigabits(value.ToQuantityValue()); #endif - /// + /// public static Information Gigabytes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromGigabytes(double.CreateChecked(value)); + => Information.FromGigabytes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromGigabytes(value.ToDouble(null)); + => Information.FromGigabytes(value.ToQuantityValue()); #endif - /// + /// public static Information Gigaoctets(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromGigaoctets(double.CreateChecked(value)); + => Information.FromGigaoctets(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromGigaoctets(value.ToDouble(null)); + => Information.FromGigaoctets(value.ToQuantityValue()); #endif - /// + /// public static Information Kibibits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromKibibits(double.CreateChecked(value)); + => Information.FromKibibits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromKibibits(value.ToDouble(null)); + => Information.FromKibibits(value.ToQuantityValue()); #endif - /// + /// public static Information Kibibytes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromKibibytes(double.CreateChecked(value)); + => Information.FromKibibytes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromKibibytes(value.ToDouble(null)); + => Information.FromKibibytes(value.ToQuantityValue()); #endif - /// + /// public static Information Kibioctets(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromKibioctets(double.CreateChecked(value)); + => Information.FromKibioctets(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromKibioctets(value.ToDouble(null)); + => Information.FromKibioctets(value.ToQuantityValue()); #endif - /// + /// public static Information Kilobits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromKilobits(double.CreateChecked(value)); + => Information.FromKilobits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromKilobits(value.ToDouble(null)); + => Information.FromKilobits(value.ToQuantityValue()); #endif - /// + /// public static Information Kilobytes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromKilobytes(double.CreateChecked(value)); + => Information.FromKilobytes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromKilobytes(value.ToDouble(null)); + => Information.FromKilobytes(value.ToQuantityValue()); #endif - /// + /// public static Information Kilooctets(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromKilooctets(double.CreateChecked(value)); + => Information.FromKilooctets(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromKilooctets(value.ToDouble(null)); + => Information.FromKilooctets(value.ToQuantityValue()); #endif - /// + /// public static Information Mebibits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromMebibits(double.CreateChecked(value)); + => Information.FromMebibits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromMebibits(value.ToDouble(null)); + => Information.FromMebibits(value.ToQuantityValue()); #endif - /// + /// public static Information Mebibytes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromMebibytes(double.CreateChecked(value)); + => Information.FromMebibytes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromMebibytes(value.ToDouble(null)); + => Information.FromMebibytes(value.ToQuantityValue()); #endif - /// + /// public static Information Mebioctets(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromMebioctets(double.CreateChecked(value)); + => Information.FromMebioctets(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromMebioctets(value.ToDouble(null)); + => Information.FromMebioctets(value.ToQuantityValue()); #endif - /// + /// public static Information Megabits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromMegabits(double.CreateChecked(value)); + => Information.FromMegabits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromMegabits(value.ToDouble(null)); + => Information.FromMegabits(value.ToQuantityValue()); #endif - /// + /// public static Information Megabytes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromMegabytes(double.CreateChecked(value)); + => Information.FromMegabytes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromMegabytes(value.ToDouble(null)); + => Information.FromMegabytes(value.ToQuantityValue()); #endif - /// + /// public static Information Megaoctets(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromMegaoctets(double.CreateChecked(value)); + => Information.FromMegaoctets(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromMegaoctets(value.ToDouble(null)); + => Information.FromMegaoctets(value.ToQuantityValue()); #endif - /// + /// public static Information Octets(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromOctets(double.CreateChecked(value)); + => Information.FromOctets(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromOctets(value.ToDouble(null)); + => Information.FromOctets(value.ToQuantityValue()); #endif - /// + /// public static Information Pebibits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromPebibits(double.CreateChecked(value)); + => Information.FromPebibits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromPebibits(value.ToDouble(null)); + => Information.FromPebibits(value.ToQuantityValue()); #endif - /// + /// public static Information Pebibytes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromPebibytes(double.CreateChecked(value)); + => Information.FromPebibytes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromPebibytes(value.ToDouble(null)); + => Information.FromPebibytes(value.ToQuantityValue()); #endif - /// + /// public static Information Pebioctets(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromPebioctets(double.CreateChecked(value)); + => Information.FromPebioctets(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromPebioctets(value.ToDouble(null)); + => Information.FromPebioctets(value.ToQuantityValue()); #endif - /// + /// public static Information Petabits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromPetabits(double.CreateChecked(value)); + => Information.FromPetabits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromPetabits(value.ToDouble(null)); + => Information.FromPetabits(value.ToQuantityValue()); #endif - /// + /// public static Information Petabytes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromPetabytes(double.CreateChecked(value)); + => Information.FromPetabytes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromPetabytes(value.ToDouble(null)); + => Information.FromPetabytes(value.ToQuantityValue()); #endif - /// + /// public static Information Petaoctets(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromPetaoctets(double.CreateChecked(value)); + => Information.FromPetaoctets(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromPetaoctets(value.ToDouble(null)); + => Information.FromPetaoctets(value.ToQuantityValue()); #endif - /// + /// public static Information Tebibits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromTebibits(double.CreateChecked(value)); + => Information.FromTebibits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromTebibits(value.ToDouble(null)); + => Information.FromTebibits(value.ToQuantityValue()); #endif - /// + /// public static Information Tebibytes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromTebibytes(double.CreateChecked(value)); + => Information.FromTebibytes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromTebibytes(value.ToDouble(null)); + => Information.FromTebibytes(value.ToQuantityValue()); #endif - /// + /// public static Information Tebioctets(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromTebioctets(double.CreateChecked(value)); + => Information.FromTebioctets(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromTebioctets(value.ToDouble(null)); + => Information.FromTebioctets(value.ToQuantityValue()); #endif - /// + /// public static Information Terabits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromTerabits(double.CreateChecked(value)); + => Information.FromTerabits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromTerabits(value.ToDouble(null)); + => Information.FromTerabits(value.ToQuantityValue()); #endif - /// + /// public static Information Terabytes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromTerabytes(double.CreateChecked(value)); + => Information.FromTerabytes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromTerabytes(value.ToDouble(null)); + => Information.FromTerabytes(value.ToQuantityValue()); #endif - /// + /// public static Information Teraoctets(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Information.FromTeraoctets(double.CreateChecked(value)); + => Information.FromTeraoctets(QuantityValue.CreateChecked(value)); #else , IConvertible - => Information.FromTeraoctets(value.ToDouble(null)); + => Information.FromTeraoctets(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToIrradianceExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToIrradianceExtensions.g.cs index a003581b53..e8fac71f73 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToIrradianceExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToIrradianceExtensions.g.cs @@ -32,158 +32,158 @@ namespace UnitsNet.NumberExtensions.NumberToIrradiance /// public static class NumberToIrradianceExtensions { - /// + /// public static Irradiance KilowattsPerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiance.FromKilowattsPerSquareCentimeter(double.CreateChecked(value)); + => Irradiance.FromKilowattsPerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiance.FromKilowattsPerSquareCentimeter(value.ToDouble(null)); + => Irradiance.FromKilowattsPerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiance KilowattsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiance.FromKilowattsPerSquareMeter(double.CreateChecked(value)); + => Irradiance.FromKilowattsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiance.FromKilowattsPerSquareMeter(value.ToDouble(null)); + => Irradiance.FromKilowattsPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiance MegawattsPerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiance.FromMegawattsPerSquareCentimeter(double.CreateChecked(value)); + => Irradiance.FromMegawattsPerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiance.FromMegawattsPerSquareCentimeter(value.ToDouble(null)); + => Irradiance.FromMegawattsPerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiance MegawattsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiance.FromMegawattsPerSquareMeter(double.CreateChecked(value)); + => Irradiance.FromMegawattsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiance.FromMegawattsPerSquareMeter(value.ToDouble(null)); + => Irradiance.FromMegawattsPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiance MicrowattsPerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiance.FromMicrowattsPerSquareCentimeter(double.CreateChecked(value)); + => Irradiance.FromMicrowattsPerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiance.FromMicrowattsPerSquareCentimeter(value.ToDouble(null)); + => Irradiance.FromMicrowattsPerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiance MicrowattsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiance.FromMicrowattsPerSquareMeter(double.CreateChecked(value)); + => Irradiance.FromMicrowattsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiance.FromMicrowattsPerSquareMeter(value.ToDouble(null)); + => Irradiance.FromMicrowattsPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiance MilliwattsPerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiance.FromMilliwattsPerSquareCentimeter(double.CreateChecked(value)); + => Irradiance.FromMilliwattsPerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiance.FromMilliwattsPerSquareCentimeter(value.ToDouble(null)); + => Irradiance.FromMilliwattsPerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiance MilliwattsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiance.FromMilliwattsPerSquareMeter(double.CreateChecked(value)); + => Irradiance.FromMilliwattsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiance.FromMilliwattsPerSquareMeter(value.ToDouble(null)); + => Irradiance.FromMilliwattsPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiance NanowattsPerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiance.FromNanowattsPerSquareCentimeter(double.CreateChecked(value)); + => Irradiance.FromNanowattsPerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiance.FromNanowattsPerSquareCentimeter(value.ToDouble(null)); + => Irradiance.FromNanowattsPerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiance NanowattsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiance.FromNanowattsPerSquareMeter(double.CreateChecked(value)); + => Irradiance.FromNanowattsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiance.FromNanowattsPerSquareMeter(value.ToDouble(null)); + => Irradiance.FromNanowattsPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiance PicowattsPerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiance.FromPicowattsPerSquareCentimeter(double.CreateChecked(value)); + => Irradiance.FromPicowattsPerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiance.FromPicowattsPerSquareCentimeter(value.ToDouble(null)); + => Irradiance.FromPicowattsPerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiance PicowattsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiance.FromPicowattsPerSquareMeter(double.CreateChecked(value)); + => Irradiance.FromPicowattsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiance.FromPicowattsPerSquareMeter(value.ToDouble(null)); + => Irradiance.FromPicowattsPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiance WattsPerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiance.FromWattsPerSquareCentimeter(double.CreateChecked(value)); + => Irradiance.FromWattsPerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiance.FromWattsPerSquareCentimeter(value.ToDouble(null)); + => Irradiance.FromWattsPerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiance WattsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiance.FromWattsPerSquareMeter(double.CreateChecked(value)); + => Irradiance.FromWattsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiance.FromWattsPerSquareMeter(value.ToDouble(null)); + => Irradiance.FromWattsPerSquareMeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToIrradiationExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToIrradiationExtensions.g.cs index a9fed1227a..4b1c1a21bd 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToIrradiationExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToIrradiationExtensions.g.cs @@ -32,103 +32,103 @@ namespace UnitsNet.NumberExtensions.NumberToIrradiation /// public static class NumberToIrradiationExtensions { - /// + /// public static Irradiation BtusPerSquareFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiation.FromBtusPerSquareFoot(double.CreateChecked(value)); + => Irradiation.FromBtusPerSquareFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiation.FromBtusPerSquareFoot(value.ToDouble(null)); + => Irradiation.FromBtusPerSquareFoot(value.ToQuantityValue()); #endif - /// + /// public static Irradiation JoulesPerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiation.FromJoulesPerSquareCentimeter(double.CreateChecked(value)); + => Irradiation.FromJoulesPerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiation.FromJoulesPerSquareCentimeter(value.ToDouble(null)); + => Irradiation.FromJoulesPerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiation JoulesPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiation.FromJoulesPerSquareMeter(double.CreateChecked(value)); + => Irradiation.FromJoulesPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiation.FromJoulesPerSquareMeter(value.ToDouble(null)); + => Irradiation.FromJoulesPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiation JoulesPerSquareMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiation.FromJoulesPerSquareMillimeter(double.CreateChecked(value)); + => Irradiation.FromJoulesPerSquareMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiation.FromJoulesPerSquareMillimeter(value.ToDouble(null)); + => Irradiation.FromJoulesPerSquareMillimeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiation KilobtusPerSquareFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiation.FromKilobtusPerSquareFoot(double.CreateChecked(value)); + => Irradiation.FromKilobtusPerSquareFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiation.FromKilobtusPerSquareFoot(value.ToDouble(null)); + => Irradiation.FromKilobtusPerSquareFoot(value.ToQuantityValue()); #endif - /// + /// public static Irradiation KilojoulesPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiation.FromKilojoulesPerSquareMeter(double.CreateChecked(value)); + => Irradiation.FromKilojoulesPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiation.FromKilojoulesPerSquareMeter(value.ToDouble(null)); + => Irradiation.FromKilojoulesPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiation KilowattHoursPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiation.FromKilowattHoursPerSquareMeter(double.CreateChecked(value)); + => Irradiation.FromKilowattHoursPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiation.FromKilowattHoursPerSquareMeter(value.ToDouble(null)); + => Irradiation.FromKilowattHoursPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiation MillijoulesPerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiation.FromMillijoulesPerSquareCentimeter(double.CreateChecked(value)); + => Irradiation.FromMillijoulesPerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiation.FromMillijoulesPerSquareCentimeter(value.ToDouble(null)); + => Irradiation.FromMillijoulesPerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Irradiation WattHoursPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Irradiation.FromWattHoursPerSquareMeter(double.CreateChecked(value)); + => Irradiation.FromWattHoursPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Irradiation.FromWattHoursPerSquareMeter(value.ToDouble(null)); + => Irradiation.FromWattHoursPerSquareMeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToJerkExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToJerkExtensions.g.cs index b53a174a31..c87c7d8b01 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToJerkExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToJerkExtensions.g.cs @@ -32,125 +32,125 @@ namespace UnitsNet.NumberExtensions.NumberToJerk /// public static class NumberToJerkExtensions { - /// + /// public static Jerk CentimetersPerSecondCubed(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Jerk.FromCentimetersPerSecondCubed(double.CreateChecked(value)); + => Jerk.FromCentimetersPerSecondCubed(QuantityValue.CreateChecked(value)); #else , IConvertible - => Jerk.FromCentimetersPerSecondCubed(value.ToDouble(null)); + => Jerk.FromCentimetersPerSecondCubed(value.ToQuantityValue()); #endif - /// + /// public static Jerk DecimetersPerSecondCubed(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Jerk.FromDecimetersPerSecondCubed(double.CreateChecked(value)); + => Jerk.FromDecimetersPerSecondCubed(QuantityValue.CreateChecked(value)); #else , IConvertible - => Jerk.FromDecimetersPerSecondCubed(value.ToDouble(null)); + => Jerk.FromDecimetersPerSecondCubed(value.ToQuantityValue()); #endif - /// + /// public static Jerk FeetPerSecondCubed(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Jerk.FromFeetPerSecondCubed(double.CreateChecked(value)); + => Jerk.FromFeetPerSecondCubed(QuantityValue.CreateChecked(value)); #else , IConvertible - => Jerk.FromFeetPerSecondCubed(value.ToDouble(null)); + => Jerk.FromFeetPerSecondCubed(value.ToQuantityValue()); #endif - /// + /// public static Jerk InchesPerSecondCubed(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Jerk.FromInchesPerSecondCubed(double.CreateChecked(value)); + => Jerk.FromInchesPerSecondCubed(QuantityValue.CreateChecked(value)); #else , IConvertible - => Jerk.FromInchesPerSecondCubed(value.ToDouble(null)); + => Jerk.FromInchesPerSecondCubed(value.ToQuantityValue()); #endif - /// + /// public static Jerk KilometersPerSecondCubed(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Jerk.FromKilometersPerSecondCubed(double.CreateChecked(value)); + => Jerk.FromKilometersPerSecondCubed(QuantityValue.CreateChecked(value)); #else , IConvertible - => Jerk.FromKilometersPerSecondCubed(value.ToDouble(null)); + => Jerk.FromKilometersPerSecondCubed(value.ToQuantityValue()); #endif - /// + /// public static Jerk MetersPerSecondCubed(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Jerk.FromMetersPerSecondCubed(double.CreateChecked(value)); + => Jerk.FromMetersPerSecondCubed(QuantityValue.CreateChecked(value)); #else , IConvertible - => Jerk.FromMetersPerSecondCubed(value.ToDouble(null)); + => Jerk.FromMetersPerSecondCubed(value.ToQuantityValue()); #endif - /// + /// public static Jerk MicrometersPerSecondCubed(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Jerk.FromMicrometersPerSecondCubed(double.CreateChecked(value)); + => Jerk.FromMicrometersPerSecondCubed(QuantityValue.CreateChecked(value)); #else , IConvertible - => Jerk.FromMicrometersPerSecondCubed(value.ToDouble(null)); + => Jerk.FromMicrometersPerSecondCubed(value.ToQuantityValue()); #endif - /// + /// public static Jerk MillimetersPerSecondCubed(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Jerk.FromMillimetersPerSecondCubed(double.CreateChecked(value)); + => Jerk.FromMillimetersPerSecondCubed(QuantityValue.CreateChecked(value)); #else , IConvertible - => Jerk.FromMillimetersPerSecondCubed(value.ToDouble(null)); + => Jerk.FromMillimetersPerSecondCubed(value.ToQuantityValue()); #endif - /// + /// public static Jerk MillistandardGravitiesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Jerk.FromMillistandardGravitiesPerSecond(double.CreateChecked(value)); + => Jerk.FromMillistandardGravitiesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Jerk.FromMillistandardGravitiesPerSecond(value.ToDouble(null)); + => Jerk.FromMillistandardGravitiesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static Jerk NanometersPerSecondCubed(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Jerk.FromNanometersPerSecondCubed(double.CreateChecked(value)); + => Jerk.FromNanometersPerSecondCubed(QuantityValue.CreateChecked(value)); #else , IConvertible - => Jerk.FromNanometersPerSecondCubed(value.ToDouble(null)); + => Jerk.FromNanometersPerSecondCubed(value.ToQuantityValue()); #endif - /// + /// public static Jerk StandardGravitiesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Jerk.FromStandardGravitiesPerSecond(double.CreateChecked(value)); + => Jerk.FromStandardGravitiesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Jerk.FromStandardGravitiesPerSecond(value.ToDouble(null)); + => Jerk.FromStandardGravitiesPerSecond(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToKinematicViscosityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToKinematicViscosityExtensions.g.cs index 0d0b8432a0..471121df00 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToKinematicViscosityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToKinematicViscosityExtensions.g.cs @@ -32,103 +32,103 @@ namespace UnitsNet.NumberExtensions.NumberToKinematicViscosity /// public static class NumberToKinematicViscosityExtensions { - /// + /// public static KinematicViscosity Centistokes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => KinematicViscosity.FromCentistokes(double.CreateChecked(value)); + => KinematicViscosity.FromCentistokes(QuantityValue.CreateChecked(value)); #else , IConvertible - => KinematicViscosity.FromCentistokes(value.ToDouble(null)); + => KinematicViscosity.FromCentistokes(value.ToQuantityValue()); #endif - /// + /// public static KinematicViscosity Decistokes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => KinematicViscosity.FromDecistokes(double.CreateChecked(value)); + => KinematicViscosity.FromDecistokes(QuantityValue.CreateChecked(value)); #else , IConvertible - => KinematicViscosity.FromDecistokes(value.ToDouble(null)); + => KinematicViscosity.FromDecistokes(value.ToQuantityValue()); #endif - /// + /// public static KinematicViscosity Kilostokes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => KinematicViscosity.FromKilostokes(double.CreateChecked(value)); + => KinematicViscosity.FromKilostokes(QuantityValue.CreateChecked(value)); #else , IConvertible - => KinematicViscosity.FromKilostokes(value.ToDouble(null)); + => KinematicViscosity.FromKilostokes(value.ToQuantityValue()); #endif - /// + /// public static KinematicViscosity Microstokes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => KinematicViscosity.FromMicrostokes(double.CreateChecked(value)); + => KinematicViscosity.FromMicrostokes(QuantityValue.CreateChecked(value)); #else , IConvertible - => KinematicViscosity.FromMicrostokes(value.ToDouble(null)); + => KinematicViscosity.FromMicrostokes(value.ToQuantityValue()); #endif - /// + /// public static KinematicViscosity Millistokes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => KinematicViscosity.FromMillistokes(double.CreateChecked(value)); + => KinematicViscosity.FromMillistokes(QuantityValue.CreateChecked(value)); #else , IConvertible - => KinematicViscosity.FromMillistokes(value.ToDouble(null)); + => KinematicViscosity.FromMillistokes(value.ToQuantityValue()); #endif - /// + /// public static KinematicViscosity Nanostokes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => KinematicViscosity.FromNanostokes(double.CreateChecked(value)); + => KinematicViscosity.FromNanostokes(QuantityValue.CreateChecked(value)); #else , IConvertible - => KinematicViscosity.FromNanostokes(value.ToDouble(null)); + => KinematicViscosity.FromNanostokes(value.ToQuantityValue()); #endif - /// + /// public static KinematicViscosity SquareFeetPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => KinematicViscosity.FromSquareFeetPerSecond(double.CreateChecked(value)); + => KinematicViscosity.FromSquareFeetPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => KinematicViscosity.FromSquareFeetPerSecond(value.ToDouble(null)); + => KinematicViscosity.FromSquareFeetPerSecond(value.ToQuantityValue()); #endif - /// + /// public static KinematicViscosity SquareMetersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => KinematicViscosity.FromSquareMetersPerSecond(double.CreateChecked(value)); + => KinematicViscosity.FromSquareMetersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => KinematicViscosity.FromSquareMetersPerSecond(value.ToDouble(null)); + => KinematicViscosity.FromSquareMetersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static KinematicViscosity Stokes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => KinematicViscosity.FromStokes(double.CreateChecked(value)); + => KinematicViscosity.FromStokes(QuantityValue.CreateChecked(value)); #else , IConvertible - => KinematicViscosity.FromStokes(value.ToDouble(null)); + => KinematicViscosity.FromStokes(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLeakRateExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLeakRateExtensions.g.cs index 97baf4167b..91f7a37b12 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLeakRateExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLeakRateExtensions.g.cs @@ -32,48 +32,48 @@ namespace UnitsNet.NumberExtensions.NumberToLeakRate /// public static class NumberToLeakRateExtensions { - /// + /// public static LeakRate AtmCubicCentimetersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LeakRate.FromAtmCubicCentimetersPerSecond(double.CreateChecked(value)); + => LeakRate.FromAtmCubicCentimetersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => LeakRate.FromAtmCubicCentimetersPerSecond(value.ToDouble(null)); + => LeakRate.FromAtmCubicCentimetersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static LeakRate MillibarLitersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LeakRate.FromMillibarLitersPerSecond(double.CreateChecked(value)); + => LeakRate.FromMillibarLitersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => LeakRate.FromMillibarLitersPerSecond(value.ToDouble(null)); + => LeakRate.FromMillibarLitersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static LeakRate PascalCubicMetersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LeakRate.FromPascalCubicMetersPerSecond(double.CreateChecked(value)); + => LeakRate.FromPascalCubicMetersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => LeakRate.FromPascalCubicMetersPerSecond(value.ToDouble(null)); + => LeakRate.FromPascalCubicMetersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static LeakRate TorrLitersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LeakRate.FromTorrLitersPerSecond(double.CreateChecked(value)); + => LeakRate.FromTorrLitersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => LeakRate.FromTorrLitersPerSecond(value.ToDouble(null)); + => LeakRate.FromTorrLitersPerSecond(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLengthExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLengthExtensions.g.cs index 2ef0258f35..08c56dc264 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLengthExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLengthExtensions.g.cs @@ -32,466 +32,466 @@ namespace UnitsNet.NumberExtensions.NumberToLength /// public static class NumberToLengthExtensions { - /// + /// public static Length Angstroms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromAngstroms(double.CreateChecked(value)); + => Length.FromAngstroms(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromAngstroms(value.ToDouble(null)); + => Length.FromAngstroms(value.ToQuantityValue()); #endif - /// + /// public static Length AstronomicalUnits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromAstronomicalUnits(double.CreateChecked(value)); + => Length.FromAstronomicalUnits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromAstronomicalUnits(value.ToDouble(null)); + => Length.FromAstronomicalUnits(value.ToQuantityValue()); #endif - /// + /// public static Length Centimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromCentimeters(double.CreateChecked(value)); + => Length.FromCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromCentimeters(value.ToDouble(null)); + => Length.FromCentimeters(value.ToQuantityValue()); #endif - /// + /// public static Length Chains(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromChains(double.CreateChecked(value)); + => Length.FromChains(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromChains(value.ToDouble(null)); + => Length.FromChains(value.ToQuantityValue()); #endif - /// + /// public static Length DataMiles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromDataMiles(double.CreateChecked(value)); + => Length.FromDataMiles(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromDataMiles(value.ToDouble(null)); + => Length.FromDataMiles(value.ToQuantityValue()); #endif - /// + /// public static Length Decameters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromDecameters(double.CreateChecked(value)); + => Length.FromDecameters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromDecameters(value.ToDouble(null)); + => Length.FromDecameters(value.ToQuantityValue()); #endif - /// + /// public static Length Decimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromDecimeters(double.CreateChecked(value)); + => Length.FromDecimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromDecimeters(value.ToDouble(null)); + => Length.FromDecimeters(value.ToQuantityValue()); #endif - /// + /// public static Length DtpPicas(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromDtpPicas(double.CreateChecked(value)); + => Length.FromDtpPicas(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromDtpPicas(value.ToDouble(null)); + => Length.FromDtpPicas(value.ToQuantityValue()); #endif - /// + /// public static Length DtpPoints(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromDtpPoints(double.CreateChecked(value)); + => Length.FromDtpPoints(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromDtpPoints(value.ToDouble(null)); + => Length.FromDtpPoints(value.ToQuantityValue()); #endif - /// + /// public static Length Fathoms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromFathoms(double.CreateChecked(value)); + => Length.FromFathoms(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromFathoms(value.ToDouble(null)); + => Length.FromFathoms(value.ToQuantityValue()); #endif - /// + /// public static Length Femtometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromFemtometers(double.CreateChecked(value)); + => Length.FromFemtometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromFemtometers(value.ToDouble(null)); + => Length.FromFemtometers(value.ToQuantityValue()); #endif - /// + /// public static Length Feet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromFeet(double.CreateChecked(value)); + => Length.FromFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromFeet(value.ToDouble(null)); + => Length.FromFeet(value.ToQuantityValue()); #endif - /// + /// public static Length Gigameters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromGigameters(double.CreateChecked(value)); + => Length.FromGigameters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromGigameters(value.ToDouble(null)); + => Length.FromGigameters(value.ToQuantityValue()); #endif - /// + /// public static Length Hands(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromHands(double.CreateChecked(value)); + => Length.FromHands(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromHands(value.ToDouble(null)); + => Length.FromHands(value.ToQuantityValue()); #endif - /// + /// public static Length Hectometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromHectometers(double.CreateChecked(value)); + => Length.FromHectometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromHectometers(value.ToDouble(null)); + => Length.FromHectometers(value.ToQuantityValue()); #endif - /// + /// public static Length Inches(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromInches(double.CreateChecked(value)); + => Length.FromInches(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromInches(value.ToDouble(null)); + => Length.FromInches(value.ToQuantityValue()); #endif - /// + /// public static Length Kilofeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromKilofeet(double.CreateChecked(value)); + => Length.FromKilofeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromKilofeet(value.ToDouble(null)); + => Length.FromKilofeet(value.ToQuantityValue()); #endif - /// + /// public static Length KilolightYears(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromKilolightYears(double.CreateChecked(value)); + => Length.FromKilolightYears(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromKilolightYears(value.ToDouble(null)); + => Length.FromKilolightYears(value.ToQuantityValue()); #endif - /// + /// public static Length Kilometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromKilometers(double.CreateChecked(value)); + => Length.FromKilometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromKilometers(value.ToDouble(null)); + => Length.FromKilometers(value.ToQuantityValue()); #endif - /// + /// public static Length Kiloparsecs(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromKiloparsecs(double.CreateChecked(value)); + => Length.FromKiloparsecs(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromKiloparsecs(value.ToDouble(null)); + => Length.FromKiloparsecs(value.ToQuantityValue()); #endif - /// + /// public static Length Kiloyards(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromKiloyards(double.CreateChecked(value)); + => Length.FromKiloyards(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromKiloyards(value.ToDouble(null)); + => Length.FromKiloyards(value.ToQuantityValue()); #endif - /// + /// public static Length LightYears(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromLightYears(double.CreateChecked(value)); + => Length.FromLightYears(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromLightYears(value.ToDouble(null)); + => Length.FromLightYears(value.ToQuantityValue()); #endif - /// + /// public static Length MegalightYears(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromMegalightYears(double.CreateChecked(value)); + => Length.FromMegalightYears(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromMegalightYears(value.ToDouble(null)); + => Length.FromMegalightYears(value.ToQuantityValue()); #endif - /// + /// public static Length Megameters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromMegameters(double.CreateChecked(value)); + => Length.FromMegameters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromMegameters(value.ToDouble(null)); + => Length.FromMegameters(value.ToQuantityValue()); #endif - /// + /// public static Length Megaparsecs(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromMegaparsecs(double.CreateChecked(value)); + => Length.FromMegaparsecs(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromMegaparsecs(value.ToDouble(null)); + => Length.FromMegaparsecs(value.ToQuantityValue()); #endif - /// + /// public static Length Meters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromMeters(double.CreateChecked(value)); + => Length.FromMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromMeters(value.ToDouble(null)); + => Length.FromMeters(value.ToQuantityValue()); #endif - /// + /// public static Length Microinches(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromMicroinches(double.CreateChecked(value)); + => Length.FromMicroinches(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromMicroinches(value.ToDouble(null)); + => Length.FromMicroinches(value.ToQuantityValue()); #endif - /// + /// public static Length Micrometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromMicrometers(double.CreateChecked(value)); + => Length.FromMicrometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromMicrometers(value.ToDouble(null)); + => Length.FromMicrometers(value.ToQuantityValue()); #endif - /// + /// public static Length Mils(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromMils(double.CreateChecked(value)); + => Length.FromMils(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromMils(value.ToDouble(null)); + => Length.FromMils(value.ToQuantityValue()); #endif - /// + /// public static Length Miles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromMiles(double.CreateChecked(value)); + => Length.FromMiles(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromMiles(value.ToDouble(null)); + => Length.FromMiles(value.ToQuantityValue()); #endif - /// + /// public static Length Millimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromMillimeters(double.CreateChecked(value)); + => Length.FromMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromMillimeters(value.ToDouble(null)); + => Length.FromMillimeters(value.ToQuantityValue()); #endif - /// + /// public static Length Nanometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromNanometers(double.CreateChecked(value)); + => Length.FromNanometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromNanometers(value.ToDouble(null)); + => Length.FromNanometers(value.ToQuantityValue()); #endif - /// + /// public static Length NauticalMiles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromNauticalMiles(double.CreateChecked(value)); + => Length.FromNauticalMiles(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromNauticalMiles(value.ToDouble(null)); + => Length.FromNauticalMiles(value.ToQuantityValue()); #endif - /// + /// public static Length Parsecs(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromParsecs(double.CreateChecked(value)); + => Length.FromParsecs(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromParsecs(value.ToDouble(null)); + => Length.FromParsecs(value.ToQuantityValue()); #endif - /// + /// public static Length Picometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromPicometers(double.CreateChecked(value)); + => Length.FromPicometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromPicometers(value.ToDouble(null)); + => Length.FromPicometers(value.ToQuantityValue()); #endif - /// + /// public static Length PrinterPicas(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromPrinterPicas(double.CreateChecked(value)); + => Length.FromPrinterPicas(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromPrinterPicas(value.ToDouble(null)); + => Length.FromPrinterPicas(value.ToQuantityValue()); #endif - /// + /// public static Length PrinterPoints(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromPrinterPoints(double.CreateChecked(value)); + => Length.FromPrinterPoints(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromPrinterPoints(value.ToDouble(null)); + => Length.FromPrinterPoints(value.ToQuantityValue()); #endif - /// + /// public static Length Shackles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromShackles(double.CreateChecked(value)); + => Length.FromShackles(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromShackles(value.ToDouble(null)); + => Length.FromShackles(value.ToQuantityValue()); #endif - /// + /// public static Length SolarRadiuses(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromSolarRadiuses(double.CreateChecked(value)); + => Length.FromSolarRadiuses(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromSolarRadiuses(value.ToDouble(null)); + => Length.FromSolarRadiuses(value.ToQuantityValue()); #endif - /// + /// public static Length Twips(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromTwips(double.CreateChecked(value)); + => Length.FromTwips(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromTwips(value.ToDouble(null)); + => Length.FromTwips(value.ToQuantityValue()); #endif - /// + /// public static Length UsSurveyFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromUsSurveyFeet(double.CreateChecked(value)); + => Length.FromUsSurveyFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromUsSurveyFeet(value.ToDouble(null)); + => Length.FromUsSurveyFeet(value.ToQuantityValue()); #endif - /// + /// public static Length Yards(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Length.FromYards(double.CreateChecked(value)); + => Length.FromYards(QuantityValue.CreateChecked(value)); #else , IConvertible - => Length.FromYards(value.ToDouble(null)); + => Length.FromYards(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLevelExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLevelExtensions.g.cs index 8152e30451..639ed80d32 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLevelExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLevelExtensions.g.cs @@ -32,26 +32,26 @@ namespace UnitsNet.NumberExtensions.NumberToLevel /// public static class NumberToLevelExtensions { - /// + /// public static Level Decibels(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Level.FromDecibels(double.CreateChecked(value)); + => Level.FromDecibels(QuantityValue.CreateChecked(value)); #else , IConvertible - => Level.FromDecibels(value.ToDouble(null)); + => Level.FromDecibels(value.ToQuantityValue()); #endif - /// + /// public static Level Nepers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Level.FromNepers(double.CreateChecked(value)); + => Level.FromNepers(QuantityValue.CreateChecked(value)); #else , IConvertible - => Level.FromNepers(value.ToDouble(null)); + => Level.FromNepers(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLinearDensityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLinearDensityExtensions.g.cs index 59b841b487..b23ed92c4f 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLinearDensityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLinearDensityExtensions.g.cs @@ -32,202 +32,202 @@ namespace UnitsNet.NumberExtensions.NumberToLinearDensity /// public static class NumberToLinearDensityExtensions { - /// + /// public static LinearDensity GramsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromGramsPerCentimeter(double.CreateChecked(value)); + => LinearDensity.FromGramsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromGramsPerCentimeter(value.ToDouble(null)); + => LinearDensity.FromGramsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static LinearDensity GramsPerFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromGramsPerFoot(double.CreateChecked(value)); + => LinearDensity.FromGramsPerFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromGramsPerFoot(value.ToDouble(null)); + => LinearDensity.FromGramsPerFoot(value.ToQuantityValue()); #endif - /// + /// public static LinearDensity GramsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromGramsPerMeter(double.CreateChecked(value)); + => LinearDensity.FromGramsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromGramsPerMeter(value.ToDouble(null)); + => LinearDensity.FromGramsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static LinearDensity GramsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromGramsPerMillimeter(double.CreateChecked(value)); + => LinearDensity.FromGramsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromGramsPerMillimeter(value.ToDouble(null)); + => LinearDensity.FromGramsPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static LinearDensity KilogramsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromKilogramsPerCentimeter(double.CreateChecked(value)); + => LinearDensity.FromKilogramsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromKilogramsPerCentimeter(value.ToDouble(null)); + => LinearDensity.FromKilogramsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static LinearDensity KilogramsPerFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromKilogramsPerFoot(double.CreateChecked(value)); + => LinearDensity.FromKilogramsPerFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromKilogramsPerFoot(value.ToDouble(null)); + => LinearDensity.FromKilogramsPerFoot(value.ToQuantityValue()); #endif - /// + /// public static LinearDensity KilogramsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromKilogramsPerMeter(double.CreateChecked(value)); + => LinearDensity.FromKilogramsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromKilogramsPerMeter(value.ToDouble(null)); + => LinearDensity.FromKilogramsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static LinearDensity KilogramsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromKilogramsPerMillimeter(double.CreateChecked(value)); + => LinearDensity.FromKilogramsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromKilogramsPerMillimeter(value.ToDouble(null)); + => LinearDensity.FromKilogramsPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static LinearDensity MicrogramsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromMicrogramsPerCentimeter(double.CreateChecked(value)); + => LinearDensity.FromMicrogramsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromMicrogramsPerCentimeter(value.ToDouble(null)); + => LinearDensity.FromMicrogramsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static LinearDensity MicrogramsPerFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromMicrogramsPerFoot(double.CreateChecked(value)); + => LinearDensity.FromMicrogramsPerFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromMicrogramsPerFoot(value.ToDouble(null)); + => LinearDensity.FromMicrogramsPerFoot(value.ToQuantityValue()); #endif - /// + /// public static LinearDensity MicrogramsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromMicrogramsPerMeter(double.CreateChecked(value)); + => LinearDensity.FromMicrogramsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromMicrogramsPerMeter(value.ToDouble(null)); + => LinearDensity.FromMicrogramsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static LinearDensity MicrogramsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromMicrogramsPerMillimeter(double.CreateChecked(value)); + => LinearDensity.FromMicrogramsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromMicrogramsPerMillimeter(value.ToDouble(null)); + => LinearDensity.FromMicrogramsPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static LinearDensity MilligramsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromMilligramsPerCentimeter(double.CreateChecked(value)); + => LinearDensity.FromMilligramsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromMilligramsPerCentimeter(value.ToDouble(null)); + => LinearDensity.FromMilligramsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static LinearDensity MilligramsPerFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromMilligramsPerFoot(double.CreateChecked(value)); + => LinearDensity.FromMilligramsPerFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromMilligramsPerFoot(value.ToDouble(null)); + => LinearDensity.FromMilligramsPerFoot(value.ToQuantityValue()); #endif - /// + /// public static LinearDensity MilligramsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromMilligramsPerMeter(double.CreateChecked(value)); + => LinearDensity.FromMilligramsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromMilligramsPerMeter(value.ToDouble(null)); + => LinearDensity.FromMilligramsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static LinearDensity MilligramsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromMilligramsPerMillimeter(double.CreateChecked(value)); + => LinearDensity.FromMilligramsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromMilligramsPerMillimeter(value.ToDouble(null)); + => LinearDensity.FromMilligramsPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static LinearDensity PoundsPerFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromPoundsPerFoot(double.CreateChecked(value)); + => LinearDensity.FromPoundsPerFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromPoundsPerFoot(value.ToDouble(null)); + => LinearDensity.FromPoundsPerFoot(value.ToQuantityValue()); #endif - /// + /// public static LinearDensity PoundsPerInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearDensity.FromPoundsPerInch(double.CreateChecked(value)); + => LinearDensity.FromPoundsPerInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearDensity.FromPoundsPerInch(value.ToDouble(null)); + => LinearDensity.FromPoundsPerInch(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLinearPowerDensityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLinearPowerDensityExtensions.g.cs index 3f32d79b86..ab06b93b5b 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLinearPowerDensityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLinearPowerDensityExtensions.g.cs @@ -32,279 +32,279 @@ namespace UnitsNet.NumberExtensions.NumberToLinearPowerDensity /// public static class NumberToLinearPowerDensityExtensions { - /// + /// public static LinearPowerDensity GigawattsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromGigawattsPerCentimeter(double.CreateChecked(value)); + => LinearPowerDensity.FromGigawattsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromGigawattsPerCentimeter(value.ToDouble(null)); + => LinearPowerDensity.FromGigawattsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity GigawattsPerFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromGigawattsPerFoot(double.CreateChecked(value)); + => LinearPowerDensity.FromGigawattsPerFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromGigawattsPerFoot(value.ToDouble(null)); + => LinearPowerDensity.FromGigawattsPerFoot(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity GigawattsPerInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromGigawattsPerInch(double.CreateChecked(value)); + => LinearPowerDensity.FromGigawattsPerInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromGigawattsPerInch(value.ToDouble(null)); + => LinearPowerDensity.FromGigawattsPerInch(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity GigawattsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromGigawattsPerMeter(double.CreateChecked(value)); + => LinearPowerDensity.FromGigawattsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromGigawattsPerMeter(value.ToDouble(null)); + => LinearPowerDensity.FromGigawattsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity GigawattsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromGigawattsPerMillimeter(double.CreateChecked(value)); + => LinearPowerDensity.FromGigawattsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromGigawattsPerMillimeter(value.ToDouble(null)); + => LinearPowerDensity.FromGigawattsPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity KilowattsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromKilowattsPerCentimeter(double.CreateChecked(value)); + => LinearPowerDensity.FromKilowattsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromKilowattsPerCentimeter(value.ToDouble(null)); + => LinearPowerDensity.FromKilowattsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity KilowattsPerFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromKilowattsPerFoot(double.CreateChecked(value)); + => LinearPowerDensity.FromKilowattsPerFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromKilowattsPerFoot(value.ToDouble(null)); + => LinearPowerDensity.FromKilowattsPerFoot(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity KilowattsPerInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromKilowattsPerInch(double.CreateChecked(value)); + => LinearPowerDensity.FromKilowattsPerInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromKilowattsPerInch(value.ToDouble(null)); + => LinearPowerDensity.FromKilowattsPerInch(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity KilowattsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromKilowattsPerMeter(double.CreateChecked(value)); + => LinearPowerDensity.FromKilowattsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromKilowattsPerMeter(value.ToDouble(null)); + => LinearPowerDensity.FromKilowattsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity KilowattsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromKilowattsPerMillimeter(double.CreateChecked(value)); + => LinearPowerDensity.FromKilowattsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromKilowattsPerMillimeter(value.ToDouble(null)); + => LinearPowerDensity.FromKilowattsPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity MegawattsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromMegawattsPerCentimeter(double.CreateChecked(value)); + => LinearPowerDensity.FromMegawattsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromMegawattsPerCentimeter(value.ToDouble(null)); + => LinearPowerDensity.FromMegawattsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity MegawattsPerFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromMegawattsPerFoot(double.CreateChecked(value)); + => LinearPowerDensity.FromMegawattsPerFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromMegawattsPerFoot(value.ToDouble(null)); + => LinearPowerDensity.FromMegawattsPerFoot(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity MegawattsPerInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromMegawattsPerInch(double.CreateChecked(value)); + => LinearPowerDensity.FromMegawattsPerInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromMegawattsPerInch(value.ToDouble(null)); + => LinearPowerDensity.FromMegawattsPerInch(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity MegawattsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromMegawattsPerMeter(double.CreateChecked(value)); + => LinearPowerDensity.FromMegawattsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromMegawattsPerMeter(value.ToDouble(null)); + => LinearPowerDensity.FromMegawattsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity MegawattsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromMegawattsPerMillimeter(double.CreateChecked(value)); + => LinearPowerDensity.FromMegawattsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromMegawattsPerMillimeter(value.ToDouble(null)); + => LinearPowerDensity.FromMegawattsPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity MilliwattsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromMilliwattsPerCentimeter(double.CreateChecked(value)); + => LinearPowerDensity.FromMilliwattsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromMilliwattsPerCentimeter(value.ToDouble(null)); + => LinearPowerDensity.FromMilliwattsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity MilliwattsPerFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromMilliwattsPerFoot(double.CreateChecked(value)); + => LinearPowerDensity.FromMilliwattsPerFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromMilliwattsPerFoot(value.ToDouble(null)); + => LinearPowerDensity.FromMilliwattsPerFoot(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity MilliwattsPerInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromMilliwattsPerInch(double.CreateChecked(value)); + => LinearPowerDensity.FromMilliwattsPerInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromMilliwattsPerInch(value.ToDouble(null)); + => LinearPowerDensity.FromMilliwattsPerInch(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity MilliwattsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromMilliwattsPerMeter(double.CreateChecked(value)); + => LinearPowerDensity.FromMilliwattsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromMilliwattsPerMeter(value.ToDouble(null)); + => LinearPowerDensity.FromMilliwattsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity MilliwattsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromMilliwattsPerMillimeter(double.CreateChecked(value)); + => LinearPowerDensity.FromMilliwattsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromMilliwattsPerMillimeter(value.ToDouble(null)); + => LinearPowerDensity.FromMilliwattsPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity WattsPerCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromWattsPerCentimeter(double.CreateChecked(value)); + => LinearPowerDensity.FromWattsPerCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromWattsPerCentimeter(value.ToDouble(null)); + => LinearPowerDensity.FromWattsPerCentimeter(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity WattsPerFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromWattsPerFoot(double.CreateChecked(value)); + => LinearPowerDensity.FromWattsPerFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromWattsPerFoot(value.ToDouble(null)); + => LinearPowerDensity.FromWattsPerFoot(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity WattsPerInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromWattsPerInch(double.CreateChecked(value)); + => LinearPowerDensity.FromWattsPerInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromWattsPerInch(value.ToDouble(null)); + => LinearPowerDensity.FromWattsPerInch(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity WattsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromWattsPerMeter(double.CreateChecked(value)); + => LinearPowerDensity.FromWattsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromWattsPerMeter(value.ToDouble(null)); + => LinearPowerDensity.FromWattsPerMeter(value.ToQuantityValue()); #endif - /// + /// public static LinearPowerDensity WattsPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LinearPowerDensity.FromWattsPerMillimeter(double.CreateChecked(value)); + => LinearPowerDensity.FromWattsPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => LinearPowerDensity.FromWattsPerMillimeter(value.ToDouble(null)); + => LinearPowerDensity.FromWattsPerMillimeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLuminanceExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLuminanceExtensions.g.cs index ef5a2a1453..1af6e8be91 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLuminanceExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLuminanceExtensions.g.cs @@ -32,114 +32,114 @@ namespace UnitsNet.NumberExtensions.NumberToLuminance /// public static class NumberToLuminanceExtensions { - /// + /// public static Luminance CandelasPerSquareFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminance.FromCandelasPerSquareFoot(double.CreateChecked(value)); + => Luminance.FromCandelasPerSquareFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminance.FromCandelasPerSquareFoot(value.ToDouble(null)); + => Luminance.FromCandelasPerSquareFoot(value.ToQuantityValue()); #endif - /// + /// public static Luminance CandelasPerSquareInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminance.FromCandelasPerSquareInch(double.CreateChecked(value)); + => Luminance.FromCandelasPerSquareInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminance.FromCandelasPerSquareInch(value.ToDouble(null)); + => Luminance.FromCandelasPerSquareInch(value.ToQuantityValue()); #endif - /// + /// public static Luminance CandelasPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminance.FromCandelasPerSquareMeter(double.CreateChecked(value)); + => Luminance.FromCandelasPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminance.FromCandelasPerSquareMeter(value.ToDouble(null)); + => Luminance.FromCandelasPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Luminance CenticandelasPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminance.FromCenticandelasPerSquareMeter(double.CreateChecked(value)); + => Luminance.FromCenticandelasPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminance.FromCenticandelasPerSquareMeter(value.ToDouble(null)); + => Luminance.FromCenticandelasPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Luminance DecicandelasPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminance.FromDecicandelasPerSquareMeter(double.CreateChecked(value)); + => Luminance.FromDecicandelasPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminance.FromDecicandelasPerSquareMeter(value.ToDouble(null)); + => Luminance.FromDecicandelasPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Luminance KilocandelasPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminance.FromKilocandelasPerSquareMeter(double.CreateChecked(value)); + => Luminance.FromKilocandelasPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminance.FromKilocandelasPerSquareMeter(value.ToDouble(null)); + => Luminance.FromKilocandelasPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Luminance MicrocandelasPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminance.FromMicrocandelasPerSquareMeter(double.CreateChecked(value)); + => Luminance.FromMicrocandelasPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminance.FromMicrocandelasPerSquareMeter(value.ToDouble(null)); + => Luminance.FromMicrocandelasPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Luminance MillicandelasPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminance.FromMillicandelasPerSquareMeter(double.CreateChecked(value)); + => Luminance.FromMillicandelasPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminance.FromMillicandelasPerSquareMeter(value.ToDouble(null)); + => Luminance.FromMillicandelasPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Luminance NanocandelasPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminance.FromNanocandelasPerSquareMeter(double.CreateChecked(value)); + => Luminance.FromNanocandelasPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminance.FromNanocandelasPerSquareMeter(value.ToDouble(null)); + => Luminance.FromNanocandelasPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Luminance Nits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminance.FromNits(double.CreateChecked(value)); + => Luminance.FromNits(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminance.FromNits(value.ToDouble(null)); + => Luminance.FromNits(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLuminosityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLuminosityExtensions.g.cs index d9c5901e1f..dd8111a618 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLuminosityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLuminosityExtensions.g.cs @@ -32,158 +32,158 @@ namespace UnitsNet.NumberExtensions.NumberToLuminosity /// public static class NumberToLuminosityExtensions { - /// + /// public static Luminosity Decawatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminosity.FromDecawatts(double.CreateChecked(value)); + => Luminosity.FromDecawatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminosity.FromDecawatts(value.ToDouble(null)); + => Luminosity.FromDecawatts(value.ToQuantityValue()); #endif - /// + /// public static Luminosity Deciwatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminosity.FromDeciwatts(double.CreateChecked(value)); + => Luminosity.FromDeciwatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminosity.FromDeciwatts(value.ToDouble(null)); + => Luminosity.FromDeciwatts(value.ToQuantityValue()); #endif - /// + /// public static Luminosity Femtowatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminosity.FromFemtowatts(double.CreateChecked(value)); + => Luminosity.FromFemtowatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminosity.FromFemtowatts(value.ToDouble(null)); + => Luminosity.FromFemtowatts(value.ToQuantityValue()); #endif - /// + /// public static Luminosity Gigawatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminosity.FromGigawatts(double.CreateChecked(value)); + => Luminosity.FromGigawatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminosity.FromGigawatts(value.ToDouble(null)); + => Luminosity.FromGigawatts(value.ToQuantityValue()); #endif - /// + /// public static Luminosity Kilowatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminosity.FromKilowatts(double.CreateChecked(value)); + => Luminosity.FromKilowatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminosity.FromKilowatts(value.ToDouble(null)); + => Luminosity.FromKilowatts(value.ToQuantityValue()); #endif - /// + /// public static Luminosity Megawatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminosity.FromMegawatts(double.CreateChecked(value)); + => Luminosity.FromMegawatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminosity.FromMegawatts(value.ToDouble(null)); + => Luminosity.FromMegawatts(value.ToQuantityValue()); #endif - /// + /// public static Luminosity Microwatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminosity.FromMicrowatts(double.CreateChecked(value)); + => Luminosity.FromMicrowatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminosity.FromMicrowatts(value.ToDouble(null)); + => Luminosity.FromMicrowatts(value.ToQuantityValue()); #endif - /// + /// public static Luminosity Milliwatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminosity.FromMilliwatts(double.CreateChecked(value)); + => Luminosity.FromMilliwatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminosity.FromMilliwatts(value.ToDouble(null)); + => Luminosity.FromMilliwatts(value.ToQuantityValue()); #endif - /// + /// public static Luminosity Nanowatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminosity.FromNanowatts(double.CreateChecked(value)); + => Luminosity.FromNanowatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminosity.FromNanowatts(value.ToDouble(null)); + => Luminosity.FromNanowatts(value.ToQuantityValue()); #endif - /// + /// public static Luminosity Petawatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminosity.FromPetawatts(double.CreateChecked(value)); + => Luminosity.FromPetawatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminosity.FromPetawatts(value.ToDouble(null)); + => Luminosity.FromPetawatts(value.ToQuantityValue()); #endif - /// + /// public static Luminosity Picowatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminosity.FromPicowatts(double.CreateChecked(value)); + => Luminosity.FromPicowatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminosity.FromPicowatts(value.ToDouble(null)); + => Luminosity.FromPicowatts(value.ToQuantityValue()); #endif - /// + /// public static Luminosity SolarLuminosities(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminosity.FromSolarLuminosities(double.CreateChecked(value)); + => Luminosity.FromSolarLuminosities(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminosity.FromSolarLuminosities(value.ToDouble(null)); + => Luminosity.FromSolarLuminosities(value.ToQuantityValue()); #endif - /// + /// public static Luminosity Terawatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminosity.FromTerawatts(double.CreateChecked(value)); + => Luminosity.FromTerawatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminosity.FromTerawatts(value.ToDouble(null)); + => Luminosity.FromTerawatts(value.ToQuantityValue()); #endif - /// + /// public static Luminosity Watts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Luminosity.FromWatts(double.CreateChecked(value)); + => Luminosity.FromWatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Luminosity.FromWatts(value.ToDouble(null)); + => Luminosity.FromWatts(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLuminousFluxExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLuminousFluxExtensions.g.cs index 77b32a6349..cc402384a7 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLuminousFluxExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLuminousFluxExtensions.g.cs @@ -32,15 +32,15 @@ namespace UnitsNet.NumberExtensions.NumberToLuminousFlux /// public static class NumberToLuminousFluxExtensions { - /// + /// public static LuminousFlux Lumens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LuminousFlux.FromLumens(double.CreateChecked(value)); + => LuminousFlux.FromLumens(QuantityValue.CreateChecked(value)); #else , IConvertible - => LuminousFlux.FromLumens(value.ToDouble(null)); + => LuminousFlux.FromLumens(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLuminousIntensityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLuminousIntensityExtensions.g.cs index 0f7022e11f..1ca22a12dd 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToLuminousIntensityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToLuminousIntensityExtensions.g.cs @@ -32,15 +32,15 @@ namespace UnitsNet.NumberExtensions.NumberToLuminousIntensity /// public static class NumberToLuminousIntensityExtensions { - /// + /// public static LuminousIntensity Candela(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => LuminousIntensity.FromCandela(double.CreateChecked(value)); + => LuminousIntensity.FromCandela(QuantityValue.CreateChecked(value)); #else , IConvertible - => LuminousIntensity.FromCandela(value.ToDouble(null)); + => LuminousIntensity.FromCandela(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMagneticFieldExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMagneticFieldExtensions.g.cs index 7df946205f..7394148f9a 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMagneticFieldExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMagneticFieldExtensions.g.cs @@ -32,70 +32,70 @@ namespace UnitsNet.NumberExtensions.NumberToMagneticField /// public static class NumberToMagneticFieldExtensions { - /// + /// public static MagneticField Gausses(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MagneticField.FromGausses(double.CreateChecked(value)); + => MagneticField.FromGausses(QuantityValue.CreateChecked(value)); #else , IConvertible - => MagneticField.FromGausses(value.ToDouble(null)); + => MagneticField.FromGausses(value.ToQuantityValue()); #endif - /// + /// public static MagneticField Microteslas(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MagneticField.FromMicroteslas(double.CreateChecked(value)); + => MagneticField.FromMicroteslas(QuantityValue.CreateChecked(value)); #else , IConvertible - => MagneticField.FromMicroteslas(value.ToDouble(null)); + => MagneticField.FromMicroteslas(value.ToQuantityValue()); #endif - /// + /// public static MagneticField Milligausses(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MagneticField.FromMilligausses(double.CreateChecked(value)); + => MagneticField.FromMilligausses(QuantityValue.CreateChecked(value)); #else , IConvertible - => MagneticField.FromMilligausses(value.ToDouble(null)); + => MagneticField.FromMilligausses(value.ToQuantityValue()); #endif - /// + /// public static MagneticField Milliteslas(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MagneticField.FromMilliteslas(double.CreateChecked(value)); + => MagneticField.FromMilliteslas(QuantityValue.CreateChecked(value)); #else , IConvertible - => MagneticField.FromMilliteslas(value.ToDouble(null)); + => MagneticField.FromMilliteslas(value.ToQuantityValue()); #endif - /// + /// public static MagneticField Nanoteslas(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MagneticField.FromNanoteslas(double.CreateChecked(value)); + => MagneticField.FromNanoteslas(QuantityValue.CreateChecked(value)); #else , IConvertible - => MagneticField.FromNanoteslas(value.ToDouble(null)); + => MagneticField.FromNanoteslas(value.ToQuantityValue()); #endif - /// + /// public static MagneticField Teslas(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MagneticField.FromTeslas(double.CreateChecked(value)); + => MagneticField.FromTeslas(QuantityValue.CreateChecked(value)); #else , IConvertible - => MagneticField.FromTeslas(value.ToDouble(null)); + => MagneticField.FromTeslas(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMagneticFluxExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMagneticFluxExtensions.g.cs index 6d96430872..473c0f26c3 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMagneticFluxExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMagneticFluxExtensions.g.cs @@ -32,15 +32,15 @@ namespace UnitsNet.NumberExtensions.NumberToMagneticFlux /// public static class NumberToMagneticFluxExtensions { - /// + /// public static MagneticFlux Webers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MagneticFlux.FromWebers(double.CreateChecked(value)); + => MagneticFlux.FromWebers(QuantityValue.CreateChecked(value)); #else , IConvertible - => MagneticFlux.FromWebers(value.ToDouble(null)); + => MagneticFlux.FromWebers(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMagnetizationExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMagnetizationExtensions.g.cs index 663b43fd9b..fac03116da 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMagnetizationExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMagnetizationExtensions.g.cs @@ -32,15 +32,15 @@ namespace UnitsNet.NumberExtensions.NumberToMagnetization /// public static class NumberToMagnetizationExtensions { - /// + /// public static Magnetization AmperesPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Magnetization.FromAmperesPerMeter(double.CreateChecked(value)); + => Magnetization.FromAmperesPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Magnetization.FromAmperesPerMeter(value.ToDouble(null)); + => Magnetization.FromAmperesPerMeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassConcentrationExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassConcentrationExtensions.g.cs index f1e991a534..22861dedf2 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassConcentrationExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassConcentrationExtensions.g.cs @@ -32,543 +32,543 @@ namespace UnitsNet.NumberExtensions.NumberToMassConcentration /// public static class NumberToMassConcentrationExtensions { - /// + /// public static MassConcentration CentigramsPerDeciliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromCentigramsPerDeciliter(double.CreateChecked(value)); + => MassConcentration.FromCentigramsPerDeciliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromCentigramsPerDeciliter(value.ToDouble(null)); + => MassConcentration.FromCentigramsPerDeciliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration CentigramsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromCentigramsPerLiter(double.CreateChecked(value)); + => MassConcentration.FromCentigramsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromCentigramsPerLiter(value.ToDouble(null)); + => MassConcentration.FromCentigramsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration CentigramsPerMicroliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromCentigramsPerMicroliter(double.CreateChecked(value)); + => MassConcentration.FromCentigramsPerMicroliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromCentigramsPerMicroliter(value.ToDouble(null)); + => MassConcentration.FromCentigramsPerMicroliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration CentigramsPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromCentigramsPerMilliliter(double.CreateChecked(value)); + => MassConcentration.FromCentigramsPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromCentigramsPerMilliliter(value.ToDouble(null)); + => MassConcentration.FromCentigramsPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration DecigramsPerDeciliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromDecigramsPerDeciliter(double.CreateChecked(value)); + => MassConcentration.FromDecigramsPerDeciliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromDecigramsPerDeciliter(value.ToDouble(null)); + => MassConcentration.FromDecigramsPerDeciliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration DecigramsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromDecigramsPerLiter(double.CreateChecked(value)); + => MassConcentration.FromDecigramsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromDecigramsPerLiter(value.ToDouble(null)); + => MassConcentration.FromDecigramsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration DecigramsPerMicroliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromDecigramsPerMicroliter(double.CreateChecked(value)); + => MassConcentration.FromDecigramsPerMicroliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromDecigramsPerMicroliter(value.ToDouble(null)); + => MassConcentration.FromDecigramsPerMicroliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration DecigramsPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromDecigramsPerMilliliter(double.CreateChecked(value)); + => MassConcentration.FromDecigramsPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromDecigramsPerMilliliter(value.ToDouble(null)); + => MassConcentration.FromDecigramsPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration GramsPerCubicCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromGramsPerCubicCentimeter(double.CreateChecked(value)); + => MassConcentration.FromGramsPerCubicCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromGramsPerCubicCentimeter(value.ToDouble(null)); + => MassConcentration.FromGramsPerCubicCentimeter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration GramsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromGramsPerCubicMeter(double.CreateChecked(value)); + => MassConcentration.FromGramsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromGramsPerCubicMeter(value.ToDouble(null)); + => MassConcentration.FromGramsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration GramsPerCubicMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromGramsPerCubicMillimeter(double.CreateChecked(value)); + => MassConcentration.FromGramsPerCubicMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromGramsPerCubicMillimeter(value.ToDouble(null)); + => MassConcentration.FromGramsPerCubicMillimeter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration GramsPerDeciliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromGramsPerDeciliter(double.CreateChecked(value)); + => MassConcentration.FromGramsPerDeciliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromGramsPerDeciliter(value.ToDouble(null)); + => MassConcentration.FromGramsPerDeciliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration GramsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromGramsPerLiter(double.CreateChecked(value)); + => MassConcentration.FromGramsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromGramsPerLiter(value.ToDouble(null)); + => MassConcentration.FromGramsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration GramsPerMicroliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromGramsPerMicroliter(double.CreateChecked(value)); + => MassConcentration.FromGramsPerMicroliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromGramsPerMicroliter(value.ToDouble(null)); + => MassConcentration.FromGramsPerMicroliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration GramsPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromGramsPerMilliliter(double.CreateChecked(value)); + => MassConcentration.FromGramsPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromGramsPerMilliliter(value.ToDouble(null)); + => MassConcentration.FromGramsPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration KilogramsPerCubicCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromKilogramsPerCubicCentimeter(double.CreateChecked(value)); + => MassConcentration.FromKilogramsPerCubicCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromKilogramsPerCubicCentimeter(value.ToDouble(null)); + => MassConcentration.FromKilogramsPerCubicCentimeter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration KilogramsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromKilogramsPerCubicMeter(double.CreateChecked(value)); + => MassConcentration.FromKilogramsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromKilogramsPerCubicMeter(value.ToDouble(null)); + => MassConcentration.FromKilogramsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration KilogramsPerCubicMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromKilogramsPerCubicMillimeter(double.CreateChecked(value)); + => MassConcentration.FromKilogramsPerCubicMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromKilogramsPerCubicMillimeter(value.ToDouble(null)); + => MassConcentration.FromKilogramsPerCubicMillimeter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration KilogramsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromKilogramsPerLiter(double.CreateChecked(value)); + => MassConcentration.FromKilogramsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromKilogramsPerLiter(value.ToDouble(null)); + => MassConcentration.FromKilogramsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration KilopoundsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromKilopoundsPerCubicFoot(double.CreateChecked(value)); + => MassConcentration.FromKilopoundsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromKilopoundsPerCubicFoot(value.ToDouble(null)); + => MassConcentration.FromKilopoundsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration KilopoundsPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromKilopoundsPerCubicInch(double.CreateChecked(value)); + => MassConcentration.FromKilopoundsPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromKilopoundsPerCubicInch(value.ToDouble(null)); + => MassConcentration.FromKilopoundsPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration MicrogramsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromMicrogramsPerCubicMeter(double.CreateChecked(value)); + => MassConcentration.FromMicrogramsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromMicrogramsPerCubicMeter(value.ToDouble(null)); + => MassConcentration.FromMicrogramsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration MicrogramsPerDeciliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromMicrogramsPerDeciliter(double.CreateChecked(value)); + => MassConcentration.FromMicrogramsPerDeciliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromMicrogramsPerDeciliter(value.ToDouble(null)); + => MassConcentration.FromMicrogramsPerDeciliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration MicrogramsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromMicrogramsPerLiter(double.CreateChecked(value)); + => MassConcentration.FromMicrogramsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromMicrogramsPerLiter(value.ToDouble(null)); + => MassConcentration.FromMicrogramsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration MicrogramsPerMicroliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromMicrogramsPerMicroliter(double.CreateChecked(value)); + => MassConcentration.FromMicrogramsPerMicroliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromMicrogramsPerMicroliter(value.ToDouble(null)); + => MassConcentration.FromMicrogramsPerMicroliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration MicrogramsPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromMicrogramsPerMilliliter(double.CreateChecked(value)); + => MassConcentration.FromMicrogramsPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromMicrogramsPerMilliliter(value.ToDouble(null)); + => MassConcentration.FromMicrogramsPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration MilligramsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromMilligramsPerCubicMeter(double.CreateChecked(value)); + => MassConcentration.FromMilligramsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromMilligramsPerCubicMeter(value.ToDouble(null)); + => MassConcentration.FromMilligramsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration MilligramsPerDeciliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromMilligramsPerDeciliter(double.CreateChecked(value)); + => MassConcentration.FromMilligramsPerDeciliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromMilligramsPerDeciliter(value.ToDouble(null)); + => MassConcentration.FromMilligramsPerDeciliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration MilligramsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromMilligramsPerLiter(double.CreateChecked(value)); + => MassConcentration.FromMilligramsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromMilligramsPerLiter(value.ToDouble(null)); + => MassConcentration.FromMilligramsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration MilligramsPerMicroliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromMilligramsPerMicroliter(double.CreateChecked(value)); + => MassConcentration.FromMilligramsPerMicroliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromMilligramsPerMicroliter(value.ToDouble(null)); + => MassConcentration.FromMilligramsPerMicroliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration MilligramsPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromMilligramsPerMilliliter(double.CreateChecked(value)); + => MassConcentration.FromMilligramsPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromMilligramsPerMilliliter(value.ToDouble(null)); + => MassConcentration.FromMilligramsPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration NanogramsPerDeciliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromNanogramsPerDeciliter(double.CreateChecked(value)); + => MassConcentration.FromNanogramsPerDeciliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromNanogramsPerDeciliter(value.ToDouble(null)); + => MassConcentration.FromNanogramsPerDeciliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration NanogramsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromNanogramsPerLiter(double.CreateChecked(value)); + => MassConcentration.FromNanogramsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromNanogramsPerLiter(value.ToDouble(null)); + => MassConcentration.FromNanogramsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration NanogramsPerMicroliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromNanogramsPerMicroliter(double.CreateChecked(value)); + => MassConcentration.FromNanogramsPerMicroliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromNanogramsPerMicroliter(value.ToDouble(null)); + => MassConcentration.FromNanogramsPerMicroliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration NanogramsPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromNanogramsPerMilliliter(double.CreateChecked(value)); + => MassConcentration.FromNanogramsPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromNanogramsPerMilliliter(value.ToDouble(null)); + => MassConcentration.FromNanogramsPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration OuncesPerImperialGallon(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromOuncesPerImperialGallon(double.CreateChecked(value)); + => MassConcentration.FromOuncesPerImperialGallon(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromOuncesPerImperialGallon(value.ToDouble(null)); + => MassConcentration.FromOuncesPerImperialGallon(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration OuncesPerUSGallon(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromOuncesPerUSGallon(double.CreateChecked(value)); + => MassConcentration.FromOuncesPerUSGallon(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromOuncesPerUSGallon(value.ToDouble(null)); + => MassConcentration.FromOuncesPerUSGallon(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration PicogramsPerDeciliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromPicogramsPerDeciliter(double.CreateChecked(value)); + => MassConcentration.FromPicogramsPerDeciliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromPicogramsPerDeciliter(value.ToDouble(null)); + => MassConcentration.FromPicogramsPerDeciliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration PicogramsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromPicogramsPerLiter(double.CreateChecked(value)); + => MassConcentration.FromPicogramsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromPicogramsPerLiter(value.ToDouble(null)); + => MassConcentration.FromPicogramsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration PicogramsPerMicroliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromPicogramsPerMicroliter(double.CreateChecked(value)); + => MassConcentration.FromPicogramsPerMicroliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromPicogramsPerMicroliter(value.ToDouble(null)); + => MassConcentration.FromPicogramsPerMicroliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration PicogramsPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromPicogramsPerMilliliter(double.CreateChecked(value)); + => MassConcentration.FromPicogramsPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromPicogramsPerMilliliter(value.ToDouble(null)); + => MassConcentration.FromPicogramsPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration PoundsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromPoundsPerCubicFoot(double.CreateChecked(value)); + => MassConcentration.FromPoundsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromPoundsPerCubicFoot(value.ToDouble(null)); + => MassConcentration.FromPoundsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration PoundsPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromPoundsPerCubicInch(double.CreateChecked(value)); + => MassConcentration.FromPoundsPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromPoundsPerCubicInch(value.ToDouble(null)); + => MassConcentration.FromPoundsPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration PoundsPerImperialGallon(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromPoundsPerImperialGallon(double.CreateChecked(value)); + => MassConcentration.FromPoundsPerImperialGallon(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromPoundsPerImperialGallon(value.ToDouble(null)); + => MassConcentration.FromPoundsPerImperialGallon(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration PoundsPerUSGallon(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromPoundsPerUSGallon(double.CreateChecked(value)); + => MassConcentration.FromPoundsPerUSGallon(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromPoundsPerUSGallon(value.ToDouble(null)); + => MassConcentration.FromPoundsPerUSGallon(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration SlugsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromSlugsPerCubicFoot(double.CreateChecked(value)); + => MassConcentration.FromSlugsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromSlugsPerCubicFoot(value.ToDouble(null)); + => MassConcentration.FromSlugsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration TonnesPerCubicCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromTonnesPerCubicCentimeter(double.CreateChecked(value)); + => MassConcentration.FromTonnesPerCubicCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromTonnesPerCubicCentimeter(value.ToDouble(null)); + => MassConcentration.FromTonnesPerCubicCentimeter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration TonnesPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromTonnesPerCubicMeter(double.CreateChecked(value)); + => MassConcentration.FromTonnesPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromTonnesPerCubicMeter(value.ToDouble(null)); + => MassConcentration.FromTonnesPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static MassConcentration TonnesPerCubicMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassConcentration.FromTonnesPerCubicMillimeter(double.CreateChecked(value)); + => MassConcentration.FromTonnesPerCubicMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassConcentration.FromTonnesPerCubicMillimeter(value.ToDouble(null)); + => MassConcentration.FromTonnesPerCubicMillimeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassExtensions.g.cs index ea55f84c4d..02bb37e626 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassExtensions.g.cs @@ -32,301 +32,301 @@ namespace UnitsNet.NumberExtensions.NumberToMass /// public static class NumberToMassExtensions { - /// + /// public static Mass Centigrams(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromCentigrams(double.CreateChecked(value)); + => Mass.FromCentigrams(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromCentigrams(value.ToDouble(null)); + => Mass.FromCentigrams(value.ToQuantityValue()); #endif - /// + /// public static Mass Decagrams(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromDecagrams(double.CreateChecked(value)); + => Mass.FromDecagrams(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromDecagrams(value.ToDouble(null)); + => Mass.FromDecagrams(value.ToQuantityValue()); #endif - /// + /// public static Mass Decigrams(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromDecigrams(double.CreateChecked(value)); + => Mass.FromDecigrams(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromDecigrams(value.ToDouble(null)); + => Mass.FromDecigrams(value.ToQuantityValue()); #endif - /// + /// public static Mass EarthMasses(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromEarthMasses(double.CreateChecked(value)); + => Mass.FromEarthMasses(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromEarthMasses(value.ToDouble(null)); + => Mass.FromEarthMasses(value.ToQuantityValue()); #endif - /// + /// public static Mass Femtograms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromFemtograms(double.CreateChecked(value)); + => Mass.FromFemtograms(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromFemtograms(value.ToDouble(null)); + => Mass.FromFemtograms(value.ToQuantityValue()); #endif - /// + /// public static Mass Grains(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromGrains(double.CreateChecked(value)); + => Mass.FromGrains(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromGrains(value.ToDouble(null)); + => Mass.FromGrains(value.ToQuantityValue()); #endif - /// + /// public static Mass Grams(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromGrams(double.CreateChecked(value)); + => Mass.FromGrams(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromGrams(value.ToDouble(null)); + => Mass.FromGrams(value.ToQuantityValue()); #endif - /// + /// public static Mass Hectograms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromHectograms(double.CreateChecked(value)); + => Mass.FromHectograms(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromHectograms(value.ToDouble(null)); + => Mass.FromHectograms(value.ToQuantityValue()); #endif - /// + /// public static Mass Kilograms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromKilograms(double.CreateChecked(value)); + => Mass.FromKilograms(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromKilograms(value.ToDouble(null)); + => Mass.FromKilograms(value.ToQuantityValue()); #endif - /// + /// public static Mass Kilopounds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromKilopounds(double.CreateChecked(value)); + => Mass.FromKilopounds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromKilopounds(value.ToDouble(null)); + => Mass.FromKilopounds(value.ToQuantityValue()); #endif - /// + /// public static Mass Kilotonnes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromKilotonnes(double.CreateChecked(value)); + => Mass.FromKilotonnes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromKilotonnes(value.ToDouble(null)); + => Mass.FromKilotonnes(value.ToQuantityValue()); #endif - /// + /// public static Mass LongHundredweight(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromLongHundredweight(double.CreateChecked(value)); + => Mass.FromLongHundredweight(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromLongHundredweight(value.ToDouble(null)); + => Mass.FromLongHundredweight(value.ToQuantityValue()); #endif - /// + /// public static Mass LongTons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromLongTons(double.CreateChecked(value)); + => Mass.FromLongTons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromLongTons(value.ToDouble(null)); + => Mass.FromLongTons(value.ToQuantityValue()); #endif - /// + /// public static Mass Megapounds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromMegapounds(double.CreateChecked(value)); + => Mass.FromMegapounds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromMegapounds(value.ToDouble(null)); + => Mass.FromMegapounds(value.ToQuantityValue()); #endif - /// + /// public static Mass Megatonnes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromMegatonnes(double.CreateChecked(value)); + => Mass.FromMegatonnes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromMegatonnes(value.ToDouble(null)); + => Mass.FromMegatonnes(value.ToQuantityValue()); #endif - /// + /// public static Mass Micrograms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromMicrograms(double.CreateChecked(value)); + => Mass.FromMicrograms(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromMicrograms(value.ToDouble(null)); + => Mass.FromMicrograms(value.ToQuantityValue()); #endif - /// + /// public static Mass Milligrams(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromMilligrams(double.CreateChecked(value)); + => Mass.FromMilligrams(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromMilligrams(value.ToDouble(null)); + => Mass.FromMilligrams(value.ToQuantityValue()); #endif - /// + /// public static Mass Nanograms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromNanograms(double.CreateChecked(value)); + => Mass.FromNanograms(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromNanograms(value.ToDouble(null)); + => Mass.FromNanograms(value.ToQuantityValue()); #endif - /// + /// public static Mass Ounces(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromOunces(double.CreateChecked(value)); + => Mass.FromOunces(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromOunces(value.ToDouble(null)); + => Mass.FromOunces(value.ToQuantityValue()); #endif - /// + /// public static Mass Picograms(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromPicograms(double.CreateChecked(value)); + => Mass.FromPicograms(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromPicograms(value.ToDouble(null)); + => Mass.FromPicograms(value.ToQuantityValue()); #endif - /// + /// public static Mass Pounds(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromPounds(double.CreateChecked(value)); + => Mass.FromPounds(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromPounds(value.ToDouble(null)); + => Mass.FromPounds(value.ToQuantityValue()); #endif - /// + /// public static Mass ShortHundredweight(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromShortHundredweight(double.CreateChecked(value)); + => Mass.FromShortHundredweight(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromShortHundredweight(value.ToDouble(null)); + => Mass.FromShortHundredweight(value.ToQuantityValue()); #endif - /// + /// public static Mass ShortTons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromShortTons(double.CreateChecked(value)); + => Mass.FromShortTons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromShortTons(value.ToDouble(null)); + => Mass.FromShortTons(value.ToQuantityValue()); #endif - /// + /// public static Mass Slugs(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromSlugs(double.CreateChecked(value)); + => Mass.FromSlugs(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromSlugs(value.ToDouble(null)); + => Mass.FromSlugs(value.ToQuantityValue()); #endif - /// + /// public static Mass SolarMasses(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromSolarMasses(double.CreateChecked(value)); + => Mass.FromSolarMasses(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromSolarMasses(value.ToDouble(null)); + => Mass.FromSolarMasses(value.ToQuantityValue()); #endif - /// + /// public static Mass Stone(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromStone(double.CreateChecked(value)); + => Mass.FromStone(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromStone(value.ToDouble(null)); + => Mass.FromStone(value.ToQuantityValue()); #endif - /// + /// public static Mass Tonnes(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Mass.FromTonnes(double.CreateChecked(value)); + => Mass.FromTonnes(QuantityValue.CreateChecked(value)); #else , IConvertible - => Mass.FromTonnes(value.ToDouble(null)); + => Mass.FromTonnes(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassFlowExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassFlowExtensions.g.cs index 487d0f3e19..9b0577191b 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassFlowExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassFlowExtensions.g.cs @@ -32,367 +32,367 @@ namespace UnitsNet.NumberExtensions.NumberToMassFlow /// public static class NumberToMassFlowExtensions { - /// + /// public static MassFlow CentigramsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromCentigramsPerDay(double.CreateChecked(value)); + => MassFlow.FromCentigramsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromCentigramsPerDay(value.ToDouble(null)); + => MassFlow.FromCentigramsPerDay(value.ToQuantityValue()); #endif - /// + /// public static MassFlow CentigramsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromCentigramsPerSecond(double.CreateChecked(value)); + => MassFlow.FromCentigramsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromCentigramsPerSecond(value.ToDouble(null)); + => MassFlow.FromCentigramsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static MassFlow DecagramsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromDecagramsPerDay(double.CreateChecked(value)); + => MassFlow.FromDecagramsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromDecagramsPerDay(value.ToDouble(null)); + => MassFlow.FromDecagramsPerDay(value.ToQuantityValue()); #endif - /// + /// public static MassFlow DecagramsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromDecagramsPerSecond(double.CreateChecked(value)); + => MassFlow.FromDecagramsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromDecagramsPerSecond(value.ToDouble(null)); + => MassFlow.FromDecagramsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static MassFlow DecigramsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromDecigramsPerDay(double.CreateChecked(value)); + => MassFlow.FromDecigramsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromDecigramsPerDay(value.ToDouble(null)); + => MassFlow.FromDecigramsPerDay(value.ToQuantityValue()); #endif - /// + /// public static MassFlow DecigramsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromDecigramsPerSecond(double.CreateChecked(value)); + => MassFlow.FromDecigramsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromDecigramsPerSecond(value.ToDouble(null)); + => MassFlow.FromDecigramsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static MassFlow GramsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromGramsPerDay(double.CreateChecked(value)); + => MassFlow.FromGramsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromGramsPerDay(value.ToDouble(null)); + => MassFlow.FromGramsPerDay(value.ToQuantityValue()); #endif - /// + /// public static MassFlow GramsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromGramsPerHour(double.CreateChecked(value)); + => MassFlow.FromGramsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromGramsPerHour(value.ToDouble(null)); + => MassFlow.FromGramsPerHour(value.ToQuantityValue()); #endif - /// + /// public static MassFlow GramsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromGramsPerSecond(double.CreateChecked(value)); + => MassFlow.FromGramsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromGramsPerSecond(value.ToDouble(null)); + => MassFlow.FromGramsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static MassFlow HectogramsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromHectogramsPerDay(double.CreateChecked(value)); + => MassFlow.FromHectogramsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromHectogramsPerDay(value.ToDouble(null)); + => MassFlow.FromHectogramsPerDay(value.ToQuantityValue()); #endif - /// + /// public static MassFlow HectogramsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromHectogramsPerSecond(double.CreateChecked(value)); + => MassFlow.FromHectogramsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromHectogramsPerSecond(value.ToDouble(null)); + => MassFlow.FromHectogramsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static MassFlow KilogramsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromKilogramsPerDay(double.CreateChecked(value)); + => MassFlow.FromKilogramsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromKilogramsPerDay(value.ToDouble(null)); + => MassFlow.FromKilogramsPerDay(value.ToQuantityValue()); #endif - /// + /// public static MassFlow KilogramsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromKilogramsPerHour(double.CreateChecked(value)); + => MassFlow.FromKilogramsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromKilogramsPerHour(value.ToDouble(null)); + => MassFlow.FromKilogramsPerHour(value.ToQuantityValue()); #endif - /// + /// public static MassFlow KilogramsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromKilogramsPerMinute(double.CreateChecked(value)); + => MassFlow.FromKilogramsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromKilogramsPerMinute(value.ToDouble(null)); + => MassFlow.FromKilogramsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static MassFlow KilogramsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromKilogramsPerSecond(double.CreateChecked(value)); + => MassFlow.FromKilogramsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromKilogramsPerSecond(value.ToDouble(null)); + => MassFlow.FromKilogramsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static MassFlow MegagramsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromMegagramsPerDay(double.CreateChecked(value)); + => MassFlow.FromMegagramsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromMegagramsPerDay(value.ToDouble(null)); + => MassFlow.FromMegagramsPerDay(value.ToQuantityValue()); #endif - /// + /// public static MassFlow MegapoundsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromMegapoundsPerDay(double.CreateChecked(value)); + => MassFlow.FromMegapoundsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromMegapoundsPerDay(value.ToDouble(null)); + => MassFlow.FromMegapoundsPerDay(value.ToQuantityValue()); #endif - /// + /// public static MassFlow MegapoundsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromMegapoundsPerHour(double.CreateChecked(value)); + => MassFlow.FromMegapoundsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromMegapoundsPerHour(value.ToDouble(null)); + => MassFlow.FromMegapoundsPerHour(value.ToQuantityValue()); #endif - /// + /// public static MassFlow MegapoundsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromMegapoundsPerMinute(double.CreateChecked(value)); + => MassFlow.FromMegapoundsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromMegapoundsPerMinute(value.ToDouble(null)); + => MassFlow.FromMegapoundsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static MassFlow MegapoundsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromMegapoundsPerSecond(double.CreateChecked(value)); + => MassFlow.FromMegapoundsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromMegapoundsPerSecond(value.ToDouble(null)); + => MassFlow.FromMegapoundsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static MassFlow MicrogramsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromMicrogramsPerDay(double.CreateChecked(value)); + => MassFlow.FromMicrogramsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromMicrogramsPerDay(value.ToDouble(null)); + => MassFlow.FromMicrogramsPerDay(value.ToQuantityValue()); #endif - /// + /// public static MassFlow MicrogramsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromMicrogramsPerSecond(double.CreateChecked(value)); + => MassFlow.FromMicrogramsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromMicrogramsPerSecond(value.ToDouble(null)); + => MassFlow.FromMicrogramsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static MassFlow MilligramsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromMilligramsPerDay(double.CreateChecked(value)); + => MassFlow.FromMilligramsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromMilligramsPerDay(value.ToDouble(null)); + => MassFlow.FromMilligramsPerDay(value.ToQuantityValue()); #endif - /// + /// public static MassFlow MilligramsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromMilligramsPerSecond(double.CreateChecked(value)); + => MassFlow.FromMilligramsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromMilligramsPerSecond(value.ToDouble(null)); + => MassFlow.FromMilligramsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static MassFlow NanogramsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromNanogramsPerDay(double.CreateChecked(value)); + => MassFlow.FromNanogramsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromNanogramsPerDay(value.ToDouble(null)); + => MassFlow.FromNanogramsPerDay(value.ToQuantityValue()); #endif - /// + /// public static MassFlow NanogramsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromNanogramsPerSecond(double.CreateChecked(value)); + => MassFlow.FromNanogramsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromNanogramsPerSecond(value.ToDouble(null)); + => MassFlow.FromNanogramsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static MassFlow PoundsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromPoundsPerDay(double.CreateChecked(value)); + => MassFlow.FromPoundsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromPoundsPerDay(value.ToDouble(null)); + => MassFlow.FromPoundsPerDay(value.ToQuantityValue()); #endif - /// + /// public static MassFlow PoundsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromPoundsPerHour(double.CreateChecked(value)); + => MassFlow.FromPoundsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromPoundsPerHour(value.ToDouble(null)); + => MassFlow.FromPoundsPerHour(value.ToQuantityValue()); #endif - /// + /// public static MassFlow PoundsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromPoundsPerMinute(double.CreateChecked(value)); + => MassFlow.FromPoundsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromPoundsPerMinute(value.ToDouble(null)); + => MassFlow.FromPoundsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static MassFlow PoundsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromPoundsPerSecond(double.CreateChecked(value)); + => MassFlow.FromPoundsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromPoundsPerSecond(value.ToDouble(null)); + => MassFlow.FromPoundsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static MassFlow ShortTonsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromShortTonsPerHour(double.CreateChecked(value)); + => MassFlow.FromShortTonsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromShortTonsPerHour(value.ToDouble(null)); + => MassFlow.FromShortTonsPerHour(value.ToQuantityValue()); #endif - /// + /// public static MassFlow TonnesPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromTonnesPerDay(double.CreateChecked(value)); + => MassFlow.FromTonnesPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromTonnesPerDay(value.ToDouble(null)); + => MassFlow.FromTonnesPerDay(value.ToQuantityValue()); #endif - /// + /// public static MassFlow TonnesPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlow.FromTonnesPerHour(double.CreateChecked(value)); + => MassFlow.FromTonnesPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlow.FromTonnesPerHour(value.ToDouble(null)); + => MassFlow.FromTonnesPerHour(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassFluxExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassFluxExtensions.g.cs index 486934bfba..9df2392291 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassFluxExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassFluxExtensions.g.cs @@ -32,136 +32,136 @@ namespace UnitsNet.NumberExtensions.NumberToMassFlux /// public static class NumberToMassFluxExtensions { - /// + /// public static MassFlux GramsPerHourPerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlux.FromGramsPerHourPerSquareCentimeter(double.CreateChecked(value)); + => MassFlux.FromGramsPerHourPerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlux.FromGramsPerHourPerSquareCentimeter(value.ToDouble(null)); + => MassFlux.FromGramsPerHourPerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static MassFlux GramsPerHourPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlux.FromGramsPerHourPerSquareMeter(double.CreateChecked(value)); + => MassFlux.FromGramsPerHourPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlux.FromGramsPerHourPerSquareMeter(value.ToDouble(null)); + => MassFlux.FromGramsPerHourPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static MassFlux GramsPerHourPerSquareMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlux.FromGramsPerHourPerSquareMillimeter(double.CreateChecked(value)); + => MassFlux.FromGramsPerHourPerSquareMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlux.FromGramsPerHourPerSquareMillimeter(value.ToDouble(null)); + => MassFlux.FromGramsPerHourPerSquareMillimeter(value.ToQuantityValue()); #endif - /// + /// public static MassFlux GramsPerSecondPerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlux.FromGramsPerSecondPerSquareCentimeter(double.CreateChecked(value)); + => MassFlux.FromGramsPerSecondPerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlux.FromGramsPerSecondPerSquareCentimeter(value.ToDouble(null)); + => MassFlux.FromGramsPerSecondPerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static MassFlux GramsPerSecondPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlux.FromGramsPerSecondPerSquareMeter(double.CreateChecked(value)); + => MassFlux.FromGramsPerSecondPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlux.FromGramsPerSecondPerSquareMeter(value.ToDouble(null)); + => MassFlux.FromGramsPerSecondPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static MassFlux GramsPerSecondPerSquareMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlux.FromGramsPerSecondPerSquareMillimeter(double.CreateChecked(value)); + => MassFlux.FromGramsPerSecondPerSquareMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlux.FromGramsPerSecondPerSquareMillimeter(value.ToDouble(null)); + => MassFlux.FromGramsPerSecondPerSquareMillimeter(value.ToQuantityValue()); #endif - /// + /// public static MassFlux KilogramsPerHourPerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlux.FromKilogramsPerHourPerSquareCentimeter(double.CreateChecked(value)); + => MassFlux.FromKilogramsPerHourPerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlux.FromKilogramsPerHourPerSquareCentimeter(value.ToDouble(null)); + => MassFlux.FromKilogramsPerHourPerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static MassFlux KilogramsPerHourPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlux.FromKilogramsPerHourPerSquareMeter(double.CreateChecked(value)); + => MassFlux.FromKilogramsPerHourPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlux.FromKilogramsPerHourPerSquareMeter(value.ToDouble(null)); + => MassFlux.FromKilogramsPerHourPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static MassFlux KilogramsPerHourPerSquareMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlux.FromKilogramsPerHourPerSquareMillimeter(double.CreateChecked(value)); + => MassFlux.FromKilogramsPerHourPerSquareMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlux.FromKilogramsPerHourPerSquareMillimeter(value.ToDouble(null)); + => MassFlux.FromKilogramsPerHourPerSquareMillimeter(value.ToQuantityValue()); #endif - /// + /// public static MassFlux KilogramsPerSecondPerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlux.FromKilogramsPerSecondPerSquareCentimeter(double.CreateChecked(value)); + => MassFlux.FromKilogramsPerSecondPerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlux.FromKilogramsPerSecondPerSquareCentimeter(value.ToDouble(null)); + => MassFlux.FromKilogramsPerSecondPerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static MassFlux KilogramsPerSecondPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlux.FromKilogramsPerSecondPerSquareMeter(double.CreateChecked(value)); + => MassFlux.FromKilogramsPerSecondPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlux.FromKilogramsPerSecondPerSquareMeter(value.ToDouble(null)); + => MassFlux.FromKilogramsPerSecondPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static MassFlux KilogramsPerSecondPerSquareMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFlux.FromKilogramsPerSecondPerSquareMillimeter(double.CreateChecked(value)); + => MassFlux.FromKilogramsPerSecondPerSquareMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFlux.FromKilogramsPerSecondPerSquareMillimeter(value.ToDouble(null)); + => MassFlux.FromKilogramsPerSecondPerSquareMillimeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassFractionExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassFractionExtensions.g.cs index 29c2971233..c1cb0c6a5a 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassFractionExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassFractionExtensions.g.cs @@ -32,268 +32,268 @@ namespace UnitsNet.NumberExtensions.NumberToMassFraction /// public static class NumberToMassFractionExtensions { - /// + /// public static MassFraction CentigramsPerGram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromCentigramsPerGram(double.CreateChecked(value)); + => MassFraction.FromCentigramsPerGram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromCentigramsPerGram(value.ToDouble(null)); + => MassFraction.FromCentigramsPerGram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction CentigramsPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromCentigramsPerKilogram(double.CreateChecked(value)); + => MassFraction.FromCentigramsPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromCentigramsPerKilogram(value.ToDouble(null)); + => MassFraction.FromCentigramsPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction DecagramsPerGram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromDecagramsPerGram(double.CreateChecked(value)); + => MassFraction.FromDecagramsPerGram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromDecagramsPerGram(value.ToDouble(null)); + => MassFraction.FromDecagramsPerGram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction DecagramsPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromDecagramsPerKilogram(double.CreateChecked(value)); + => MassFraction.FromDecagramsPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromDecagramsPerKilogram(value.ToDouble(null)); + => MassFraction.FromDecagramsPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction DecigramsPerGram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromDecigramsPerGram(double.CreateChecked(value)); + => MassFraction.FromDecigramsPerGram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromDecigramsPerGram(value.ToDouble(null)); + => MassFraction.FromDecigramsPerGram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction DecigramsPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromDecigramsPerKilogram(double.CreateChecked(value)); + => MassFraction.FromDecigramsPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromDecigramsPerKilogram(value.ToDouble(null)); + => MassFraction.FromDecigramsPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction DecimalFractions(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromDecimalFractions(double.CreateChecked(value)); + => MassFraction.FromDecimalFractions(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromDecimalFractions(value.ToDouble(null)); + => MassFraction.FromDecimalFractions(value.ToQuantityValue()); #endif - /// + /// public static MassFraction GramsPerGram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromGramsPerGram(double.CreateChecked(value)); + => MassFraction.FromGramsPerGram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromGramsPerGram(value.ToDouble(null)); + => MassFraction.FromGramsPerGram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction GramsPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromGramsPerKilogram(double.CreateChecked(value)); + => MassFraction.FromGramsPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromGramsPerKilogram(value.ToDouble(null)); + => MassFraction.FromGramsPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction HectogramsPerGram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromHectogramsPerGram(double.CreateChecked(value)); + => MassFraction.FromHectogramsPerGram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromHectogramsPerGram(value.ToDouble(null)); + => MassFraction.FromHectogramsPerGram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction HectogramsPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromHectogramsPerKilogram(double.CreateChecked(value)); + => MassFraction.FromHectogramsPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromHectogramsPerKilogram(value.ToDouble(null)); + => MassFraction.FromHectogramsPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction KilogramsPerGram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromKilogramsPerGram(double.CreateChecked(value)); + => MassFraction.FromKilogramsPerGram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromKilogramsPerGram(value.ToDouble(null)); + => MassFraction.FromKilogramsPerGram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction KilogramsPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromKilogramsPerKilogram(double.CreateChecked(value)); + => MassFraction.FromKilogramsPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromKilogramsPerKilogram(value.ToDouble(null)); + => MassFraction.FromKilogramsPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction MicrogramsPerGram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromMicrogramsPerGram(double.CreateChecked(value)); + => MassFraction.FromMicrogramsPerGram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromMicrogramsPerGram(value.ToDouble(null)); + => MassFraction.FromMicrogramsPerGram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction MicrogramsPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromMicrogramsPerKilogram(double.CreateChecked(value)); + => MassFraction.FromMicrogramsPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromMicrogramsPerKilogram(value.ToDouble(null)); + => MassFraction.FromMicrogramsPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction MilligramsPerGram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromMilligramsPerGram(double.CreateChecked(value)); + => MassFraction.FromMilligramsPerGram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromMilligramsPerGram(value.ToDouble(null)); + => MassFraction.FromMilligramsPerGram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction MilligramsPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromMilligramsPerKilogram(double.CreateChecked(value)); + => MassFraction.FromMilligramsPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromMilligramsPerKilogram(value.ToDouble(null)); + => MassFraction.FromMilligramsPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction NanogramsPerGram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromNanogramsPerGram(double.CreateChecked(value)); + => MassFraction.FromNanogramsPerGram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromNanogramsPerGram(value.ToDouble(null)); + => MassFraction.FromNanogramsPerGram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction NanogramsPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromNanogramsPerKilogram(double.CreateChecked(value)); + => MassFraction.FromNanogramsPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromNanogramsPerKilogram(value.ToDouble(null)); + => MassFraction.FromNanogramsPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static MassFraction PartsPerBillion(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromPartsPerBillion(double.CreateChecked(value)); + => MassFraction.FromPartsPerBillion(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromPartsPerBillion(value.ToDouble(null)); + => MassFraction.FromPartsPerBillion(value.ToQuantityValue()); #endif - /// + /// public static MassFraction PartsPerMillion(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromPartsPerMillion(double.CreateChecked(value)); + => MassFraction.FromPartsPerMillion(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromPartsPerMillion(value.ToDouble(null)); + => MassFraction.FromPartsPerMillion(value.ToQuantityValue()); #endif - /// + /// public static MassFraction PartsPerThousand(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromPartsPerThousand(double.CreateChecked(value)); + => MassFraction.FromPartsPerThousand(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromPartsPerThousand(value.ToDouble(null)); + => MassFraction.FromPartsPerThousand(value.ToQuantityValue()); #endif - /// + /// public static MassFraction PartsPerTrillion(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromPartsPerTrillion(double.CreateChecked(value)); + => MassFraction.FromPartsPerTrillion(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromPartsPerTrillion(value.ToDouble(null)); + => MassFraction.FromPartsPerTrillion(value.ToQuantityValue()); #endif - /// + /// public static MassFraction Percent(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassFraction.FromPercent(double.CreateChecked(value)); + => MassFraction.FromPercent(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassFraction.FromPercent(value.ToDouble(null)); + => MassFraction.FromPercent(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassMomentOfInertiaExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassMomentOfInertiaExtensions.g.cs index 98e24d2491..bbe9b2991d 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassMomentOfInertiaExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMassMomentOfInertiaExtensions.g.cs @@ -32,312 +32,312 @@ namespace UnitsNet.NumberExtensions.NumberToMassMomentOfInertia /// public static class NumberToMassMomentOfInertiaExtensions { - /// + /// public static MassMomentOfInertia GramSquareCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromGramSquareCentimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromGramSquareCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromGramSquareCentimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromGramSquareCentimeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia GramSquareDecimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromGramSquareDecimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromGramSquareDecimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromGramSquareDecimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromGramSquareDecimeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia GramSquareMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromGramSquareMeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromGramSquareMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromGramSquareMeters(value.ToDouble(null)); + => MassMomentOfInertia.FromGramSquareMeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia GramSquareMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromGramSquareMillimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromGramSquareMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromGramSquareMillimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromGramSquareMillimeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia KilogramSquareCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromKilogramSquareCentimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromKilogramSquareCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromKilogramSquareCentimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromKilogramSquareCentimeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia KilogramSquareDecimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromKilogramSquareDecimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromKilogramSquareDecimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromKilogramSquareDecimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromKilogramSquareDecimeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia KilogramSquareMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromKilogramSquareMeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromKilogramSquareMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromKilogramSquareMeters(value.ToDouble(null)); + => MassMomentOfInertia.FromKilogramSquareMeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia KilogramSquareMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromKilogramSquareMillimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromKilogramSquareMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromKilogramSquareMillimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromKilogramSquareMillimeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia KilotonneSquareCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromKilotonneSquareCentimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromKilotonneSquareCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromKilotonneSquareCentimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromKilotonneSquareCentimeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia KilotonneSquareDecimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromKilotonneSquareDecimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromKilotonneSquareDecimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromKilotonneSquareDecimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromKilotonneSquareDecimeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia KilotonneSquareMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromKilotonneSquareMeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromKilotonneSquareMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromKilotonneSquareMeters(value.ToDouble(null)); + => MassMomentOfInertia.FromKilotonneSquareMeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia KilotonneSquareMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromKilotonneSquareMillimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromKilotonneSquareMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromKilotonneSquareMillimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromKilotonneSquareMillimeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia MegatonneSquareCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromMegatonneSquareCentimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromMegatonneSquareCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromMegatonneSquareCentimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromMegatonneSquareCentimeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia MegatonneSquareDecimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromMegatonneSquareDecimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromMegatonneSquareDecimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromMegatonneSquareDecimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromMegatonneSquareDecimeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia MegatonneSquareMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromMegatonneSquareMeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromMegatonneSquareMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromMegatonneSquareMeters(value.ToDouble(null)); + => MassMomentOfInertia.FromMegatonneSquareMeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia MegatonneSquareMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromMegatonneSquareMillimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromMegatonneSquareMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromMegatonneSquareMillimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromMegatonneSquareMillimeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia MilligramSquareCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromMilligramSquareCentimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromMilligramSquareCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromMilligramSquareCentimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromMilligramSquareCentimeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia MilligramSquareDecimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromMilligramSquareDecimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromMilligramSquareDecimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromMilligramSquareDecimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromMilligramSquareDecimeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia MilligramSquareMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromMilligramSquareMeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromMilligramSquareMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromMilligramSquareMeters(value.ToDouble(null)); + => MassMomentOfInertia.FromMilligramSquareMeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia MilligramSquareMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromMilligramSquareMillimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromMilligramSquareMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromMilligramSquareMillimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromMilligramSquareMillimeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia PoundSquareFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromPoundSquareFeet(double.CreateChecked(value)); + => MassMomentOfInertia.FromPoundSquareFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromPoundSquareFeet(value.ToDouble(null)); + => MassMomentOfInertia.FromPoundSquareFeet(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia PoundSquareInches(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromPoundSquareInches(double.CreateChecked(value)); + => MassMomentOfInertia.FromPoundSquareInches(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromPoundSquareInches(value.ToDouble(null)); + => MassMomentOfInertia.FromPoundSquareInches(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia SlugSquareFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromSlugSquareFeet(double.CreateChecked(value)); + => MassMomentOfInertia.FromSlugSquareFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromSlugSquareFeet(value.ToDouble(null)); + => MassMomentOfInertia.FromSlugSquareFeet(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia SlugSquareInches(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromSlugSquareInches(double.CreateChecked(value)); + => MassMomentOfInertia.FromSlugSquareInches(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromSlugSquareInches(value.ToDouble(null)); + => MassMomentOfInertia.FromSlugSquareInches(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia TonneSquareCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromTonneSquareCentimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromTonneSquareCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromTonneSquareCentimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromTonneSquareCentimeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia TonneSquareDecimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromTonneSquareDecimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromTonneSquareDecimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromTonneSquareDecimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromTonneSquareDecimeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia TonneSquareMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromTonneSquareMeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromTonneSquareMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromTonneSquareMeters(value.ToDouble(null)); + => MassMomentOfInertia.FromTonneSquareMeters(value.ToQuantityValue()); #endif - /// + /// public static MassMomentOfInertia TonneSquareMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MassMomentOfInertia.FromTonneSquareMillimeters(double.CreateChecked(value)); + => MassMomentOfInertia.FromTonneSquareMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => MassMomentOfInertia.FromTonneSquareMillimeters(value.ToDouble(null)); + => MassMomentOfInertia.FromTonneSquareMillimeters(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolalityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolalityExtensions.g.cs index 086acee33c..949f512a9f 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolalityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolalityExtensions.g.cs @@ -32,37 +32,37 @@ namespace UnitsNet.NumberExtensions.NumberToMolality /// public static class NumberToMolalityExtensions { - /// + /// public static Molality MillimolesPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Molality.FromMillimolesPerKilogram(double.CreateChecked(value)); + => Molality.FromMillimolesPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => Molality.FromMillimolesPerKilogram(value.ToDouble(null)); + => Molality.FromMillimolesPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static Molality MolesPerGram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Molality.FromMolesPerGram(double.CreateChecked(value)); + => Molality.FromMolesPerGram(QuantityValue.CreateChecked(value)); #else , IConvertible - => Molality.FromMolesPerGram(value.ToDouble(null)); + => Molality.FromMolesPerGram(value.ToQuantityValue()); #endif - /// + /// public static Molality MolesPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Molality.FromMolesPerKilogram(double.CreateChecked(value)); + => Molality.FromMolesPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => Molality.FromMolesPerKilogram(value.ToDouble(null)); + => Molality.FromMolesPerKilogram(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarEnergyExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarEnergyExtensions.g.cs index 293f1a4ec0..51f0d67b78 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarEnergyExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarEnergyExtensions.g.cs @@ -32,37 +32,37 @@ namespace UnitsNet.NumberExtensions.NumberToMolarEnergy /// public static class NumberToMolarEnergyExtensions { - /// + /// public static MolarEnergy JoulesPerMole(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarEnergy.FromJoulesPerMole(double.CreateChecked(value)); + => MolarEnergy.FromJoulesPerMole(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarEnergy.FromJoulesPerMole(value.ToDouble(null)); + => MolarEnergy.FromJoulesPerMole(value.ToQuantityValue()); #endif - /// + /// public static MolarEnergy KilojoulesPerMole(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarEnergy.FromKilojoulesPerMole(double.CreateChecked(value)); + => MolarEnergy.FromKilojoulesPerMole(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarEnergy.FromKilojoulesPerMole(value.ToDouble(null)); + => MolarEnergy.FromKilojoulesPerMole(value.ToQuantityValue()); #endif - /// + /// public static MolarEnergy MegajoulesPerMole(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarEnergy.FromMegajoulesPerMole(double.CreateChecked(value)); + => MolarEnergy.FromMegajoulesPerMole(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarEnergy.FromMegajoulesPerMole(value.ToDouble(null)); + => MolarEnergy.FromMegajoulesPerMole(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarEntropyExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarEntropyExtensions.g.cs index 103a179231..ffbbe9fd6a 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarEntropyExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarEntropyExtensions.g.cs @@ -32,37 +32,37 @@ namespace UnitsNet.NumberExtensions.NumberToMolarEntropy /// public static class NumberToMolarEntropyExtensions { - /// + /// public static MolarEntropy JoulesPerMoleKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarEntropy.FromJoulesPerMoleKelvin(double.CreateChecked(value)); + => MolarEntropy.FromJoulesPerMoleKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarEntropy.FromJoulesPerMoleKelvin(value.ToDouble(null)); + => MolarEntropy.FromJoulesPerMoleKelvin(value.ToQuantityValue()); #endif - /// + /// public static MolarEntropy KilojoulesPerMoleKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarEntropy.FromKilojoulesPerMoleKelvin(double.CreateChecked(value)); + => MolarEntropy.FromKilojoulesPerMoleKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarEntropy.FromKilojoulesPerMoleKelvin(value.ToDouble(null)); + => MolarEntropy.FromKilojoulesPerMoleKelvin(value.ToQuantityValue()); #endif - /// + /// public static MolarEntropy MegajoulesPerMoleKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarEntropy.FromMegajoulesPerMoleKelvin(double.CreateChecked(value)); + => MolarEntropy.FromMegajoulesPerMoleKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarEntropy.FromMegajoulesPerMoleKelvin(value.ToDouble(null)); + => MolarEntropy.FromMegajoulesPerMoleKelvin(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarFlowExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarFlowExtensions.g.cs index 5dbfb6e6a3..ebcf4953a2 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarFlowExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarFlowExtensions.g.cs @@ -32,103 +32,103 @@ namespace UnitsNet.NumberExtensions.NumberToMolarFlow /// public static class NumberToMolarFlowExtensions { - /// + /// public static MolarFlow KilomolesPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarFlow.FromKilomolesPerHour(double.CreateChecked(value)); + => MolarFlow.FromKilomolesPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarFlow.FromKilomolesPerHour(value.ToDouble(null)); + => MolarFlow.FromKilomolesPerHour(value.ToQuantityValue()); #endif - /// + /// public static MolarFlow KilomolesPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarFlow.FromKilomolesPerMinute(double.CreateChecked(value)); + => MolarFlow.FromKilomolesPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarFlow.FromKilomolesPerMinute(value.ToDouble(null)); + => MolarFlow.FromKilomolesPerMinute(value.ToQuantityValue()); #endif - /// + /// public static MolarFlow KilomolesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarFlow.FromKilomolesPerSecond(double.CreateChecked(value)); + => MolarFlow.FromKilomolesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarFlow.FromKilomolesPerSecond(value.ToDouble(null)); + => MolarFlow.FromKilomolesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static MolarFlow MolesPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarFlow.FromMolesPerHour(double.CreateChecked(value)); + => MolarFlow.FromMolesPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarFlow.FromMolesPerHour(value.ToDouble(null)); + => MolarFlow.FromMolesPerHour(value.ToQuantityValue()); #endif - /// + /// public static MolarFlow MolesPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarFlow.FromMolesPerMinute(double.CreateChecked(value)); + => MolarFlow.FromMolesPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarFlow.FromMolesPerMinute(value.ToDouble(null)); + => MolarFlow.FromMolesPerMinute(value.ToQuantityValue()); #endif - /// + /// public static MolarFlow MolesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarFlow.FromMolesPerSecond(double.CreateChecked(value)); + => MolarFlow.FromMolesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarFlow.FromMolesPerSecond(value.ToDouble(null)); + => MolarFlow.FromMolesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static MolarFlow PoundMolesPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarFlow.FromPoundMolesPerHour(double.CreateChecked(value)); + => MolarFlow.FromPoundMolesPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarFlow.FromPoundMolesPerHour(value.ToDouble(null)); + => MolarFlow.FromPoundMolesPerHour(value.ToQuantityValue()); #endif - /// + /// public static MolarFlow PoundMolesPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarFlow.FromPoundMolesPerMinute(double.CreateChecked(value)); + => MolarFlow.FromPoundMolesPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarFlow.FromPoundMolesPerMinute(value.ToDouble(null)); + => MolarFlow.FromPoundMolesPerMinute(value.ToQuantityValue()); #endif - /// + /// public static MolarFlow PoundMolesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarFlow.FromPoundMolesPerSecond(double.CreateChecked(value)); + => MolarFlow.FromPoundMolesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarFlow.FromPoundMolesPerSecond(value.ToDouble(null)); + => MolarFlow.FromPoundMolesPerSecond(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarMassExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarMassExtensions.g.cs index 8b8236f581..07de8d1751 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarMassExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarMassExtensions.g.cs @@ -32,147 +32,147 @@ namespace UnitsNet.NumberExtensions.NumberToMolarMass /// public static class NumberToMolarMassExtensions { - /// + /// public static MolarMass CentigramsPerMole(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarMass.FromCentigramsPerMole(double.CreateChecked(value)); + => MolarMass.FromCentigramsPerMole(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarMass.FromCentigramsPerMole(value.ToDouble(null)); + => MolarMass.FromCentigramsPerMole(value.ToQuantityValue()); #endif - /// + /// public static MolarMass DecagramsPerMole(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarMass.FromDecagramsPerMole(double.CreateChecked(value)); + => MolarMass.FromDecagramsPerMole(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarMass.FromDecagramsPerMole(value.ToDouble(null)); + => MolarMass.FromDecagramsPerMole(value.ToQuantityValue()); #endif - /// + /// public static MolarMass DecigramsPerMole(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarMass.FromDecigramsPerMole(double.CreateChecked(value)); + => MolarMass.FromDecigramsPerMole(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarMass.FromDecigramsPerMole(value.ToDouble(null)); + => MolarMass.FromDecigramsPerMole(value.ToQuantityValue()); #endif - /// + /// public static MolarMass GramsPerMole(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarMass.FromGramsPerMole(double.CreateChecked(value)); + => MolarMass.FromGramsPerMole(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarMass.FromGramsPerMole(value.ToDouble(null)); + => MolarMass.FromGramsPerMole(value.ToQuantityValue()); #endif - /// + /// public static MolarMass HectogramsPerMole(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarMass.FromHectogramsPerMole(double.CreateChecked(value)); + => MolarMass.FromHectogramsPerMole(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarMass.FromHectogramsPerMole(value.ToDouble(null)); + => MolarMass.FromHectogramsPerMole(value.ToQuantityValue()); #endif - /// + /// public static MolarMass KilogramsPerKilomole(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarMass.FromKilogramsPerKilomole(double.CreateChecked(value)); + => MolarMass.FromKilogramsPerKilomole(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarMass.FromKilogramsPerKilomole(value.ToDouble(null)); + => MolarMass.FromKilogramsPerKilomole(value.ToQuantityValue()); #endif - /// + /// public static MolarMass KilogramsPerMole(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarMass.FromKilogramsPerMole(double.CreateChecked(value)); + => MolarMass.FromKilogramsPerMole(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarMass.FromKilogramsPerMole(value.ToDouble(null)); + => MolarMass.FromKilogramsPerMole(value.ToQuantityValue()); #endif - /// + /// public static MolarMass KilopoundsPerMole(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarMass.FromKilopoundsPerMole(double.CreateChecked(value)); + => MolarMass.FromKilopoundsPerMole(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarMass.FromKilopoundsPerMole(value.ToDouble(null)); + => MolarMass.FromKilopoundsPerMole(value.ToQuantityValue()); #endif - /// + /// public static MolarMass MegapoundsPerMole(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarMass.FromMegapoundsPerMole(double.CreateChecked(value)); + => MolarMass.FromMegapoundsPerMole(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarMass.FromMegapoundsPerMole(value.ToDouble(null)); + => MolarMass.FromMegapoundsPerMole(value.ToQuantityValue()); #endif - /// + /// public static MolarMass MicrogramsPerMole(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarMass.FromMicrogramsPerMole(double.CreateChecked(value)); + => MolarMass.FromMicrogramsPerMole(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarMass.FromMicrogramsPerMole(value.ToDouble(null)); + => MolarMass.FromMicrogramsPerMole(value.ToQuantityValue()); #endif - /// + /// public static MolarMass MilligramsPerMole(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarMass.FromMilligramsPerMole(double.CreateChecked(value)); + => MolarMass.FromMilligramsPerMole(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarMass.FromMilligramsPerMole(value.ToDouble(null)); + => MolarMass.FromMilligramsPerMole(value.ToQuantityValue()); #endif - /// + /// public static MolarMass NanogramsPerMole(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarMass.FromNanogramsPerMole(double.CreateChecked(value)); + => MolarMass.FromNanogramsPerMole(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarMass.FromNanogramsPerMole(value.ToDouble(null)); + => MolarMass.FromNanogramsPerMole(value.ToQuantityValue()); #endif - /// + /// public static MolarMass PoundsPerMole(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => MolarMass.FromPoundsPerMole(double.CreateChecked(value)); + => MolarMass.FromPoundsPerMole(QuantityValue.CreateChecked(value)); #else , IConvertible - => MolarMass.FromPoundsPerMole(value.ToDouble(null)); + => MolarMass.FromPoundsPerMole(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarityExtensions.g.cs index a9fb608bf2..a7480085fe 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToMolarityExtensions.g.cs @@ -32,125 +32,125 @@ namespace UnitsNet.NumberExtensions.NumberToMolarity /// public static class NumberToMolarityExtensions { - /// + /// public static Molarity CentimolesPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Molarity.FromCentimolesPerLiter(double.CreateChecked(value)); + => Molarity.FromCentimolesPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Molarity.FromCentimolesPerLiter(value.ToDouble(null)); + => Molarity.FromCentimolesPerLiter(value.ToQuantityValue()); #endif - /// + /// public static Molarity DecimolesPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Molarity.FromDecimolesPerLiter(double.CreateChecked(value)); + => Molarity.FromDecimolesPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Molarity.FromDecimolesPerLiter(value.ToDouble(null)); + => Molarity.FromDecimolesPerLiter(value.ToQuantityValue()); #endif - /// + /// public static Molarity FemtomolesPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Molarity.FromFemtomolesPerLiter(double.CreateChecked(value)); + => Molarity.FromFemtomolesPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Molarity.FromFemtomolesPerLiter(value.ToDouble(null)); + => Molarity.FromFemtomolesPerLiter(value.ToQuantityValue()); #endif - /// + /// public static Molarity KilomolesPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Molarity.FromKilomolesPerCubicMeter(double.CreateChecked(value)); + => Molarity.FromKilomolesPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Molarity.FromKilomolesPerCubicMeter(value.ToDouble(null)); + => Molarity.FromKilomolesPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static Molarity MicromolesPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Molarity.FromMicromolesPerLiter(double.CreateChecked(value)); + => Molarity.FromMicromolesPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Molarity.FromMicromolesPerLiter(value.ToDouble(null)); + => Molarity.FromMicromolesPerLiter(value.ToQuantityValue()); #endif - /// + /// public static Molarity MillimolesPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Molarity.FromMillimolesPerLiter(double.CreateChecked(value)); + => Molarity.FromMillimolesPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Molarity.FromMillimolesPerLiter(value.ToDouble(null)); + => Molarity.FromMillimolesPerLiter(value.ToQuantityValue()); #endif - /// + /// public static Molarity MolesPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Molarity.FromMolesPerCubicMeter(double.CreateChecked(value)); + => Molarity.FromMolesPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Molarity.FromMolesPerCubicMeter(value.ToDouble(null)); + => Molarity.FromMolesPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static Molarity MolesPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Molarity.FromMolesPerLiter(double.CreateChecked(value)); + => Molarity.FromMolesPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Molarity.FromMolesPerLiter(value.ToDouble(null)); + => Molarity.FromMolesPerLiter(value.ToQuantityValue()); #endif - /// + /// public static Molarity NanomolesPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Molarity.FromNanomolesPerLiter(double.CreateChecked(value)); + => Molarity.FromNanomolesPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Molarity.FromNanomolesPerLiter(value.ToDouble(null)); + => Molarity.FromNanomolesPerLiter(value.ToQuantityValue()); #endif - /// + /// public static Molarity PicomolesPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Molarity.FromPicomolesPerLiter(double.CreateChecked(value)); + => Molarity.FromPicomolesPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Molarity.FromPicomolesPerLiter(value.ToDouble(null)); + => Molarity.FromPicomolesPerLiter(value.ToQuantityValue()); #endif - /// + /// public static Molarity PoundMolesPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Molarity.FromPoundMolesPerCubicFoot(double.CreateChecked(value)); + => Molarity.FromPoundMolesPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => Molarity.FromPoundMolesPerCubicFoot(value.ToDouble(null)); + => Molarity.FromPoundMolesPerCubicFoot(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToPermeabilityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToPermeabilityExtensions.g.cs index 0a4dc39592..dd7ce0fba0 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToPermeabilityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToPermeabilityExtensions.g.cs @@ -32,15 +32,15 @@ namespace UnitsNet.NumberExtensions.NumberToPermeability /// public static class NumberToPermeabilityExtensions { - /// + /// public static Permeability HenriesPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Permeability.FromHenriesPerMeter(double.CreateChecked(value)); + => Permeability.FromHenriesPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Permeability.FromHenriesPerMeter(value.ToDouble(null)); + => Permeability.FromHenriesPerMeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToPermittivityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToPermittivityExtensions.g.cs index 1aa3a2b179..f843bfb315 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToPermittivityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToPermittivityExtensions.g.cs @@ -32,15 +32,15 @@ namespace UnitsNet.NumberExtensions.NumberToPermittivity /// public static class NumberToPermittivityExtensions { - /// + /// public static Permittivity FaradsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Permittivity.FromFaradsPerMeter(double.CreateChecked(value)); + => Permittivity.FromFaradsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Permittivity.FromFaradsPerMeter(value.ToDouble(null)); + => Permittivity.FromFaradsPerMeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToPorousMediumPermeabilityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToPorousMediumPermeabilityExtensions.g.cs index 1c661842ae..63b3a665f2 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToPorousMediumPermeabilityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToPorousMediumPermeabilityExtensions.g.cs @@ -32,59 +32,59 @@ namespace UnitsNet.NumberExtensions.NumberToPorousMediumPermeability /// public static class NumberToPorousMediumPermeabilityExtensions { - /// + /// public static PorousMediumPermeability Darcys(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PorousMediumPermeability.FromDarcys(double.CreateChecked(value)); + => PorousMediumPermeability.FromDarcys(QuantityValue.CreateChecked(value)); #else , IConvertible - => PorousMediumPermeability.FromDarcys(value.ToDouble(null)); + => PorousMediumPermeability.FromDarcys(value.ToQuantityValue()); #endif - /// + /// public static PorousMediumPermeability Microdarcys(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PorousMediumPermeability.FromMicrodarcys(double.CreateChecked(value)); + => PorousMediumPermeability.FromMicrodarcys(QuantityValue.CreateChecked(value)); #else , IConvertible - => PorousMediumPermeability.FromMicrodarcys(value.ToDouble(null)); + => PorousMediumPermeability.FromMicrodarcys(value.ToQuantityValue()); #endif - /// + /// public static PorousMediumPermeability Millidarcys(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PorousMediumPermeability.FromMillidarcys(double.CreateChecked(value)); + => PorousMediumPermeability.FromMillidarcys(QuantityValue.CreateChecked(value)); #else , IConvertible - => PorousMediumPermeability.FromMillidarcys(value.ToDouble(null)); + => PorousMediumPermeability.FromMillidarcys(value.ToQuantityValue()); #endif - /// + /// public static PorousMediumPermeability SquareCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PorousMediumPermeability.FromSquareCentimeters(double.CreateChecked(value)); + => PorousMediumPermeability.FromSquareCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => PorousMediumPermeability.FromSquareCentimeters(value.ToDouble(null)); + => PorousMediumPermeability.FromSquareCentimeters(value.ToQuantityValue()); #endif - /// + /// public static PorousMediumPermeability SquareMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PorousMediumPermeability.FromSquareMeters(double.CreateChecked(value)); + => PorousMediumPermeability.FromSquareMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => PorousMediumPermeability.FromSquareMeters(value.ToDouble(null)); + => PorousMediumPermeability.FromSquareMeters(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToPowerDensityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToPowerDensityExtensions.g.cs index 685f2c96e7..a6027ca347 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToPowerDensityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToPowerDensityExtensions.g.cs @@ -32,488 +32,488 @@ namespace UnitsNet.NumberExtensions.NumberToPowerDensity /// public static class NumberToPowerDensityExtensions { - /// + /// public static PowerDensity DecawattsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromDecawattsPerCubicFoot(double.CreateChecked(value)); + => PowerDensity.FromDecawattsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromDecawattsPerCubicFoot(value.ToDouble(null)); + => PowerDensity.FromDecawattsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity DecawattsPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromDecawattsPerCubicInch(double.CreateChecked(value)); + => PowerDensity.FromDecawattsPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromDecawattsPerCubicInch(value.ToDouble(null)); + => PowerDensity.FromDecawattsPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity DecawattsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromDecawattsPerCubicMeter(double.CreateChecked(value)); + => PowerDensity.FromDecawattsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromDecawattsPerCubicMeter(value.ToDouble(null)); + => PowerDensity.FromDecawattsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity DecawattsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromDecawattsPerLiter(double.CreateChecked(value)); + => PowerDensity.FromDecawattsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromDecawattsPerLiter(value.ToDouble(null)); + => PowerDensity.FromDecawattsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity DeciwattsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromDeciwattsPerCubicFoot(double.CreateChecked(value)); + => PowerDensity.FromDeciwattsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromDeciwattsPerCubicFoot(value.ToDouble(null)); + => PowerDensity.FromDeciwattsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity DeciwattsPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromDeciwattsPerCubicInch(double.CreateChecked(value)); + => PowerDensity.FromDeciwattsPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromDeciwattsPerCubicInch(value.ToDouble(null)); + => PowerDensity.FromDeciwattsPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity DeciwattsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromDeciwattsPerCubicMeter(double.CreateChecked(value)); + => PowerDensity.FromDeciwattsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromDeciwattsPerCubicMeter(value.ToDouble(null)); + => PowerDensity.FromDeciwattsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity DeciwattsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromDeciwattsPerLiter(double.CreateChecked(value)); + => PowerDensity.FromDeciwattsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromDeciwattsPerLiter(value.ToDouble(null)); + => PowerDensity.FromDeciwattsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity GigawattsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromGigawattsPerCubicFoot(double.CreateChecked(value)); + => PowerDensity.FromGigawattsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromGigawattsPerCubicFoot(value.ToDouble(null)); + => PowerDensity.FromGigawattsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity GigawattsPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromGigawattsPerCubicInch(double.CreateChecked(value)); + => PowerDensity.FromGigawattsPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromGigawattsPerCubicInch(value.ToDouble(null)); + => PowerDensity.FromGigawattsPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity GigawattsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromGigawattsPerCubicMeter(double.CreateChecked(value)); + => PowerDensity.FromGigawattsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromGigawattsPerCubicMeter(value.ToDouble(null)); + => PowerDensity.FromGigawattsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity GigawattsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromGigawattsPerLiter(double.CreateChecked(value)); + => PowerDensity.FromGigawattsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromGigawattsPerLiter(value.ToDouble(null)); + => PowerDensity.FromGigawattsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity KilowattsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromKilowattsPerCubicFoot(double.CreateChecked(value)); + => PowerDensity.FromKilowattsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromKilowattsPerCubicFoot(value.ToDouble(null)); + => PowerDensity.FromKilowattsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity KilowattsPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromKilowattsPerCubicInch(double.CreateChecked(value)); + => PowerDensity.FromKilowattsPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromKilowattsPerCubicInch(value.ToDouble(null)); + => PowerDensity.FromKilowattsPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity KilowattsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromKilowattsPerCubicMeter(double.CreateChecked(value)); + => PowerDensity.FromKilowattsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromKilowattsPerCubicMeter(value.ToDouble(null)); + => PowerDensity.FromKilowattsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity KilowattsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromKilowattsPerLiter(double.CreateChecked(value)); + => PowerDensity.FromKilowattsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromKilowattsPerLiter(value.ToDouble(null)); + => PowerDensity.FromKilowattsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity MegawattsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromMegawattsPerCubicFoot(double.CreateChecked(value)); + => PowerDensity.FromMegawattsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromMegawattsPerCubicFoot(value.ToDouble(null)); + => PowerDensity.FromMegawattsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity MegawattsPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromMegawattsPerCubicInch(double.CreateChecked(value)); + => PowerDensity.FromMegawattsPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromMegawattsPerCubicInch(value.ToDouble(null)); + => PowerDensity.FromMegawattsPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity MegawattsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromMegawattsPerCubicMeter(double.CreateChecked(value)); + => PowerDensity.FromMegawattsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromMegawattsPerCubicMeter(value.ToDouble(null)); + => PowerDensity.FromMegawattsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity MegawattsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromMegawattsPerLiter(double.CreateChecked(value)); + => PowerDensity.FromMegawattsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromMegawattsPerLiter(value.ToDouble(null)); + => PowerDensity.FromMegawattsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity MicrowattsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromMicrowattsPerCubicFoot(double.CreateChecked(value)); + => PowerDensity.FromMicrowattsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromMicrowattsPerCubicFoot(value.ToDouble(null)); + => PowerDensity.FromMicrowattsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity MicrowattsPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromMicrowattsPerCubicInch(double.CreateChecked(value)); + => PowerDensity.FromMicrowattsPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromMicrowattsPerCubicInch(value.ToDouble(null)); + => PowerDensity.FromMicrowattsPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity MicrowattsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromMicrowattsPerCubicMeter(double.CreateChecked(value)); + => PowerDensity.FromMicrowattsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromMicrowattsPerCubicMeter(value.ToDouble(null)); + => PowerDensity.FromMicrowattsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity MicrowattsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromMicrowattsPerLiter(double.CreateChecked(value)); + => PowerDensity.FromMicrowattsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromMicrowattsPerLiter(value.ToDouble(null)); + => PowerDensity.FromMicrowattsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity MilliwattsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromMilliwattsPerCubicFoot(double.CreateChecked(value)); + => PowerDensity.FromMilliwattsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromMilliwattsPerCubicFoot(value.ToDouble(null)); + => PowerDensity.FromMilliwattsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity MilliwattsPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromMilliwattsPerCubicInch(double.CreateChecked(value)); + => PowerDensity.FromMilliwattsPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromMilliwattsPerCubicInch(value.ToDouble(null)); + => PowerDensity.FromMilliwattsPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity MilliwattsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromMilliwattsPerCubicMeter(double.CreateChecked(value)); + => PowerDensity.FromMilliwattsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromMilliwattsPerCubicMeter(value.ToDouble(null)); + => PowerDensity.FromMilliwattsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity MilliwattsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromMilliwattsPerLiter(double.CreateChecked(value)); + => PowerDensity.FromMilliwattsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromMilliwattsPerLiter(value.ToDouble(null)); + => PowerDensity.FromMilliwattsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity NanowattsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromNanowattsPerCubicFoot(double.CreateChecked(value)); + => PowerDensity.FromNanowattsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromNanowattsPerCubicFoot(value.ToDouble(null)); + => PowerDensity.FromNanowattsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity NanowattsPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromNanowattsPerCubicInch(double.CreateChecked(value)); + => PowerDensity.FromNanowattsPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromNanowattsPerCubicInch(value.ToDouble(null)); + => PowerDensity.FromNanowattsPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity NanowattsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromNanowattsPerCubicMeter(double.CreateChecked(value)); + => PowerDensity.FromNanowattsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromNanowattsPerCubicMeter(value.ToDouble(null)); + => PowerDensity.FromNanowattsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity NanowattsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromNanowattsPerLiter(double.CreateChecked(value)); + => PowerDensity.FromNanowattsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromNanowattsPerLiter(value.ToDouble(null)); + => PowerDensity.FromNanowattsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity PicowattsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromPicowattsPerCubicFoot(double.CreateChecked(value)); + => PowerDensity.FromPicowattsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromPicowattsPerCubicFoot(value.ToDouble(null)); + => PowerDensity.FromPicowattsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity PicowattsPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromPicowattsPerCubicInch(double.CreateChecked(value)); + => PowerDensity.FromPicowattsPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromPicowattsPerCubicInch(value.ToDouble(null)); + => PowerDensity.FromPicowattsPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity PicowattsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromPicowattsPerCubicMeter(double.CreateChecked(value)); + => PowerDensity.FromPicowattsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromPicowattsPerCubicMeter(value.ToDouble(null)); + => PowerDensity.FromPicowattsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity PicowattsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromPicowattsPerLiter(double.CreateChecked(value)); + => PowerDensity.FromPicowattsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromPicowattsPerLiter(value.ToDouble(null)); + => PowerDensity.FromPicowattsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity TerawattsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromTerawattsPerCubicFoot(double.CreateChecked(value)); + => PowerDensity.FromTerawattsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromTerawattsPerCubicFoot(value.ToDouble(null)); + => PowerDensity.FromTerawattsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity TerawattsPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromTerawattsPerCubicInch(double.CreateChecked(value)); + => PowerDensity.FromTerawattsPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromTerawattsPerCubicInch(value.ToDouble(null)); + => PowerDensity.FromTerawattsPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity TerawattsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromTerawattsPerCubicMeter(double.CreateChecked(value)); + => PowerDensity.FromTerawattsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromTerawattsPerCubicMeter(value.ToDouble(null)); + => PowerDensity.FromTerawattsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity TerawattsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromTerawattsPerLiter(double.CreateChecked(value)); + => PowerDensity.FromTerawattsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromTerawattsPerLiter(value.ToDouble(null)); + => PowerDensity.FromTerawattsPerLiter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity WattsPerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromWattsPerCubicFoot(double.CreateChecked(value)); + => PowerDensity.FromWattsPerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromWattsPerCubicFoot(value.ToDouble(null)); + => PowerDensity.FromWattsPerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity WattsPerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromWattsPerCubicInch(double.CreateChecked(value)); + => PowerDensity.FromWattsPerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromWattsPerCubicInch(value.ToDouble(null)); + => PowerDensity.FromWattsPerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity WattsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromWattsPerCubicMeter(double.CreateChecked(value)); + => PowerDensity.FromWattsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromWattsPerCubicMeter(value.ToDouble(null)); + => PowerDensity.FromWattsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static PowerDensity WattsPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerDensity.FromWattsPerLiter(double.CreateChecked(value)); + => PowerDensity.FromWattsPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerDensity.FromWattsPerLiter(value.ToDouble(null)); + => PowerDensity.FromWattsPerLiter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToPowerExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToPowerExtensions.g.cs index a3f802215b..886ab7566b 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToPowerExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToPowerExtensions.g.cs @@ -32,301 +32,301 @@ namespace UnitsNet.NumberExtensions.NumberToPower /// public static class NumberToPowerExtensions { - /// + /// public static Power BoilerHorsepower(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromBoilerHorsepower(double.CreateChecked(value)); + => Power.FromBoilerHorsepower(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromBoilerHorsepower(value.ToDouble(null)); + => Power.FromBoilerHorsepower(value.ToQuantityValue()); #endif - /// + /// public static Power BritishThermalUnitsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromBritishThermalUnitsPerHour(double.CreateChecked(value)); + => Power.FromBritishThermalUnitsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromBritishThermalUnitsPerHour(value.ToDouble(null)); + => Power.FromBritishThermalUnitsPerHour(value.ToQuantityValue()); #endif - /// + /// public static Power Decawatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromDecawatts(double.CreateChecked(value)); + => Power.FromDecawatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromDecawatts(value.ToDouble(null)); + => Power.FromDecawatts(value.ToQuantityValue()); #endif - /// + /// public static Power Deciwatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromDeciwatts(double.CreateChecked(value)); + => Power.FromDeciwatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromDeciwatts(value.ToDouble(null)); + => Power.FromDeciwatts(value.ToQuantityValue()); #endif - /// + /// public static Power ElectricalHorsepower(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromElectricalHorsepower(double.CreateChecked(value)); + => Power.FromElectricalHorsepower(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromElectricalHorsepower(value.ToDouble(null)); + => Power.FromElectricalHorsepower(value.ToQuantityValue()); #endif - /// + /// public static Power Femtowatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromFemtowatts(double.CreateChecked(value)); + => Power.FromFemtowatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromFemtowatts(value.ToDouble(null)); + => Power.FromFemtowatts(value.ToQuantityValue()); #endif - /// + /// public static Power GigajoulesPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromGigajoulesPerHour(double.CreateChecked(value)); + => Power.FromGigajoulesPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromGigajoulesPerHour(value.ToDouble(null)); + => Power.FromGigajoulesPerHour(value.ToQuantityValue()); #endif - /// + /// public static Power Gigawatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromGigawatts(double.CreateChecked(value)); + => Power.FromGigawatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromGigawatts(value.ToDouble(null)); + => Power.FromGigawatts(value.ToQuantityValue()); #endif - /// + /// public static Power HydraulicHorsepower(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromHydraulicHorsepower(double.CreateChecked(value)); + => Power.FromHydraulicHorsepower(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromHydraulicHorsepower(value.ToDouble(null)); + => Power.FromHydraulicHorsepower(value.ToQuantityValue()); #endif - /// + /// public static Power JoulesPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromJoulesPerHour(double.CreateChecked(value)); + => Power.FromJoulesPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromJoulesPerHour(value.ToDouble(null)); + => Power.FromJoulesPerHour(value.ToQuantityValue()); #endif - /// + /// public static Power KilobritishThermalUnitsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromKilobritishThermalUnitsPerHour(double.CreateChecked(value)); + => Power.FromKilobritishThermalUnitsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromKilobritishThermalUnitsPerHour(value.ToDouble(null)); + => Power.FromKilobritishThermalUnitsPerHour(value.ToQuantityValue()); #endif - /// + /// public static Power KilojoulesPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromKilojoulesPerHour(double.CreateChecked(value)); + => Power.FromKilojoulesPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromKilojoulesPerHour(value.ToDouble(null)); + => Power.FromKilojoulesPerHour(value.ToQuantityValue()); #endif - /// + /// public static Power Kilowatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromKilowatts(double.CreateChecked(value)); + => Power.FromKilowatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromKilowatts(value.ToDouble(null)); + => Power.FromKilowatts(value.ToQuantityValue()); #endif - /// + /// public static Power MechanicalHorsepower(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromMechanicalHorsepower(double.CreateChecked(value)); + => Power.FromMechanicalHorsepower(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromMechanicalHorsepower(value.ToDouble(null)); + => Power.FromMechanicalHorsepower(value.ToQuantityValue()); #endif - /// + /// public static Power MegabritishThermalUnitsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromMegabritishThermalUnitsPerHour(double.CreateChecked(value)); + => Power.FromMegabritishThermalUnitsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromMegabritishThermalUnitsPerHour(value.ToDouble(null)); + => Power.FromMegabritishThermalUnitsPerHour(value.ToQuantityValue()); #endif - /// + /// public static Power MegajoulesPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromMegajoulesPerHour(double.CreateChecked(value)); + => Power.FromMegajoulesPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromMegajoulesPerHour(value.ToDouble(null)); + => Power.FromMegajoulesPerHour(value.ToQuantityValue()); #endif - /// + /// public static Power Megawatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromMegawatts(double.CreateChecked(value)); + => Power.FromMegawatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromMegawatts(value.ToDouble(null)); + => Power.FromMegawatts(value.ToQuantityValue()); #endif - /// + /// public static Power MetricHorsepower(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromMetricHorsepower(double.CreateChecked(value)); + => Power.FromMetricHorsepower(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromMetricHorsepower(value.ToDouble(null)); + => Power.FromMetricHorsepower(value.ToQuantityValue()); #endif - /// + /// public static Power Microwatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromMicrowatts(double.CreateChecked(value)); + => Power.FromMicrowatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromMicrowatts(value.ToDouble(null)); + => Power.FromMicrowatts(value.ToQuantityValue()); #endif - /// + /// public static Power MillijoulesPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromMillijoulesPerHour(double.CreateChecked(value)); + => Power.FromMillijoulesPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromMillijoulesPerHour(value.ToDouble(null)); + => Power.FromMillijoulesPerHour(value.ToQuantityValue()); #endif - /// + /// public static Power Milliwatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromMilliwatts(double.CreateChecked(value)); + => Power.FromMilliwatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromMilliwatts(value.ToDouble(null)); + => Power.FromMilliwatts(value.ToQuantityValue()); #endif - /// + /// public static Power Nanowatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromNanowatts(double.CreateChecked(value)); + => Power.FromNanowatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromNanowatts(value.ToDouble(null)); + => Power.FromNanowatts(value.ToQuantityValue()); #endif - /// + /// public static Power Petawatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromPetawatts(double.CreateChecked(value)); + => Power.FromPetawatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromPetawatts(value.ToDouble(null)); + => Power.FromPetawatts(value.ToQuantityValue()); #endif - /// + /// public static Power Picowatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromPicowatts(double.CreateChecked(value)); + => Power.FromPicowatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromPicowatts(value.ToDouble(null)); + => Power.FromPicowatts(value.ToQuantityValue()); #endif - /// + /// public static Power Terawatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromTerawatts(double.CreateChecked(value)); + => Power.FromTerawatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromTerawatts(value.ToDouble(null)); + => Power.FromTerawatts(value.ToQuantityValue()); #endif - /// + /// public static Power TonsOfRefrigeration(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromTonsOfRefrigeration(double.CreateChecked(value)); + => Power.FromTonsOfRefrigeration(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromTonsOfRefrigeration(value.ToDouble(null)); + => Power.FromTonsOfRefrigeration(value.ToQuantityValue()); #endif - /// + /// public static Power Watts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Power.FromWatts(double.CreateChecked(value)); + => Power.FromWatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Power.FromWatts(value.ToDouble(null)); + => Power.FromWatts(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToPowerRatioExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToPowerRatioExtensions.g.cs index 2577f12def..6e2869e040 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToPowerRatioExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToPowerRatioExtensions.g.cs @@ -32,26 +32,26 @@ namespace UnitsNet.NumberExtensions.NumberToPowerRatio /// public static class NumberToPowerRatioExtensions { - /// + /// public static PowerRatio DecibelMilliwatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerRatio.FromDecibelMilliwatts(double.CreateChecked(value)); + => PowerRatio.FromDecibelMilliwatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerRatio.FromDecibelMilliwatts(value.ToDouble(null)); + => PowerRatio.FromDecibelMilliwatts(value.ToQuantityValue()); #endif - /// + /// public static PowerRatio DecibelWatts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PowerRatio.FromDecibelWatts(double.CreateChecked(value)); + => PowerRatio.FromDecibelWatts(QuantityValue.CreateChecked(value)); #else , IConvertible - => PowerRatio.FromDecibelWatts(value.ToDouble(null)); + => PowerRatio.FromDecibelWatts(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToPressureChangeRateExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToPressureChangeRateExtensions.g.cs index 525d631589..891ed7ae78 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToPressureChangeRateExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToPressureChangeRateExtensions.g.cs @@ -32,202 +32,202 @@ namespace UnitsNet.NumberExtensions.NumberToPressureChangeRate /// public static class NumberToPressureChangeRateExtensions { - /// + /// public static PressureChangeRate AtmospheresPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromAtmospheresPerSecond(double.CreateChecked(value)); + => PressureChangeRate.FromAtmospheresPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromAtmospheresPerSecond(value.ToDouble(null)); + => PressureChangeRate.FromAtmospheresPerSecond(value.ToQuantityValue()); #endif - /// + /// public static PressureChangeRate BarsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromBarsPerMinute(double.CreateChecked(value)); + => PressureChangeRate.FromBarsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromBarsPerMinute(value.ToDouble(null)); + => PressureChangeRate.FromBarsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static PressureChangeRate BarsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromBarsPerSecond(double.CreateChecked(value)); + => PressureChangeRate.FromBarsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromBarsPerSecond(value.ToDouble(null)); + => PressureChangeRate.FromBarsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static PressureChangeRate KilopascalsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromKilopascalsPerMinute(double.CreateChecked(value)); + => PressureChangeRate.FromKilopascalsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromKilopascalsPerMinute(value.ToDouble(null)); + => PressureChangeRate.FromKilopascalsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static PressureChangeRate KilopascalsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromKilopascalsPerSecond(double.CreateChecked(value)); + => PressureChangeRate.FromKilopascalsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromKilopascalsPerSecond(value.ToDouble(null)); + => PressureChangeRate.FromKilopascalsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static PressureChangeRate KilopoundsForcePerSquareInchPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromKilopoundsForcePerSquareInchPerMinute(double.CreateChecked(value)); + => PressureChangeRate.FromKilopoundsForcePerSquareInchPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromKilopoundsForcePerSquareInchPerMinute(value.ToDouble(null)); + => PressureChangeRate.FromKilopoundsForcePerSquareInchPerMinute(value.ToQuantityValue()); #endif - /// + /// public static PressureChangeRate KilopoundsForcePerSquareInchPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromKilopoundsForcePerSquareInchPerSecond(double.CreateChecked(value)); + => PressureChangeRate.FromKilopoundsForcePerSquareInchPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromKilopoundsForcePerSquareInchPerSecond(value.ToDouble(null)); + => PressureChangeRate.FromKilopoundsForcePerSquareInchPerSecond(value.ToQuantityValue()); #endif - /// + /// public static PressureChangeRate MegapascalsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromMegapascalsPerMinute(double.CreateChecked(value)); + => PressureChangeRate.FromMegapascalsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromMegapascalsPerMinute(value.ToDouble(null)); + => PressureChangeRate.FromMegapascalsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static PressureChangeRate MegapascalsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromMegapascalsPerSecond(double.CreateChecked(value)); + => PressureChangeRate.FromMegapascalsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromMegapascalsPerSecond(value.ToDouble(null)); + => PressureChangeRate.FromMegapascalsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static PressureChangeRate MegapoundsForcePerSquareInchPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromMegapoundsForcePerSquareInchPerMinute(double.CreateChecked(value)); + => PressureChangeRate.FromMegapoundsForcePerSquareInchPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromMegapoundsForcePerSquareInchPerMinute(value.ToDouble(null)); + => PressureChangeRate.FromMegapoundsForcePerSquareInchPerMinute(value.ToQuantityValue()); #endif - /// + /// public static PressureChangeRate MegapoundsForcePerSquareInchPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromMegapoundsForcePerSquareInchPerSecond(double.CreateChecked(value)); + => PressureChangeRate.FromMegapoundsForcePerSquareInchPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromMegapoundsForcePerSquareInchPerSecond(value.ToDouble(null)); + => PressureChangeRate.FromMegapoundsForcePerSquareInchPerSecond(value.ToQuantityValue()); #endif - /// + /// public static PressureChangeRate MillibarsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromMillibarsPerMinute(double.CreateChecked(value)); + => PressureChangeRate.FromMillibarsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromMillibarsPerMinute(value.ToDouble(null)); + => PressureChangeRate.FromMillibarsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static PressureChangeRate MillibarsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromMillibarsPerSecond(double.CreateChecked(value)); + => PressureChangeRate.FromMillibarsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromMillibarsPerSecond(value.ToDouble(null)); + => PressureChangeRate.FromMillibarsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static PressureChangeRate MillimetersOfMercuryPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromMillimetersOfMercuryPerSecond(double.CreateChecked(value)); + => PressureChangeRate.FromMillimetersOfMercuryPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromMillimetersOfMercuryPerSecond(value.ToDouble(null)); + => PressureChangeRate.FromMillimetersOfMercuryPerSecond(value.ToQuantityValue()); #endif - /// + /// public static PressureChangeRate PascalsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromPascalsPerMinute(double.CreateChecked(value)); + => PressureChangeRate.FromPascalsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromPascalsPerMinute(value.ToDouble(null)); + => PressureChangeRate.FromPascalsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static PressureChangeRate PascalsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromPascalsPerSecond(double.CreateChecked(value)); + => PressureChangeRate.FromPascalsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromPascalsPerSecond(value.ToDouble(null)); + => PressureChangeRate.FromPascalsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static PressureChangeRate PoundsForcePerSquareInchPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromPoundsForcePerSquareInchPerMinute(double.CreateChecked(value)); + => PressureChangeRate.FromPoundsForcePerSquareInchPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromPoundsForcePerSquareInchPerMinute(value.ToDouble(null)); + => PressureChangeRate.FromPoundsForcePerSquareInchPerMinute(value.ToQuantityValue()); #endif - /// + /// public static PressureChangeRate PoundsForcePerSquareInchPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => PressureChangeRate.FromPoundsForcePerSquareInchPerSecond(double.CreateChecked(value)); + => PressureChangeRate.FromPoundsForcePerSquareInchPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => PressureChangeRate.FromPoundsForcePerSquareInchPerSecond(value.ToDouble(null)); + => PressureChangeRate.FromPoundsForcePerSquareInchPerSecond(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToPressureExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToPressureExtensions.g.cs index b731ef1138..1734ba642b 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToPressureExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToPressureExtensions.g.cs @@ -32,532 +32,532 @@ namespace UnitsNet.NumberExtensions.NumberToPressure /// public static class NumberToPressureExtensions { - /// + /// public static Pressure Atmospheres(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromAtmospheres(double.CreateChecked(value)); + => Pressure.FromAtmospheres(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromAtmospheres(value.ToDouble(null)); + => Pressure.FromAtmospheres(value.ToQuantityValue()); #endif - /// + /// public static Pressure Bars(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromBars(double.CreateChecked(value)); + => Pressure.FromBars(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromBars(value.ToDouble(null)); + => Pressure.FromBars(value.ToQuantityValue()); #endif - /// + /// public static Pressure Centibars(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromCentibars(double.CreateChecked(value)); + => Pressure.FromCentibars(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromCentibars(value.ToDouble(null)); + => Pressure.FromCentibars(value.ToQuantityValue()); #endif - /// + /// public static Pressure CentimetersOfWaterColumn(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromCentimetersOfWaterColumn(double.CreateChecked(value)); + => Pressure.FromCentimetersOfWaterColumn(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromCentimetersOfWaterColumn(value.ToDouble(null)); + => Pressure.FromCentimetersOfWaterColumn(value.ToQuantityValue()); #endif - /// + /// public static Pressure Decapascals(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromDecapascals(double.CreateChecked(value)); + => Pressure.FromDecapascals(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromDecapascals(value.ToDouble(null)); + => Pressure.FromDecapascals(value.ToQuantityValue()); #endif - /// + /// public static Pressure Decibars(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromDecibars(double.CreateChecked(value)); + => Pressure.FromDecibars(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromDecibars(value.ToDouble(null)); + => Pressure.FromDecibars(value.ToQuantityValue()); #endif - /// + /// public static Pressure DynesPerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromDynesPerSquareCentimeter(double.CreateChecked(value)); + => Pressure.FromDynesPerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromDynesPerSquareCentimeter(value.ToDouble(null)); + => Pressure.FromDynesPerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Pressure FeetOfHead(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromFeetOfHead(double.CreateChecked(value)); + => Pressure.FromFeetOfHead(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromFeetOfHead(value.ToDouble(null)); + => Pressure.FromFeetOfHead(value.ToQuantityValue()); #endif - /// + /// public static Pressure Gigapascals(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromGigapascals(double.CreateChecked(value)); + => Pressure.FromGigapascals(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromGigapascals(value.ToDouble(null)); + => Pressure.FromGigapascals(value.ToQuantityValue()); #endif - /// + /// public static Pressure Hectopascals(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromHectopascals(double.CreateChecked(value)); + => Pressure.FromHectopascals(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromHectopascals(value.ToDouble(null)); + => Pressure.FromHectopascals(value.ToQuantityValue()); #endif - /// + /// public static Pressure InchesOfMercury(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromInchesOfMercury(double.CreateChecked(value)); + => Pressure.FromInchesOfMercury(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromInchesOfMercury(value.ToDouble(null)); + => Pressure.FromInchesOfMercury(value.ToQuantityValue()); #endif - /// + /// public static Pressure InchesOfWaterColumn(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromInchesOfWaterColumn(double.CreateChecked(value)); + => Pressure.FromInchesOfWaterColumn(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromInchesOfWaterColumn(value.ToDouble(null)); + => Pressure.FromInchesOfWaterColumn(value.ToQuantityValue()); #endif - /// + /// public static Pressure Kilobars(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromKilobars(double.CreateChecked(value)); + => Pressure.FromKilobars(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromKilobars(value.ToDouble(null)); + => Pressure.FromKilobars(value.ToQuantityValue()); #endif - /// + /// public static Pressure KilogramsForcePerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromKilogramsForcePerSquareCentimeter(double.CreateChecked(value)); + => Pressure.FromKilogramsForcePerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromKilogramsForcePerSquareCentimeter(value.ToDouble(null)); + => Pressure.FromKilogramsForcePerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Pressure KilogramsForcePerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromKilogramsForcePerSquareMeter(double.CreateChecked(value)); + => Pressure.FromKilogramsForcePerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromKilogramsForcePerSquareMeter(value.ToDouble(null)); + => Pressure.FromKilogramsForcePerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Pressure KilogramsForcePerSquareMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromKilogramsForcePerSquareMillimeter(double.CreateChecked(value)); + => Pressure.FromKilogramsForcePerSquareMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromKilogramsForcePerSquareMillimeter(value.ToDouble(null)); + => Pressure.FromKilogramsForcePerSquareMillimeter(value.ToQuantityValue()); #endif - /// + /// public static Pressure KilonewtonsPerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromKilonewtonsPerSquareCentimeter(double.CreateChecked(value)); + => Pressure.FromKilonewtonsPerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromKilonewtonsPerSquareCentimeter(value.ToDouble(null)); + => Pressure.FromKilonewtonsPerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Pressure KilonewtonsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromKilonewtonsPerSquareMeter(double.CreateChecked(value)); + => Pressure.FromKilonewtonsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromKilonewtonsPerSquareMeter(value.ToDouble(null)); + => Pressure.FromKilonewtonsPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Pressure KilonewtonsPerSquareMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromKilonewtonsPerSquareMillimeter(double.CreateChecked(value)); + => Pressure.FromKilonewtonsPerSquareMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromKilonewtonsPerSquareMillimeter(value.ToDouble(null)); + => Pressure.FromKilonewtonsPerSquareMillimeter(value.ToQuantityValue()); #endif - /// + /// public static Pressure Kilopascals(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromKilopascals(double.CreateChecked(value)); + => Pressure.FromKilopascals(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromKilopascals(value.ToDouble(null)); + => Pressure.FromKilopascals(value.ToQuantityValue()); #endif - /// + /// public static Pressure KilopoundsForcePerSquareFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromKilopoundsForcePerSquareFoot(double.CreateChecked(value)); + => Pressure.FromKilopoundsForcePerSquareFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromKilopoundsForcePerSquareFoot(value.ToDouble(null)); + => Pressure.FromKilopoundsForcePerSquareFoot(value.ToQuantityValue()); #endif - /// + /// public static Pressure KilopoundsForcePerSquareInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromKilopoundsForcePerSquareInch(double.CreateChecked(value)); + => Pressure.FromKilopoundsForcePerSquareInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromKilopoundsForcePerSquareInch(value.ToDouble(null)); + => Pressure.FromKilopoundsForcePerSquareInch(value.ToQuantityValue()); #endif - /// + /// public static Pressure KilopoundsForcePerSquareMil(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromKilopoundsForcePerSquareMil(double.CreateChecked(value)); + => Pressure.FromKilopoundsForcePerSquareMil(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromKilopoundsForcePerSquareMil(value.ToDouble(null)); + => Pressure.FromKilopoundsForcePerSquareMil(value.ToQuantityValue()); #endif - /// + /// public static Pressure Megabars(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromMegabars(double.CreateChecked(value)); + => Pressure.FromMegabars(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromMegabars(value.ToDouble(null)); + => Pressure.FromMegabars(value.ToQuantityValue()); #endif - /// + /// public static Pressure MeganewtonsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromMeganewtonsPerSquareMeter(double.CreateChecked(value)); + => Pressure.FromMeganewtonsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromMeganewtonsPerSquareMeter(value.ToDouble(null)); + => Pressure.FromMeganewtonsPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Pressure Megapascals(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromMegapascals(double.CreateChecked(value)); + => Pressure.FromMegapascals(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromMegapascals(value.ToDouble(null)); + => Pressure.FromMegapascals(value.ToQuantityValue()); #endif - /// + /// public static Pressure MetersOfHead(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromMetersOfHead(double.CreateChecked(value)); + => Pressure.FromMetersOfHead(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromMetersOfHead(value.ToDouble(null)); + => Pressure.FromMetersOfHead(value.ToQuantityValue()); #endif - /// + /// public static Pressure MetersOfWaterColumn(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromMetersOfWaterColumn(double.CreateChecked(value)); + => Pressure.FromMetersOfWaterColumn(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromMetersOfWaterColumn(value.ToDouble(null)); + => Pressure.FromMetersOfWaterColumn(value.ToQuantityValue()); #endif - /// + /// public static Pressure Microbars(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromMicrobars(double.CreateChecked(value)); + => Pressure.FromMicrobars(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromMicrobars(value.ToDouble(null)); + => Pressure.FromMicrobars(value.ToQuantityValue()); #endif - /// + /// public static Pressure Micropascals(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromMicropascals(double.CreateChecked(value)); + => Pressure.FromMicropascals(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromMicropascals(value.ToDouble(null)); + => Pressure.FromMicropascals(value.ToQuantityValue()); #endif - /// + /// public static Pressure Millibars(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromMillibars(double.CreateChecked(value)); + => Pressure.FromMillibars(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromMillibars(value.ToDouble(null)); + => Pressure.FromMillibars(value.ToQuantityValue()); #endif - /// + /// public static Pressure MillimetersOfMercury(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromMillimetersOfMercury(double.CreateChecked(value)); + => Pressure.FromMillimetersOfMercury(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromMillimetersOfMercury(value.ToDouble(null)); + => Pressure.FromMillimetersOfMercury(value.ToQuantityValue()); #endif - /// + /// public static Pressure MillimetersOfWaterColumn(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromMillimetersOfWaterColumn(double.CreateChecked(value)); + => Pressure.FromMillimetersOfWaterColumn(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromMillimetersOfWaterColumn(value.ToDouble(null)); + => Pressure.FromMillimetersOfWaterColumn(value.ToQuantityValue()); #endif - /// + /// public static Pressure Millipascals(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromMillipascals(double.CreateChecked(value)); + => Pressure.FromMillipascals(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromMillipascals(value.ToDouble(null)); + => Pressure.FromMillipascals(value.ToQuantityValue()); #endif - /// + /// public static Pressure Millitorrs(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromMillitorrs(double.CreateChecked(value)); + => Pressure.FromMillitorrs(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromMillitorrs(value.ToDouble(null)); + => Pressure.FromMillitorrs(value.ToQuantityValue()); #endif - /// + /// public static Pressure NewtonsPerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromNewtonsPerSquareCentimeter(double.CreateChecked(value)); + => Pressure.FromNewtonsPerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromNewtonsPerSquareCentimeter(value.ToDouble(null)); + => Pressure.FromNewtonsPerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Pressure NewtonsPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromNewtonsPerSquareMeter(double.CreateChecked(value)); + => Pressure.FromNewtonsPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromNewtonsPerSquareMeter(value.ToDouble(null)); + => Pressure.FromNewtonsPerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Pressure NewtonsPerSquareMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromNewtonsPerSquareMillimeter(double.CreateChecked(value)); + => Pressure.FromNewtonsPerSquareMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromNewtonsPerSquareMillimeter(value.ToDouble(null)); + => Pressure.FromNewtonsPerSquareMillimeter(value.ToQuantityValue()); #endif - /// + /// public static Pressure Pascals(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromPascals(double.CreateChecked(value)); + => Pressure.FromPascals(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromPascals(value.ToDouble(null)); + => Pressure.FromPascals(value.ToQuantityValue()); #endif - /// + /// public static Pressure PoundsForcePerSquareFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromPoundsForcePerSquareFoot(double.CreateChecked(value)); + => Pressure.FromPoundsForcePerSquareFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromPoundsForcePerSquareFoot(value.ToDouble(null)); + => Pressure.FromPoundsForcePerSquareFoot(value.ToQuantityValue()); #endif - /// + /// public static Pressure PoundsForcePerSquareInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromPoundsForcePerSquareInch(double.CreateChecked(value)); + => Pressure.FromPoundsForcePerSquareInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromPoundsForcePerSquareInch(value.ToDouble(null)); + => Pressure.FromPoundsForcePerSquareInch(value.ToQuantityValue()); #endif - /// + /// public static Pressure PoundsForcePerSquareMil(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromPoundsForcePerSquareMil(double.CreateChecked(value)); + => Pressure.FromPoundsForcePerSquareMil(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromPoundsForcePerSquareMil(value.ToDouble(null)); + => Pressure.FromPoundsForcePerSquareMil(value.ToQuantityValue()); #endif - /// + /// public static Pressure PoundsPerInchSecondSquared(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromPoundsPerInchSecondSquared(double.CreateChecked(value)); + => Pressure.FromPoundsPerInchSecondSquared(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromPoundsPerInchSecondSquared(value.ToDouble(null)); + => Pressure.FromPoundsPerInchSecondSquared(value.ToQuantityValue()); #endif - /// + /// public static Pressure TechnicalAtmospheres(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromTechnicalAtmospheres(double.CreateChecked(value)); + => Pressure.FromTechnicalAtmospheres(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromTechnicalAtmospheres(value.ToDouble(null)); + => Pressure.FromTechnicalAtmospheres(value.ToQuantityValue()); #endif - /// + /// public static Pressure TonnesForcePerSquareCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromTonnesForcePerSquareCentimeter(double.CreateChecked(value)); + => Pressure.FromTonnesForcePerSquareCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromTonnesForcePerSquareCentimeter(value.ToDouble(null)); + => Pressure.FromTonnesForcePerSquareCentimeter(value.ToQuantityValue()); #endif - /// + /// public static Pressure TonnesForcePerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromTonnesForcePerSquareMeter(double.CreateChecked(value)); + => Pressure.FromTonnesForcePerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromTonnesForcePerSquareMeter(value.ToDouble(null)); + => Pressure.FromTonnesForcePerSquareMeter(value.ToQuantityValue()); #endif - /// + /// public static Pressure TonnesForcePerSquareMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromTonnesForcePerSquareMillimeter(double.CreateChecked(value)); + => Pressure.FromTonnesForcePerSquareMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromTonnesForcePerSquareMillimeter(value.ToDouble(null)); + => Pressure.FromTonnesForcePerSquareMillimeter(value.ToQuantityValue()); #endif - /// + /// public static Pressure Torrs(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Pressure.FromTorrs(double.CreateChecked(value)); + => Pressure.FromTorrs(QuantityValue.CreateChecked(value)); #else , IConvertible - => Pressure.FromTorrs(value.ToDouble(null)); + => Pressure.FromTorrs(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRadiationEquivalentDoseExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRadiationEquivalentDoseExtensions.g.cs index e86c930c83..1c5eb87336 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRadiationEquivalentDoseExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRadiationEquivalentDoseExtensions.g.cs @@ -32,70 +32,70 @@ namespace UnitsNet.NumberExtensions.NumberToRadiationEquivalentDose /// public static class NumberToRadiationEquivalentDoseExtensions { - /// + /// public static RadiationEquivalentDose Microsieverts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationEquivalentDose.FromMicrosieverts(double.CreateChecked(value)); + => RadiationEquivalentDose.FromMicrosieverts(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationEquivalentDose.FromMicrosieverts(value.ToDouble(null)); + => RadiationEquivalentDose.FromMicrosieverts(value.ToQuantityValue()); #endif - /// + /// public static RadiationEquivalentDose MilliroentgensEquivalentMan(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationEquivalentDose.FromMilliroentgensEquivalentMan(double.CreateChecked(value)); + => RadiationEquivalentDose.FromMilliroentgensEquivalentMan(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationEquivalentDose.FromMilliroentgensEquivalentMan(value.ToDouble(null)); + => RadiationEquivalentDose.FromMilliroentgensEquivalentMan(value.ToQuantityValue()); #endif - /// + /// public static RadiationEquivalentDose Millisieverts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationEquivalentDose.FromMillisieverts(double.CreateChecked(value)); + => RadiationEquivalentDose.FromMillisieverts(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationEquivalentDose.FromMillisieverts(value.ToDouble(null)); + => RadiationEquivalentDose.FromMillisieverts(value.ToQuantityValue()); #endif - /// + /// public static RadiationEquivalentDose Nanosieverts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationEquivalentDose.FromNanosieverts(double.CreateChecked(value)); + => RadiationEquivalentDose.FromNanosieverts(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationEquivalentDose.FromNanosieverts(value.ToDouble(null)); + => RadiationEquivalentDose.FromNanosieverts(value.ToQuantityValue()); #endif - /// + /// public static RadiationEquivalentDose RoentgensEquivalentMan(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationEquivalentDose.FromRoentgensEquivalentMan(double.CreateChecked(value)); + => RadiationEquivalentDose.FromRoentgensEquivalentMan(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationEquivalentDose.FromRoentgensEquivalentMan(value.ToDouble(null)); + => RadiationEquivalentDose.FromRoentgensEquivalentMan(value.ToQuantityValue()); #endif - /// + /// public static RadiationEquivalentDose Sieverts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationEquivalentDose.FromSieverts(double.CreateChecked(value)); + => RadiationEquivalentDose.FromSieverts(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationEquivalentDose.FromSieverts(value.ToDouble(null)); + => RadiationEquivalentDose.FromSieverts(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRadiationEquivalentDoseRateExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRadiationEquivalentDoseRateExtensions.g.cs index c0c03ea347..1d6f43c731 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRadiationEquivalentDoseRateExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRadiationEquivalentDoseRateExtensions.g.cs @@ -32,114 +32,114 @@ namespace UnitsNet.NumberExtensions.NumberToRadiationEquivalentDoseRate /// public static class NumberToRadiationEquivalentDoseRateExtensions { - /// + /// public static RadiationEquivalentDoseRate MicrosievertsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationEquivalentDoseRate.FromMicrosievertsPerHour(double.CreateChecked(value)); + => RadiationEquivalentDoseRate.FromMicrosievertsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationEquivalentDoseRate.FromMicrosievertsPerHour(value.ToDouble(null)); + => RadiationEquivalentDoseRate.FromMicrosievertsPerHour(value.ToQuantityValue()); #endif - /// + /// public static RadiationEquivalentDoseRate MicrosievertsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationEquivalentDoseRate.FromMicrosievertsPerSecond(double.CreateChecked(value)); + => RadiationEquivalentDoseRate.FromMicrosievertsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationEquivalentDoseRate.FromMicrosievertsPerSecond(value.ToDouble(null)); + => RadiationEquivalentDoseRate.FromMicrosievertsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static RadiationEquivalentDoseRate MilliroentgensEquivalentManPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationEquivalentDoseRate.FromMilliroentgensEquivalentManPerHour(double.CreateChecked(value)); + => RadiationEquivalentDoseRate.FromMilliroentgensEquivalentManPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationEquivalentDoseRate.FromMilliroentgensEquivalentManPerHour(value.ToDouble(null)); + => RadiationEquivalentDoseRate.FromMilliroentgensEquivalentManPerHour(value.ToQuantityValue()); #endif - /// + /// public static RadiationEquivalentDoseRate MillisievertsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationEquivalentDoseRate.FromMillisievertsPerHour(double.CreateChecked(value)); + => RadiationEquivalentDoseRate.FromMillisievertsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationEquivalentDoseRate.FromMillisievertsPerHour(value.ToDouble(null)); + => RadiationEquivalentDoseRate.FromMillisievertsPerHour(value.ToQuantityValue()); #endif - /// + /// public static RadiationEquivalentDoseRate MillisievertsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationEquivalentDoseRate.FromMillisievertsPerSecond(double.CreateChecked(value)); + => RadiationEquivalentDoseRate.FromMillisievertsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationEquivalentDoseRate.FromMillisievertsPerSecond(value.ToDouble(null)); + => RadiationEquivalentDoseRate.FromMillisievertsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static RadiationEquivalentDoseRate NanosievertsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationEquivalentDoseRate.FromNanosievertsPerHour(double.CreateChecked(value)); + => RadiationEquivalentDoseRate.FromNanosievertsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationEquivalentDoseRate.FromNanosievertsPerHour(value.ToDouble(null)); + => RadiationEquivalentDoseRate.FromNanosievertsPerHour(value.ToQuantityValue()); #endif - /// + /// public static RadiationEquivalentDoseRate NanosievertsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationEquivalentDoseRate.FromNanosievertsPerSecond(double.CreateChecked(value)); + => RadiationEquivalentDoseRate.FromNanosievertsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationEquivalentDoseRate.FromNanosievertsPerSecond(value.ToDouble(null)); + => RadiationEquivalentDoseRate.FromNanosievertsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static RadiationEquivalentDoseRate RoentgensEquivalentManPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationEquivalentDoseRate.FromRoentgensEquivalentManPerHour(double.CreateChecked(value)); + => RadiationEquivalentDoseRate.FromRoentgensEquivalentManPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationEquivalentDoseRate.FromRoentgensEquivalentManPerHour(value.ToDouble(null)); + => RadiationEquivalentDoseRate.FromRoentgensEquivalentManPerHour(value.ToQuantityValue()); #endif - /// + /// public static RadiationEquivalentDoseRate SievertsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationEquivalentDoseRate.FromSievertsPerHour(double.CreateChecked(value)); + => RadiationEquivalentDoseRate.FromSievertsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationEquivalentDoseRate.FromSievertsPerHour(value.ToDouble(null)); + => RadiationEquivalentDoseRate.FromSievertsPerHour(value.ToQuantityValue()); #endif - /// + /// public static RadiationEquivalentDoseRate SievertsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationEquivalentDoseRate.FromSievertsPerSecond(double.CreateChecked(value)); + => RadiationEquivalentDoseRate.FromSievertsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationEquivalentDoseRate.FromSievertsPerSecond(value.ToDouble(null)); + => RadiationEquivalentDoseRate.FromSievertsPerSecond(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRadiationExposureExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRadiationExposureExtensions.g.cs index 001ea47db6..adcb0dd5ae 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRadiationExposureExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRadiationExposureExtensions.g.cs @@ -32,92 +32,92 @@ namespace UnitsNet.NumberExtensions.NumberToRadiationExposure /// public static class NumberToRadiationExposureExtensions { - /// + /// public static RadiationExposure CoulombsPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationExposure.FromCoulombsPerKilogram(double.CreateChecked(value)); + => RadiationExposure.FromCoulombsPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationExposure.FromCoulombsPerKilogram(value.ToDouble(null)); + => RadiationExposure.FromCoulombsPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static RadiationExposure MicrocoulombsPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationExposure.FromMicrocoulombsPerKilogram(double.CreateChecked(value)); + => RadiationExposure.FromMicrocoulombsPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationExposure.FromMicrocoulombsPerKilogram(value.ToDouble(null)); + => RadiationExposure.FromMicrocoulombsPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static RadiationExposure Microroentgens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationExposure.FromMicroroentgens(double.CreateChecked(value)); + => RadiationExposure.FromMicroroentgens(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationExposure.FromMicroroentgens(value.ToDouble(null)); + => RadiationExposure.FromMicroroentgens(value.ToQuantityValue()); #endif - /// + /// public static RadiationExposure MillicoulombsPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationExposure.FromMillicoulombsPerKilogram(double.CreateChecked(value)); + => RadiationExposure.FromMillicoulombsPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationExposure.FromMillicoulombsPerKilogram(value.ToDouble(null)); + => RadiationExposure.FromMillicoulombsPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static RadiationExposure Milliroentgens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationExposure.FromMilliroentgens(double.CreateChecked(value)); + => RadiationExposure.FromMilliroentgens(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationExposure.FromMilliroentgens(value.ToDouble(null)); + => RadiationExposure.FromMilliroentgens(value.ToQuantityValue()); #endif - /// + /// public static RadiationExposure NanocoulombsPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationExposure.FromNanocoulombsPerKilogram(double.CreateChecked(value)); + => RadiationExposure.FromNanocoulombsPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationExposure.FromNanocoulombsPerKilogram(value.ToDouble(null)); + => RadiationExposure.FromNanocoulombsPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static RadiationExposure PicocoulombsPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationExposure.FromPicocoulombsPerKilogram(double.CreateChecked(value)); + => RadiationExposure.FromPicocoulombsPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationExposure.FromPicocoulombsPerKilogram(value.ToDouble(null)); + => RadiationExposure.FromPicocoulombsPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static RadiationExposure Roentgens(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RadiationExposure.FromRoentgens(double.CreateChecked(value)); + => RadiationExposure.FromRoentgens(QuantityValue.CreateChecked(value)); #else , IConvertible - => RadiationExposure.FromRoentgens(value.ToDouble(null)); + => RadiationExposure.FromRoentgens(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRadioactivityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRadioactivityExtensions.g.cs index f9c6f632ac..c4021baa64 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRadioactivityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRadioactivityExtensions.g.cs @@ -32,323 +32,323 @@ namespace UnitsNet.NumberExtensions.NumberToRadioactivity /// public static class NumberToRadioactivityExtensions { - /// + /// public static Radioactivity Becquerels(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromBecquerels(double.CreateChecked(value)); + => Radioactivity.FromBecquerels(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromBecquerels(value.ToDouble(null)); + => Radioactivity.FromBecquerels(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Curies(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromCuries(double.CreateChecked(value)); + => Radioactivity.FromCuries(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromCuries(value.ToDouble(null)); + => Radioactivity.FromCuries(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Exabecquerels(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromExabecquerels(double.CreateChecked(value)); + => Radioactivity.FromExabecquerels(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromExabecquerels(value.ToDouble(null)); + => Radioactivity.FromExabecquerels(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Gigabecquerels(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromGigabecquerels(double.CreateChecked(value)); + => Radioactivity.FromGigabecquerels(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromGigabecquerels(value.ToDouble(null)); + => Radioactivity.FromGigabecquerels(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Gigacuries(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromGigacuries(double.CreateChecked(value)); + => Radioactivity.FromGigacuries(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromGigacuries(value.ToDouble(null)); + => Radioactivity.FromGigacuries(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Gigarutherfords(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromGigarutherfords(double.CreateChecked(value)); + => Radioactivity.FromGigarutherfords(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromGigarutherfords(value.ToDouble(null)); + => Radioactivity.FromGigarutherfords(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Kilobecquerels(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromKilobecquerels(double.CreateChecked(value)); + => Radioactivity.FromKilobecquerels(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromKilobecquerels(value.ToDouble(null)); + => Radioactivity.FromKilobecquerels(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Kilocuries(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromKilocuries(double.CreateChecked(value)); + => Radioactivity.FromKilocuries(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromKilocuries(value.ToDouble(null)); + => Radioactivity.FromKilocuries(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Kilorutherfords(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromKilorutherfords(double.CreateChecked(value)); + => Radioactivity.FromKilorutherfords(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromKilorutherfords(value.ToDouble(null)); + => Radioactivity.FromKilorutherfords(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Megabecquerels(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromMegabecquerels(double.CreateChecked(value)); + => Radioactivity.FromMegabecquerels(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromMegabecquerels(value.ToDouble(null)); + => Radioactivity.FromMegabecquerels(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Megacuries(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromMegacuries(double.CreateChecked(value)); + => Radioactivity.FromMegacuries(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromMegacuries(value.ToDouble(null)); + => Radioactivity.FromMegacuries(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Megarutherfords(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromMegarutherfords(double.CreateChecked(value)); + => Radioactivity.FromMegarutherfords(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromMegarutherfords(value.ToDouble(null)); + => Radioactivity.FromMegarutherfords(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Microbecquerels(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromMicrobecquerels(double.CreateChecked(value)); + => Radioactivity.FromMicrobecquerels(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromMicrobecquerels(value.ToDouble(null)); + => Radioactivity.FromMicrobecquerels(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Microcuries(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromMicrocuries(double.CreateChecked(value)); + => Radioactivity.FromMicrocuries(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromMicrocuries(value.ToDouble(null)); + => Radioactivity.FromMicrocuries(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Microrutherfords(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromMicrorutherfords(double.CreateChecked(value)); + => Radioactivity.FromMicrorutherfords(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromMicrorutherfords(value.ToDouble(null)); + => Radioactivity.FromMicrorutherfords(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Millibecquerels(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromMillibecquerels(double.CreateChecked(value)); + => Radioactivity.FromMillibecquerels(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromMillibecquerels(value.ToDouble(null)); + => Radioactivity.FromMillibecquerels(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Millicuries(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromMillicuries(double.CreateChecked(value)); + => Radioactivity.FromMillicuries(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromMillicuries(value.ToDouble(null)); + => Radioactivity.FromMillicuries(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Millirutherfords(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromMillirutherfords(double.CreateChecked(value)); + => Radioactivity.FromMillirutherfords(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromMillirutherfords(value.ToDouble(null)); + => Radioactivity.FromMillirutherfords(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Nanobecquerels(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromNanobecquerels(double.CreateChecked(value)); + => Radioactivity.FromNanobecquerels(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromNanobecquerels(value.ToDouble(null)); + => Radioactivity.FromNanobecquerels(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Nanocuries(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromNanocuries(double.CreateChecked(value)); + => Radioactivity.FromNanocuries(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromNanocuries(value.ToDouble(null)); + => Radioactivity.FromNanocuries(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Nanorutherfords(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromNanorutherfords(double.CreateChecked(value)); + => Radioactivity.FromNanorutherfords(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromNanorutherfords(value.ToDouble(null)); + => Radioactivity.FromNanorutherfords(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Petabecquerels(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromPetabecquerels(double.CreateChecked(value)); + => Radioactivity.FromPetabecquerels(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromPetabecquerels(value.ToDouble(null)); + => Radioactivity.FromPetabecquerels(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Picobecquerels(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromPicobecquerels(double.CreateChecked(value)); + => Radioactivity.FromPicobecquerels(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromPicobecquerels(value.ToDouble(null)); + => Radioactivity.FromPicobecquerels(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Picocuries(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromPicocuries(double.CreateChecked(value)); + => Radioactivity.FromPicocuries(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromPicocuries(value.ToDouble(null)); + => Radioactivity.FromPicocuries(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Picorutherfords(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromPicorutherfords(double.CreateChecked(value)); + => Radioactivity.FromPicorutherfords(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromPicorutherfords(value.ToDouble(null)); + => Radioactivity.FromPicorutherfords(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Rutherfords(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromRutherfords(double.CreateChecked(value)); + => Radioactivity.FromRutherfords(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromRutherfords(value.ToDouble(null)); + => Radioactivity.FromRutherfords(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Terabecquerels(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromTerabecquerels(double.CreateChecked(value)); + => Radioactivity.FromTerabecquerels(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromTerabecquerels(value.ToDouble(null)); + => Radioactivity.FromTerabecquerels(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Teracuries(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromTeracuries(double.CreateChecked(value)); + => Radioactivity.FromTeracuries(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromTeracuries(value.ToDouble(null)); + => Radioactivity.FromTeracuries(value.ToQuantityValue()); #endif - /// + /// public static Radioactivity Terarutherfords(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Radioactivity.FromTerarutherfords(double.CreateChecked(value)); + => Radioactivity.FromTerarutherfords(QuantityValue.CreateChecked(value)); #else , IConvertible - => Radioactivity.FromTerarutherfords(value.ToDouble(null)); + => Radioactivity.FromTerarutherfords(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRatioChangeRateExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRatioChangeRateExtensions.g.cs index 535a410298..d1ffec7a31 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRatioChangeRateExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRatioChangeRateExtensions.g.cs @@ -32,26 +32,26 @@ namespace UnitsNet.NumberExtensions.NumberToRatioChangeRate /// public static class NumberToRatioChangeRateExtensions { - /// + /// public static RatioChangeRate DecimalFractionsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RatioChangeRate.FromDecimalFractionsPerSecond(double.CreateChecked(value)); + => RatioChangeRate.FromDecimalFractionsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RatioChangeRate.FromDecimalFractionsPerSecond(value.ToDouble(null)); + => RatioChangeRate.FromDecimalFractionsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static RatioChangeRate PercentsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RatioChangeRate.FromPercentsPerSecond(double.CreateChecked(value)); + => RatioChangeRate.FromPercentsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RatioChangeRate.FromPercentsPerSecond(value.ToDouble(null)); + => RatioChangeRate.FromPercentsPerSecond(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRatioExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRatioExtensions.g.cs index ce070b42a0..197232eea4 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRatioExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRatioExtensions.g.cs @@ -32,70 +32,70 @@ namespace UnitsNet.NumberExtensions.NumberToRatio /// public static class NumberToRatioExtensions { - /// + /// public static Ratio DecimalFractions(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Ratio.FromDecimalFractions(double.CreateChecked(value)); + => Ratio.FromDecimalFractions(QuantityValue.CreateChecked(value)); #else , IConvertible - => Ratio.FromDecimalFractions(value.ToDouble(null)); + => Ratio.FromDecimalFractions(value.ToQuantityValue()); #endif - /// + /// public static Ratio PartsPerBillion(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Ratio.FromPartsPerBillion(double.CreateChecked(value)); + => Ratio.FromPartsPerBillion(QuantityValue.CreateChecked(value)); #else , IConvertible - => Ratio.FromPartsPerBillion(value.ToDouble(null)); + => Ratio.FromPartsPerBillion(value.ToQuantityValue()); #endif - /// + /// public static Ratio PartsPerMillion(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Ratio.FromPartsPerMillion(double.CreateChecked(value)); + => Ratio.FromPartsPerMillion(QuantityValue.CreateChecked(value)); #else , IConvertible - => Ratio.FromPartsPerMillion(value.ToDouble(null)); + => Ratio.FromPartsPerMillion(value.ToQuantityValue()); #endif - /// + /// public static Ratio PartsPerThousand(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Ratio.FromPartsPerThousand(double.CreateChecked(value)); + => Ratio.FromPartsPerThousand(QuantityValue.CreateChecked(value)); #else , IConvertible - => Ratio.FromPartsPerThousand(value.ToDouble(null)); + => Ratio.FromPartsPerThousand(value.ToQuantityValue()); #endif - /// + /// public static Ratio PartsPerTrillion(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Ratio.FromPartsPerTrillion(double.CreateChecked(value)); + => Ratio.FromPartsPerTrillion(QuantityValue.CreateChecked(value)); #else , IConvertible - => Ratio.FromPartsPerTrillion(value.ToDouble(null)); + => Ratio.FromPartsPerTrillion(value.ToQuantityValue()); #endif - /// + /// public static Ratio Percent(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Ratio.FromPercent(double.CreateChecked(value)); + => Ratio.FromPercent(QuantityValue.CreateChecked(value)); #else , IConvertible - => Ratio.FromPercent(value.ToDouble(null)); + => Ratio.FromPercent(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToReciprocalAreaExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToReciprocalAreaExtensions.g.cs index 9ab826de36..6316ad09c8 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToReciprocalAreaExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToReciprocalAreaExtensions.g.cs @@ -32,125 +32,125 @@ namespace UnitsNet.NumberExtensions.NumberToReciprocalArea /// public static class NumberToReciprocalAreaExtensions { - /// + /// public static ReciprocalArea InverseSquareCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalArea.FromInverseSquareCentimeters(double.CreateChecked(value)); + => ReciprocalArea.FromInverseSquareCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalArea.FromInverseSquareCentimeters(value.ToDouble(null)); + => ReciprocalArea.FromInverseSquareCentimeters(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalArea InverseSquareDecimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalArea.FromInverseSquareDecimeters(double.CreateChecked(value)); + => ReciprocalArea.FromInverseSquareDecimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalArea.FromInverseSquareDecimeters(value.ToDouble(null)); + => ReciprocalArea.FromInverseSquareDecimeters(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalArea InverseSquareFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalArea.FromInverseSquareFeet(double.CreateChecked(value)); + => ReciprocalArea.FromInverseSquareFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalArea.FromInverseSquareFeet(value.ToDouble(null)); + => ReciprocalArea.FromInverseSquareFeet(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalArea InverseSquareInches(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalArea.FromInverseSquareInches(double.CreateChecked(value)); + => ReciprocalArea.FromInverseSquareInches(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalArea.FromInverseSquareInches(value.ToDouble(null)); + => ReciprocalArea.FromInverseSquareInches(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalArea InverseSquareKilometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalArea.FromInverseSquareKilometers(double.CreateChecked(value)); + => ReciprocalArea.FromInverseSquareKilometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalArea.FromInverseSquareKilometers(value.ToDouble(null)); + => ReciprocalArea.FromInverseSquareKilometers(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalArea InverseSquareMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalArea.FromInverseSquareMeters(double.CreateChecked(value)); + => ReciprocalArea.FromInverseSquareMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalArea.FromInverseSquareMeters(value.ToDouble(null)); + => ReciprocalArea.FromInverseSquareMeters(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalArea InverseSquareMicrometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalArea.FromInverseSquareMicrometers(double.CreateChecked(value)); + => ReciprocalArea.FromInverseSquareMicrometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalArea.FromInverseSquareMicrometers(value.ToDouble(null)); + => ReciprocalArea.FromInverseSquareMicrometers(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalArea InverseSquareMiles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalArea.FromInverseSquareMiles(double.CreateChecked(value)); + => ReciprocalArea.FromInverseSquareMiles(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalArea.FromInverseSquareMiles(value.ToDouble(null)); + => ReciprocalArea.FromInverseSquareMiles(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalArea InverseSquareMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalArea.FromInverseSquareMillimeters(double.CreateChecked(value)); + => ReciprocalArea.FromInverseSquareMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalArea.FromInverseSquareMillimeters(value.ToDouble(null)); + => ReciprocalArea.FromInverseSquareMillimeters(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalArea InverseSquareYards(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalArea.FromInverseSquareYards(double.CreateChecked(value)); + => ReciprocalArea.FromInverseSquareYards(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalArea.FromInverseSquareYards(value.ToDouble(null)); + => ReciprocalArea.FromInverseSquareYards(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalArea InverseUsSurveySquareFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalArea.FromInverseUsSurveySquareFeet(double.CreateChecked(value)); + => ReciprocalArea.FromInverseUsSurveySquareFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalArea.FromInverseUsSurveySquareFeet(value.ToDouble(null)); + => ReciprocalArea.FromInverseUsSurveySquareFeet(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToReciprocalLengthExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToReciprocalLengthExtensions.g.cs index 2023c853fa..8d47f7f26d 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToReciprocalLengthExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToReciprocalLengthExtensions.g.cs @@ -32,114 +32,114 @@ namespace UnitsNet.NumberExtensions.NumberToReciprocalLength /// public static class NumberToReciprocalLengthExtensions { - /// + /// public static ReciprocalLength InverseCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalLength.FromInverseCentimeters(double.CreateChecked(value)); + => ReciprocalLength.FromInverseCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalLength.FromInverseCentimeters(value.ToDouble(null)); + => ReciprocalLength.FromInverseCentimeters(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalLength InverseFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalLength.FromInverseFeet(double.CreateChecked(value)); + => ReciprocalLength.FromInverseFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalLength.FromInverseFeet(value.ToDouble(null)); + => ReciprocalLength.FromInverseFeet(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalLength InverseInches(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalLength.FromInverseInches(double.CreateChecked(value)); + => ReciprocalLength.FromInverseInches(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalLength.FromInverseInches(value.ToDouble(null)); + => ReciprocalLength.FromInverseInches(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalLength InverseMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalLength.FromInverseMeters(double.CreateChecked(value)); + => ReciprocalLength.FromInverseMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalLength.FromInverseMeters(value.ToDouble(null)); + => ReciprocalLength.FromInverseMeters(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalLength InverseMicroinches(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalLength.FromInverseMicroinches(double.CreateChecked(value)); + => ReciprocalLength.FromInverseMicroinches(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalLength.FromInverseMicroinches(value.ToDouble(null)); + => ReciprocalLength.FromInverseMicroinches(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalLength InverseMils(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalLength.FromInverseMils(double.CreateChecked(value)); + => ReciprocalLength.FromInverseMils(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalLength.FromInverseMils(value.ToDouble(null)); + => ReciprocalLength.FromInverseMils(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalLength InverseMiles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalLength.FromInverseMiles(double.CreateChecked(value)); + => ReciprocalLength.FromInverseMiles(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalLength.FromInverseMiles(value.ToDouble(null)); + => ReciprocalLength.FromInverseMiles(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalLength InverseMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalLength.FromInverseMillimeters(double.CreateChecked(value)); + => ReciprocalLength.FromInverseMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalLength.FromInverseMillimeters(value.ToDouble(null)); + => ReciprocalLength.FromInverseMillimeters(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalLength InverseUsSurveyFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalLength.FromInverseUsSurveyFeet(double.CreateChecked(value)); + => ReciprocalLength.FromInverseUsSurveyFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalLength.FromInverseUsSurveyFeet(value.ToDouble(null)); + => ReciprocalLength.FromInverseUsSurveyFeet(value.ToQuantityValue()); #endif - /// + /// public static ReciprocalLength InverseYards(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ReciprocalLength.FromInverseYards(double.CreateChecked(value)); + => ReciprocalLength.FromInverseYards(QuantityValue.CreateChecked(value)); #else , IConvertible - => ReciprocalLength.FromInverseYards(value.ToDouble(null)); + => ReciprocalLength.FromInverseYards(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRelativeHumidityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRelativeHumidityExtensions.g.cs index c512c9d2eb..8db70b9d33 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRelativeHumidityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRelativeHumidityExtensions.g.cs @@ -32,15 +32,15 @@ namespace UnitsNet.NumberExtensions.NumberToRelativeHumidity /// public static class NumberToRelativeHumidityExtensions { - /// + /// public static RelativeHumidity Percent(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RelativeHumidity.FromPercent(double.CreateChecked(value)); + => RelativeHumidity.FromPercent(QuantityValue.CreateChecked(value)); #else , IConvertible - => RelativeHumidity.FromPercent(value.ToDouble(null)); + => RelativeHumidity.FromPercent(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRotationalAccelerationExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRotationalAccelerationExtensions.g.cs index d20ff97a15..da7d9664bd 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRotationalAccelerationExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRotationalAccelerationExtensions.g.cs @@ -32,48 +32,48 @@ namespace UnitsNet.NumberExtensions.NumberToRotationalAcceleration /// public static class NumberToRotationalAccelerationExtensions { - /// + /// public static RotationalAcceleration DegreesPerSecondSquared(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalAcceleration.FromDegreesPerSecondSquared(double.CreateChecked(value)); + => RotationalAcceleration.FromDegreesPerSecondSquared(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalAcceleration.FromDegreesPerSecondSquared(value.ToDouble(null)); + => RotationalAcceleration.FromDegreesPerSecondSquared(value.ToQuantityValue()); #endif - /// + /// public static RotationalAcceleration RadiansPerSecondSquared(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalAcceleration.FromRadiansPerSecondSquared(double.CreateChecked(value)); + => RotationalAcceleration.FromRadiansPerSecondSquared(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalAcceleration.FromRadiansPerSecondSquared(value.ToDouble(null)); + => RotationalAcceleration.FromRadiansPerSecondSquared(value.ToQuantityValue()); #endif - /// + /// public static RotationalAcceleration RevolutionsPerMinutePerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalAcceleration.FromRevolutionsPerMinutePerSecond(double.CreateChecked(value)); + => RotationalAcceleration.FromRevolutionsPerMinutePerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalAcceleration.FromRevolutionsPerMinutePerSecond(value.ToDouble(null)); + => RotationalAcceleration.FromRevolutionsPerMinutePerSecond(value.ToQuantityValue()); #endif - /// + /// public static RotationalAcceleration RevolutionsPerSecondSquared(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalAcceleration.FromRevolutionsPerSecondSquared(double.CreateChecked(value)); + => RotationalAcceleration.FromRevolutionsPerSecondSquared(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalAcceleration.FromRevolutionsPerSecondSquared(value.ToDouble(null)); + => RotationalAcceleration.FromRevolutionsPerSecondSquared(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRotationalSpeedExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRotationalSpeedExtensions.g.cs index e49a4938a1..81ff773006 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRotationalSpeedExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRotationalSpeedExtensions.g.cs @@ -32,147 +32,147 @@ namespace UnitsNet.NumberExtensions.NumberToRotationalSpeed /// public static class NumberToRotationalSpeedExtensions { - /// + /// public static RotationalSpeed CentiradiansPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalSpeed.FromCentiradiansPerSecond(double.CreateChecked(value)); + => RotationalSpeed.FromCentiradiansPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalSpeed.FromCentiradiansPerSecond(value.ToDouble(null)); + => RotationalSpeed.FromCentiradiansPerSecond(value.ToQuantityValue()); #endif - /// + /// public static RotationalSpeed DeciradiansPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalSpeed.FromDeciradiansPerSecond(double.CreateChecked(value)); + => RotationalSpeed.FromDeciradiansPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalSpeed.FromDeciradiansPerSecond(value.ToDouble(null)); + => RotationalSpeed.FromDeciradiansPerSecond(value.ToQuantityValue()); #endif - /// + /// public static RotationalSpeed DegreesPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalSpeed.FromDegreesPerMinute(double.CreateChecked(value)); + => RotationalSpeed.FromDegreesPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalSpeed.FromDegreesPerMinute(value.ToDouble(null)); + => RotationalSpeed.FromDegreesPerMinute(value.ToQuantityValue()); #endif - /// + /// public static RotationalSpeed DegreesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalSpeed.FromDegreesPerSecond(double.CreateChecked(value)); + => RotationalSpeed.FromDegreesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalSpeed.FromDegreesPerSecond(value.ToDouble(null)); + => RotationalSpeed.FromDegreesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static RotationalSpeed MicrodegreesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalSpeed.FromMicrodegreesPerSecond(double.CreateChecked(value)); + => RotationalSpeed.FromMicrodegreesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalSpeed.FromMicrodegreesPerSecond(value.ToDouble(null)); + => RotationalSpeed.FromMicrodegreesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static RotationalSpeed MicroradiansPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalSpeed.FromMicroradiansPerSecond(double.CreateChecked(value)); + => RotationalSpeed.FromMicroradiansPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalSpeed.FromMicroradiansPerSecond(value.ToDouble(null)); + => RotationalSpeed.FromMicroradiansPerSecond(value.ToQuantityValue()); #endif - /// + /// public static RotationalSpeed MillidegreesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalSpeed.FromMillidegreesPerSecond(double.CreateChecked(value)); + => RotationalSpeed.FromMillidegreesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalSpeed.FromMillidegreesPerSecond(value.ToDouble(null)); + => RotationalSpeed.FromMillidegreesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static RotationalSpeed MilliradiansPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalSpeed.FromMilliradiansPerSecond(double.CreateChecked(value)); + => RotationalSpeed.FromMilliradiansPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalSpeed.FromMilliradiansPerSecond(value.ToDouble(null)); + => RotationalSpeed.FromMilliradiansPerSecond(value.ToQuantityValue()); #endif - /// + /// public static RotationalSpeed NanodegreesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalSpeed.FromNanodegreesPerSecond(double.CreateChecked(value)); + => RotationalSpeed.FromNanodegreesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalSpeed.FromNanodegreesPerSecond(value.ToDouble(null)); + => RotationalSpeed.FromNanodegreesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static RotationalSpeed NanoradiansPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalSpeed.FromNanoradiansPerSecond(double.CreateChecked(value)); + => RotationalSpeed.FromNanoradiansPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalSpeed.FromNanoradiansPerSecond(value.ToDouble(null)); + => RotationalSpeed.FromNanoradiansPerSecond(value.ToQuantityValue()); #endif - /// + /// public static RotationalSpeed RadiansPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalSpeed.FromRadiansPerSecond(double.CreateChecked(value)); + => RotationalSpeed.FromRadiansPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalSpeed.FromRadiansPerSecond(value.ToDouble(null)); + => RotationalSpeed.FromRadiansPerSecond(value.ToQuantityValue()); #endif - /// + /// public static RotationalSpeed RevolutionsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalSpeed.FromRevolutionsPerMinute(double.CreateChecked(value)); + => RotationalSpeed.FromRevolutionsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalSpeed.FromRevolutionsPerMinute(value.ToDouble(null)); + => RotationalSpeed.FromRevolutionsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static RotationalSpeed RevolutionsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalSpeed.FromRevolutionsPerSecond(double.CreateChecked(value)); + => RotationalSpeed.FromRevolutionsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalSpeed.FromRevolutionsPerSecond(value.ToDouble(null)); + => RotationalSpeed.FromRevolutionsPerSecond(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRotationalStiffnessExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRotationalStiffnessExtensions.g.cs index d7f183459d..a27b8d0414 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRotationalStiffnessExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRotationalStiffnessExtensions.g.cs @@ -32,367 +32,367 @@ namespace UnitsNet.NumberExtensions.NumberToRotationalStiffness /// public static class NumberToRotationalStiffnessExtensions { - /// + /// public static RotationalStiffness CentinewtonMetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromCentinewtonMetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromCentinewtonMetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromCentinewtonMetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromCentinewtonMetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness CentinewtonMillimetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromCentinewtonMillimetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromCentinewtonMillimetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromCentinewtonMillimetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromCentinewtonMillimetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness CentinewtonMillimetersPerRadian(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromCentinewtonMillimetersPerRadian(double.CreateChecked(value)); + => RotationalStiffness.FromCentinewtonMillimetersPerRadian(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromCentinewtonMillimetersPerRadian(value.ToDouble(null)); + => RotationalStiffness.FromCentinewtonMillimetersPerRadian(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness DecanewtonMetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromDecanewtonMetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromDecanewtonMetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromDecanewtonMetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromDecanewtonMetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness DecanewtonMillimetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromDecanewtonMillimetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromDecanewtonMillimetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromDecanewtonMillimetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromDecanewtonMillimetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness DecanewtonMillimetersPerRadian(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromDecanewtonMillimetersPerRadian(double.CreateChecked(value)); + => RotationalStiffness.FromDecanewtonMillimetersPerRadian(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromDecanewtonMillimetersPerRadian(value.ToDouble(null)); + => RotationalStiffness.FromDecanewtonMillimetersPerRadian(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness DecinewtonMetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromDecinewtonMetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromDecinewtonMetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromDecinewtonMetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromDecinewtonMetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness DecinewtonMillimetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromDecinewtonMillimetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromDecinewtonMillimetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromDecinewtonMillimetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromDecinewtonMillimetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness DecinewtonMillimetersPerRadian(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromDecinewtonMillimetersPerRadian(double.CreateChecked(value)); + => RotationalStiffness.FromDecinewtonMillimetersPerRadian(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromDecinewtonMillimetersPerRadian(value.ToDouble(null)); + => RotationalStiffness.FromDecinewtonMillimetersPerRadian(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness KilonewtonMetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromKilonewtonMetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromKilonewtonMetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromKilonewtonMetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromKilonewtonMetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness KilonewtonMetersPerRadian(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromKilonewtonMetersPerRadian(double.CreateChecked(value)); + => RotationalStiffness.FromKilonewtonMetersPerRadian(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromKilonewtonMetersPerRadian(value.ToDouble(null)); + => RotationalStiffness.FromKilonewtonMetersPerRadian(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness KilonewtonMillimetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromKilonewtonMillimetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromKilonewtonMillimetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromKilonewtonMillimetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromKilonewtonMillimetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness KilonewtonMillimetersPerRadian(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromKilonewtonMillimetersPerRadian(double.CreateChecked(value)); + => RotationalStiffness.FromKilonewtonMillimetersPerRadian(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromKilonewtonMillimetersPerRadian(value.ToDouble(null)); + => RotationalStiffness.FromKilonewtonMillimetersPerRadian(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness KilopoundForceFeetPerDegrees(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromKilopoundForceFeetPerDegrees(double.CreateChecked(value)); + => RotationalStiffness.FromKilopoundForceFeetPerDegrees(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromKilopoundForceFeetPerDegrees(value.ToDouble(null)); + => RotationalStiffness.FromKilopoundForceFeetPerDegrees(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness MeganewtonMetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromMeganewtonMetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromMeganewtonMetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromMeganewtonMetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromMeganewtonMetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness MeganewtonMetersPerRadian(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromMeganewtonMetersPerRadian(double.CreateChecked(value)); + => RotationalStiffness.FromMeganewtonMetersPerRadian(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromMeganewtonMetersPerRadian(value.ToDouble(null)); + => RotationalStiffness.FromMeganewtonMetersPerRadian(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness MeganewtonMillimetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromMeganewtonMillimetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromMeganewtonMillimetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromMeganewtonMillimetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromMeganewtonMillimetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness MeganewtonMillimetersPerRadian(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromMeganewtonMillimetersPerRadian(double.CreateChecked(value)); + => RotationalStiffness.FromMeganewtonMillimetersPerRadian(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromMeganewtonMillimetersPerRadian(value.ToDouble(null)); + => RotationalStiffness.FromMeganewtonMillimetersPerRadian(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness MicronewtonMetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromMicronewtonMetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromMicronewtonMetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromMicronewtonMetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromMicronewtonMetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness MicronewtonMillimetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromMicronewtonMillimetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromMicronewtonMillimetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromMicronewtonMillimetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromMicronewtonMillimetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness MicronewtonMillimetersPerRadian(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromMicronewtonMillimetersPerRadian(double.CreateChecked(value)); + => RotationalStiffness.FromMicronewtonMillimetersPerRadian(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromMicronewtonMillimetersPerRadian(value.ToDouble(null)); + => RotationalStiffness.FromMicronewtonMillimetersPerRadian(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness MillinewtonMetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromMillinewtonMetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromMillinewtonMetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromMillinewtonMetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromMillinewtonMetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness MillinewtonMillimetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromMillinewtonMillimetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromMillinewtonMillimetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromMillinewtonMillimetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromMillinewtonMillimetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness MillinewtonMillimetersPerRadian(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromMillinewtonMillimetersPerRadian(double.CreateChecked(value)); + => RotationalStiffness.FromMillinewtonMillimetersPerRadian(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromMillinewtonMillimetersPerRadian(value.ToDouble(null)); + => RotationalStiffness.FromMillinewtonMillimetersPerRadian(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness NanonewtonMetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromNanonewtonMetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromNanonewtonMetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromNanonewtonMetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromNanonewtonMetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness NanonewtonMillimetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromNanonewtonMillimetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromNanonewtonMillimetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromNanonewtonMillimetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromNanonewtonMillimetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness NanonewtonMillimetersPerRadian(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromNanonewtonMillimetersPerRadian(double.CreateChecked(value)); + => RotationalStiffness.FromNanonewtonMillimetersPerRadian(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromNanonewtonMillimetersPerRadian(value.ToDouble(null)); + => RotationalStiffness.FromNanonewtonMillimetersPerRadian(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness NewtonMetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromNewtonMetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromNewtonMetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromNewtonMetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromNewtonMetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness NewtonMetersPerRadian(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromNewtonMetersPerRadian(double.CreateChecked(value)); + => RotationalStiffness.FromNewtonMetersPerRadian(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromNewtonMetersPerRadian(value.ToDouble(null)); + => RotationalStiffness.FromNewtonMetersPerRadian(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness NewtonMillimetersPerDegree(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromNewtonMillimetersPerDegree(double.CreateChecked(value)); + => RotationalStiffness.FromNewtonMillimetersPerDegree(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromNewtonMillimetersPerDegree(value.ToDouble(null)); + => RotationalStiffness.FromNewtonMillimetersPerDegree(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness NewtonMillimetersPerRadian(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromNewtonMillimetersPerRadian(double.CreateChecked(value)); + => RotationalStiffness.FromNewtonMillimetersPerRadian(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromNewtonMillimetersPerRadian(value.ToDouble(null)); + => RotationalStiffness.FromNewtonMillimetersPerRadian(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness PoundForceFeetPerRadian(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromPoundForceFeetPerRadian(double.CreateChecked(value)); + => RotationalStiffness.FromPoundForceFeetPerRadian(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromPoundForceFeetPerRadian(value.ToDouble(null)); + => RotationalStiffness.FromPoundForceFeetPerRadian(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffness PoundForceFeetPerDegrees(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffness.FromPoundForceFeetPerDegrees(double.CreateChecked(value)); + => RotationalStiffness.FromPoundForceFeetPerDegrees(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffness.FromPoundForceFeetPerDegrees(value.ToDouble(null)); + => RotationalStiffness.FromPoundForceFeetPerDegrees(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRotationalStiffnessPerLengthExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRotationalStiffnessPerLengthExtensions.g.cs index b49fa9ec38..01b73a5c7a 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToRotationalStiffnessPerLengthExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToRotationalStiffnessPerLengthExtensions.g.cs @@ -32,59 +32,59 @@ namespace UnitsNet.NumberExtensions.NumberToRotationalStiffnessPerLength /// public static class NumberToRotationalStiffnessPerLengthExtensions { - /// + /// public static RotationalStiffnessPerLength KilonewtonMetersPerRadianPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffnessPerLength.FromKilonewtonMetersPerRadianPerMeter(double.CreateChecked(value)); + => RotationalStiffnessPerLength.FromKilonewtonMetersPerRadianPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffnessPerLength.FromKilonewtonMetersPerRadianPerMeter(value.ToDouble(null)); + => RotationalStiffnessPerLength.FromKilonewtonMetersPerRadianPerMeter(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffnessPerLength KilopoundForceFeetPerDegreesPerFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffnessPerLength.FromKilopoundForceFeetPerDegreesPerFeet(double.CreateChecked(value)); + => RotationalStiffnessPerLength.FromKilopoundForceFeetPerDegreesPerFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffnessPerLength.FromKilopoundForceFeetPerDegreesPerFeet(value.ToDouble(null)); + => RotationalStiffnessPerLength.FromKilopoundForceFeetPerDegreesPerFeet(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffnessPerLength MeganewtonMetersPerRadianPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffnessPerLength.FromMeganewtonMetersPerRadianPerMeter(double.CreateChecked(value)); + => RotationalStiffnessPerLength.FromMeganewtonMetersPerRadianPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffnessPerLength.FromMeganewtonMetersPerRadianPerMeter(value.ToDouble(null)); + => RotationalStiffnessPerLength.FromMeganewtonMetersPerRadianPerMeter(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffnessPerLength NewtonMetersPerRadianPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(double.CreateChecked(value)); + => RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(value.ToDouble(null)); + => RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(value.ToQuantityValue()); #endif - /// + /// public static RotationalStiffnessPerLength PoundForceFeetPerDegreesPerFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => RotationalStiffnessPerLength.FromPoundForceFeetPerDegreesPerFeet(double.CreateChecked(value)); + => RotationalStiffnessPerLength.FromPoundForceFeetPerDegreesPerFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => RotationalStiffnessPerLength.FromPoundForceFeetPerDegreesPerFeet(value.ToDouble(null)); + => RotationalStiffnessPerLength.FromPoundForceFeetPerDegreesPerFeet(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToScalarExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToScalarExtensions.g.cs index decb61c473..386e60a893 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToScalarExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToScalarExtensions.g.cs @@ -32,15 +32,15 @@ namespace UnitsNet.NumberExtensions.NumberToScalar /// public static class NumberToScalarExtensions { - /// + /// public static Scalar Amount(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Scalar.FromAmount(double.CreateChecked(value)); + => Scalar.FromAmount(QuantityValue.CreateChecked(value)); #else , IConvertible - => Scalar.FromAmount(value.ToDouble(null)); + => Scalar.FromAmount(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToSolidAngleExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToSolidAngleExtensions.g.cs index 7af5f9550a..aadd2f279c 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToSolidAngleExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToSolidAngleExtensions.g.cs @@ -32,15 +32,15 @@ namespace UnitsNet.NumberExtensions.NumberToSolidAngle /// public static class NumberToSolidAngleExtensions { - /// + /// public static SolidAngle Steradians(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SolidAngle.FromSteradians(double.CreateChecked(value)); + => SolidAngle.FromSteradians(QuantityValue.CreateChecked(value)); #else , IConvertible - => SolidAngle.FromSteradians(value.ToDouble(null)); + => SolidAngle.FromSteradians(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificEnergyExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificEnergyExtensions.g.cs index f277486178..23dd803b89 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificEnergyExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificEnergyExtensions.g.cs @@ -32,334 +32,334 @@ namespace UnitsNet.NumberExtensions.NumberToSpecificEnergy /// public static class NumberToSpecificEnergyExtensions { - /// + /// public static SpecificEnergy BtuPerPound(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromBtuPerPound(double.CreateChecked(value)); + => SpecificEnergy.FromBtuPerPound(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromBtuPerPound(value.ToDouble(null)); + => SpecificEnergy.FromBtuPerPound(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy CaloriesPerGram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromCaloriesPerGram(double.CreateChecked(value)); + => SpecificEnergy.FromCaloriesPerGram(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromCaloriesPerGram(value.ToDouble(null)); + => SpecificEnergy.FromCaloriesPerGram(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy GigawattDaysPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromGigawattDaysPerKilogram(double.CreateChecked(value)); + => SpecificEnergy.FromGigawattDaysPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromGigawattDaysPerKilogram(value.ToDouble(null)); + => SpecificEnergy.FromGigawattDaysPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy GigawattDaysPerShortTon(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromGigawattDaysPerShortTon(double.CreateChecked(value)); + => SpecificEnergy.FromGigawattDaysPerShortTon(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromGigawattDaysPerShortTon(value.ToDouble(null)); + => SpecificEnergy.FromGigawattDaysPerShortTon(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy GigawattDaysPerTonne(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromGigawattDaysPerTonne(double.CreateChecked(value)); + => SpecificEnergy.FromGigawattDaysPerTonne(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromGigawattDaysPerTonne(value.ToDouble(null)); + => SpecificEnergy.FromGigawattDaysPerTonne(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy GigawattHoursPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromGigawattHoursPerKilogram(double.CreateChecked(value)); + => SpecificEnergy.FromGigawattHoursPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromGigawattHoursPerKilogram(value.ToDouble(null)); + => SpecificEnergy.FromGigawattHoursPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy GigawattHoursPerPound(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromGigawattHoursPerPound(double.CreateChecked(value)); + => SpecificEnergy.FromGigawattHoursPerPound(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromGigawattHoursPerPound(value.ToDouble(null)); + => SpecificEnergy.FromGigawattHoursPerPound(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy JoulesPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromJoulesPerKilogram(double.CreateChecked(value)); + => SpecificEnergy.FromJoulesPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromJoulesPerKilogram(value.ToDouble(null)); + => SpecificEnergy.FromJoulesPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy KilocaloriesPerGram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromKilocaloriesPerGram(double.CreateChecked(value)); + => SpecificEnergy.FromKilocaloriesPerGram(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromKilocaloriesPerGram(value.ToDouble(null)); + => SpecificEnergy.FromKilocaloriesPerGram(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy KilojoulesPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromKilojoulesPerKilogram(double.CreateChecked(value)); + => SpecificEnergy.FromKilojoulesPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromKilojoulesPerKilogram(value.ToDouble(null)); + => SpecificEnergy.FromKilojoulesPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy KilowattDaysPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromKilowattDaysPerKilogram(double.CreateChecked(value)); + => SpecificEnergy.FromKilowattDaysPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromKilowattDaysPerKilogram(value.ToDouble(null)); + => SpecificEnergy.FromKilowattDaysPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy KilowattDaysPerShortTon(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromKilowattDaysPerShortTon(double.CreateChecked(value)); + => SpecificEnergy.FromKilowattDaysPerShortTon(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromKilowattDaysPerShortTon(value.ToDouble(null)); + => SpecificEnergy.FromKilowattDaysPerShortTon(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy KilowattDaysPerTonne(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromKilowattDaysPerTonne(double.CreateChecked(value)); + => SpecificEnergy.FromKilowattDaysPerTonne(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromKilowattDaysPerTonne(value.ToDouble(null)); + => SpecificEnergy.FromKilowattDaysPerTonne(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy KilowattHoursPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromKilowattHoursPerKilogram(double.CreateChecked(value)); + => SpecificEnergy.FromKilowattHoursPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromKilowattHoursPerKilogram(value.ToDouble(null)); + => SpecificEnergy.FromKilowattHoursPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy KilowattHoursPerPound(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromKilowattHoursPerPound(double.CreateChecked(value)); + => SpecificEnergy.FromKilowattHoursPerPound(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromKilowattHoursPerPound(value.ToDouble(null)); + => SpecificEnergy.FromKilowattHoursPerPound(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy MegajoulesPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromMegajoulesPerKilogram(double.CreateChecked(value)); + => SpecificEnergy.FromMegajoulesPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromMegajoulesPerKilogram(value.ToDouble(null)); + => SpecificEnergy.FromMegajoulesPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy MegaJoulesPerTonne(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromMegaJoulesPerTonne(double.CreateChecked(value)); + => SpecificEnergy.FromMegaJoulesPerTonne(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromMegaJoulesPerTonne(value.ToDouble(null)); + => SpecificEnergy.FromMegaJoulesPerTonne(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy MegawattDaysPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromMegawattDaysPerKilogram(double.CreateChecked(value)); + => SpecificEnergy.FromMegawattDaysPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromMegawattDaysPerKilogram(value.ToDouble(null)); + => SpecificEnergy.FromMegawattDaysPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy MegawattDaysPerShortTon(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromMegawattDaysPerShortTon(double.CreateChecked(value)); + => SpecificEnergy.FromMegawattDaysPerShortTon(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromMegawattDaysPerShortTon(value.ToDouble(null)); + => SpecificEnergy.FromMegawattDaysPerShortTon(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy MegawattDaysPerTonne(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromMegawattDaysPerTonne(double.CreateChecked(value)); + => SpecificEnergy.FromMegawattDaysPerTonne(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromMegawattDaysPerTonne(value.ToDouble(null)); + => SpecificEnergy.FromMegawattDaysPerTonne(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy MegawattHoursPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromMegawattHoursPerKilogram(double.CreateChecked(value)); + => SpecificEnergy.FromMegawattHoursPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromMegawattHoursPerKilogram(value.ToDouble(null)); + => SpecificEnergy.FromMegawattHoursPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy MegawattHoursPerPound(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromMegawattHoursPerPound(double.CreateChecked(value)); + => SpecificEnergy.FromMegawattHoursPerPound(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromMegawattHoursPerPound(value.ToDouble(null)); + => SpecificEnergy.FromMegawattHoursPerPound(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy TerawattDaysPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromTerawattDaysPerKilogram(double.CreateChecked(value)); + => SpecificEnergy.FromTerawattDaysPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromTerawattDaysPerKilogram(value.ToDouble(null)); + => SpecificEnergy.FromTerawattDaysPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy TerawattDaysPerShortTon(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromTerawattDaysPerShortTon(double.CreateChecked(value)); + => SpecificEnergy.FromTerawattDaysPerShortTon(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromTerawattDaysPerShortTon(value.ToDouble(null)); + => SpecificEnergy.FromTerawattDaysPerShortTon(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy TerawattDaysPerTonne(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromTerawattDaysPerTonne(double.CreateChecked(value)); + => SpecificEnergy.FromTerawattDaysPerTonne(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromTerawattDaysPerTonne(value.ToDouble(null)); + => SpecificEnergy.FromTerawattDaysPerTonne(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy WattDaysPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromWattDaysPerKilogram(double.CreateChecked(value)); + => SpecificEnergy.FromWattDaysPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromWattDaysPerKilogram(value.ToDouble(null)); + => SpecificEnergy.FromWattDaysPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy WattDaysPerShortTon(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromWattDaysPerShortTon(double.CreateChecked(value)); + => SpecificEnergy.FromWattDaysPerShortTon(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromWattDaysPerShortTon(value.ToDouble(null)); + => SpecificEnergy.FromWattDaysPerShortTon(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy WattDaysPerTonne(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromWattDaysPerTonne(double.CreateChecked(value)); + => SpecificEnergy.FromWattDaysPerTonne(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromWattDaysPerTonne(value.ToDouble(null)); + => SpecificEnergy.FromWattDaysPerTonne(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy WattHoursPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromWattHoursPerKilogram(double.CreateChecked(value)); + => SpecificEnergy.FromWattHoursPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromWattHoursPerKilogram(value.ToDouble(null)); + => SpecificEnergy.FromWattHoursPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static SpecificEnergy WattHoursPerPound(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEnergy.FromWattHoursPerPound(double.CreateChecked(value)); + => SpecificEnergy.FromWattHoursPerPound(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEnergy.FromWattHoursPerPound(value.ToDouble(null)); + => SpecificEnergy.FromWattHoursPerPound(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificEntropyExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificEntropyExtensions.g.cs index cf22bc3712..a6688da3ed 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificEntropyExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificEntropyExtensions.g.cs @@ -32,103 +32,103 @@ namespace UnitsNet.NumberExtensions.NumberToSpecificEntropy /// public static class NumberToSpecificEntropyExtensions { - /// + /// public static SpecificEntropy BtusPerPoundFahrenheit(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEntropy.FromBtusPerPoundFahrenheit(double.CreateChecked(value)); + => SpecificEntropy.FromBtusPerPoundFahrenheit(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEntropy.FromBtusPerPoundFahrenheit(value.ToDouble(null)); + => SpecificEntropy.FromBtusPerPoundFahrenheit(value.ToQuantityValue()); #endif - /// + /// public static SpecificEntropy CaloriesPerGramKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEntropy.FromCaloriesPerGramKelvin(double.CreateChecked(value)); + => SpecificEntropy.FromCaloriesPerGramKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEntropy.FromCaloriesPerGramKelvin(value.ToDouble(null)); + => SpecificEntropy.FromCaloriesPerGramKelvin(value.ToQuantityValue()); #endif - /// + /// public static SpecificEntropy JoulesPerKilogramDegreeCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEntropy.FromJoulesPerKilogramDegreeCelsius(double.CreateChecked(value)); + => SpecificEntropy.FromJoulesPerKilogramDegreeCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEntropy.FromJoulesPerKilogramDegreeCelsius(value.ToDouble(null)); + => SpecificEntropy.FromJoulesPerKilogramDegreeCelsius(value.ToQuantityValue()); #endif - /// + /// public static SpecificEntropy JoulesPerKilogramKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEntropy.FromJoulesPerKilogramKelvin(double.CreateChecked(value)); + => SpecificEntropy.FromJoulesPerKilogramKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEntropy.FromJoulesPerKilogramKelvin(value.ToDouble(null)); + => SpecificEntropy.FromJoulesPerKilogramKelvin(value.ToQuantityValue()); #endif - /// + /// public static SpecificEntropy KilocaloriesPerGramKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEntropy.FromKilocaloriesPerGramKelvin(double.CreateChecked(value)); + => SpecificEntropy.FromKilocaloriesPerGramKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEntropy.FromKilocaloriesPerGramKelvin(value.ToDouble(null)); + => SpecificEntropy.FromKilocaloriesPerGramKelvin(value.ToQuantityValue()); #endif - /// + /// public static SpecificEntropy KilojoulesPerKilogramDegreeCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEntropy.FromKilojoulesPerKilogramDegreeCelsius(double.CreateChecked(value)); + => SpecificEntropy.FromKilojoulesPerKilogramDegreeCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEntropy.FromKilojoulesPerKilogramDegreeCelsius(value.ToDouble(null)); + => SpecificEntropy.FromKilojoulesPerKilogramDegreeCelsius(value.ToQuantityValue()); #endif - /// + /// public static SpecificEntropy KilojoulesPerKilogramKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEntropy.FromKilojoulesPerKilogramKelvin(double.CreateChecked(value)); + => SpecificEntropy.FromKilojoulesPerKilogramKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEntropy.FromKilojoulesPerKilogramKelvin(value.ToDouble(null)); + => SpecificEntropy.FromKilojoulesPerKilogramKelvin(value.ToQuantityValue()); #endif - /// + /// public static SpecificEntropy MegajoulesPerKilogramDegreeCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEntropy.FromMegajoulesPerKilogramDegreeCelsius(double.CreateChecked(value)); + => SpecificEntropy.FromMegajoulesPerKilogramDegreeCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEntropy.FromMegajoulesPerKilogramDegreeCelsius(value.ToDouble(null)); + => SpecificEntropy.FromMegajoulesPerKilogramDegreeCelsius(value.ToQuantityValue()); #endif - /// + /// public static SpecificEntropy MegajoulesPerKilogramKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificEntropy.FromMegajoulesPerKilogramKelvin(double.CreateChecked(value)); + => SpecificEntropy.FromMegajoulesPerKilogramKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificEntropy.FromMegajoulesPerKilogramKelvin(value.ToDouble(null)); + => SpecificEntropy.FromMegajoulesPerKilogramKelvin(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificFuelConsumptionExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificFuelConsumptionExtensions.g.cs index f1479d7feb..832423fe15 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificFuelConsumptionExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificFuelConsumptionExtensions.g.cs @@ -32,48 +32,48 @@ namespace UnitsNet.NumberExtensions.NumberToSpecificFuelConsumption /// public static class NumberToSpecificFuelConsumptionExtensions { - /// + /// public static SpecificFuelConsumption GramsPerKilonewtonSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificFuelConsumption.FromGramsPerKilonewtonSecond(double.CreateChecked(value)); + => SpecificFuelConsumption.FromGramsPerKilonewtonSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificFuelConsumption.FromGramsPerKilonewtonSecond(value.ToDouble(null)); + => SpecificFuelConsumption.FromGramsPerKilonewtonSecond(value.ToQuantityValue()); #endif - /// + /// public static SpecificFuelConsumption KilogramsPerKilogramForceHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificFuelConsumption.FromKilogramsPerKilogramForceHour(double.CreateChecked(value)); + => SpecificFuelConsumption.FromKilogramsPerKilogramForceHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificFuelConsumption.FromKilogramsPerKilogramForceHour(value.ToDouble(null)); + => SpecificFuelConsumption.FromKilogramsPerKilogramForceHour(value.ToQuantityValue()); #endif - /// + /// public static SpecificFuelConsumption KilogramsPerKilonewtonSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificFuelConsumption.FromKilogramsPerKilonewtonSecond(double.CreateChecked(value)); + => SpecificFuelConsumption.FromKilogramsPerKilonewtonSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificFuelConsumption.FromKilogramsPerKilonewtonSecond(value.ToDouble(null)); + => SpecificFuelConsumption.FromKilogramsPerKilonewtonSecond(value.ToQuantityValue()); #endif - /// + /// public static SpecificFuelConsumption PoundsMassPerPoundForceHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificFuelConsumption.FromPoundsMassPerPoundForceHour(double.CreateChecked(value)); + => SpecificFuelConsumption.FromPoundsMassPerPoundForceHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificFuelConsumption.FromPoundsMassPerPoundForceHour(value.ToDouble(null)); + => SpecificFuelConsumption.FromPoundsMassPerPoundForceHour(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificVolumeExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificVolumeExtensions.g.cs index 3839372237..850e09df7d 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificVolumeExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificVolumeExtensions.g.cs @@ -32,37 +32,37 @@ namespace UnitsNet.NumberExtensions.NumberToSpecificVolume /// public static class NumberToSpecificVolumeExtensions { - /// + /// public static SpecificVolume CubicFeetPerPound(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificVolume.FromCubicFeetPerPound(double.CreateChecked(value)); + => SpecificVolume.FromCubicFeetPerPound(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificVolume.FromCubicFeetPerPound(value.ToDouble(null)); + => SpecificVolume.FromCubicFeetPerPound(value.ToQuantityValue()); #endif - /// + /// public static SpecificVolume CubicMetersPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificVolume.FromCubicMetersPerKilogram(double.CreateChecked(value)); + => SpecificVolume.FromCubicMetersPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificVolume.FromCubicMetersPerKilogram(value.ToDouble(null)); + => SpecificVolume.FromCubicMetersPerKilogram(value.ToQuantityValue()); #endif - /// + /// public static SpecificVolume MillicubicMetersPerKilogram(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificVolume.FromMillicubicMetersPerKilogram(double.CreateChecked(value)); + => SpecificVolume.FromMillicubicMetersPerKilogram(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificVolume.FromMillicubicMetersPerKilogram(value.ToDouble(null)); + => SpecificVolume.FromMillicubicMetersPerKilogram(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificWeightExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificWeightExtensions.g.cs index 3bef134ca9..aa13088a97 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificWeightExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpecificWeightExtensions.g.cs @@ -32,191 +32,191 @@ namespace UnitsNet.NumberExtensions.NumberToSpecificWeight /// public static class NumberToSpecificWeightExtensions { - /// + /// public static SpecificWeight KilogramsForcePerCubicCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificWeight.FromKilogramsForcePerCubicCentimeter(double.CreateChecked(value)); + => SpecificWeight.FromKilogramsForcePerCubicCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificWeight.FromKilogramsForcePerCubicCentimeter(value.ToDouble(null)); + => SpecificWeight.FromKilogramsForcePerCubicCentimeter(value.ToQuantityValue()); #endif - /// + /// public static SpecificWeight KilogramsForcePerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificWeight.FromKilogramsForcePerCubicMeter(double.CreateChecked(value)); + => SpecificWeight.FromKilogramsForcePerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificWeight.FromKilogramsForcePerCubicMeter(value.ToDouble(null)); + => SpecificWeight.FromKilogramsForcePerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static SpecificWeight KilogramsForcePerCubicMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificWeight.FromKilogramsForcePerCubicMillimeter(double.CreateChecked(value)); + => SpecificWeight.FromKilogramsForcePerCubicMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificWeight.FromKilogramsForcePerCubicMillimeter(value.ToDouble(null)); + => SpecificWeight.FromKilogramsForcePerCubicMillimeter(value.ToQuantityValue()); #endif - /// + /// public static SpecificWeight KilonewtonsPerCubicCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificWeight.FromKilonewtonsPerCubicCentimeter(double.CreateChecked(value)); + => SpecificWeight.FromKilonewtonsPerCubicCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificWeight.FromKilonewtonsPerCubicCentimeter(value.ToDouble(null)); + => SpecificWeight.FromKilonewtonsPerCubicCentimeter(value.ToQuantityValue()); #endif - /// + /// public static SpecificWeight KilonewtonsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificWeight.FromKilonewtonsPerCubicMeter(double.CreateChecked(value)); + => SpecificWeight.FromKilonewtonsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificWeight.FromKilonewtonsPerCubicMeter(value.ToDouble(null)); + => SpecificWeight.FromKilonewtonsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static SpecificWeight KilonewtonsPerCubicMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificWeight.FromKilonewtonsPerCubicMillimeter(double.CreateChecked(value)); + => SpecificWeight.FromKilonewtonsPerCubicMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificWeight.FromKilonewtonsPerCubicMillimeter(value.ToDouble(null)); + => SpecificWeight.FromKilonewtonsPerCubicMillimeter(value.ToQuantityValue()); #endif - /// + /// public static SpecificWeight KilopoundsForcePerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificWeight.FromKilopoundsForcePerCubicFoot(double.CreateChecked(value)); + => SpecificWeight.FromKilopoundsForcePerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificWeight.FromKilopoundsForcePerCubicFoot(value.ToDouble(null)); + => SpecificWeight.FromKilopoundsForcePerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static SpecificWeight KilopoundsForcePerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificWeight.FromKilopoundsForcePerCubicInch(double.CreateChecked(value)); + => SpecificWeight.FromKilopoundsForcePerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificWeight.FromKilopoundsForcePerCubicInch(value.ToDouble(null)); + => SpecificWeight.FromKilopoundsForcePerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static SpecificWeight MeganewtonsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificWeight.FromMeganewtonsPerCubicMeter(double.CreateChecked(value)); + => SpecificWeight.FromMeganewtonsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificWeight.FromMeganewtonsPerCubicMeter(value.ToDouble(null)); + => SpecificWeight.FromMeganewtonsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static SpecificWeight NewtonsPerCubicCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificWeight.FromNewtonsPerCubicCentimeter(double.CreateChecked(value)); + => SpecificWeight.FromNewtonsPerCubicCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificWeight.FromNewtonsPerCubicCentimeter(value.ToDouble(null)); + => SpecificWeight.FromNewtonsPerCubicCentimeter(value.ToQuantityValue()); #endif - /// + /// public static SpecificWeight NewtonsPerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificWeight.FromNewtonsPerCubicMeter(double.CreateChecked(value)); + => SpecificWeight.FromNewtonsPerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificWeight.FromNewtonsPerCubicMeter(value.ToDouble(null)); + => SpecificWeight.FromNewtonsPerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static SpecificWeight NewtonsPerCubicMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificWeight.FromNewtonsPerCubicMillimeter(double.CreateChecked(value)); + => SpecificWeight.FromNewtonsPerCubicMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificWeight.FromNewtonsPerCubicMillimeter(value.ToDouble(null)); + => SpecificWeight.FromNewtonsPerCubicMillimeter(value.ToQuantityValue()); #endif - /// + /// public static SpecificWeight PoundsForcePerCubicFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificWeight.FromPoundsForcePerCubicFoot(double.CreateChecked(value)); + => SpecificWeight.FromPoundsForcePerCubicFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificWeight.FromPoundsForcePerCubicFoot(value.ToDouble(null)); + => SpecificWeight.FromPoundsForcePerCubicFoot(value.ToQuantityValue()); #endif - /// + /// public static SpecificWeight PoundsForcePerCubicInch(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificWeight.FromPoundsForcePerCubicInch(double.CreateChecked(value)); + => SpecificWeight.FromPoundsForcePerCubicInch(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificWeight.FromPoundsForcePerCubicInch(value.ToDouble(null)); + => SpecificWeight.FromPoundsForcePerCubicInch(value.ToQuantityValue()); #endif - /// + /// public static SpecificWeight TonnesForcePerCubicCentimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificWeight.FromTonnesForcePerCubicCentimeter(double.CreateChecked(value)); + => SpecificWeight.FromTonnesForcePerCubicCentimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificWeight.FromTonnesForcePerCubicCentimeter(value.ToDouble(null)); + => SpecificWeight.FromTonnesForcePerCubicCentimeter(value.ToQuantityValue()); #endif - /// + /// public static SpecificWeight TonnesForcePerCubicMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificWeight.FromTonnesForcePerCubicMeter(double.CreateChecked(value)); + => SpecificWeight.FromTonnesForcePerCubicMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificWeight.FromTonnesForcePerCubicMeter(value.ToDouble(null)); + => SpecificWeight.FromTonnesForcePerCubicMeter(value.ToQuantityValue()); #endif - /// + /// public static SpecificWeight TonnesForcePerCubicMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => SpecificWeight.FromTonnesForcePerCubicMillimeter(double.CreateChecked(value)); + => SpecificWeight.FromTonnesForcePerCubicMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => SpecificWeight.FromTonnesForcePerCubicMillimeter(value.ToDouble(null)); + => SpecificWeight.FromTonnesForcePerCubicMillimeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpeedExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpeedExtensions.g.cs index 75bd5bbe13..ec1e070bfd 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpeedExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToSpeedExtensions.g.cs @@ -32,367 +32,367 @@ namespace UnitsNet.NumberExtensions.NumberToSpeed /// public static class NumberToSpeedExtensions { - /// + /// public static Speed CentimetersPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromCentimetersPerHour(double.CreateChecked(value)); + => Speed.FromCentimetersPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromCentimetersPerHour(value.ToDouble(null)); + => Speed.FromCentimetersPerHour(value.ToQuantityValue()); #endif - /// + /// public static Speed CentimetersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromCentimetersPerMinute(double.CreateChecked(value)); + => Speed.FromCentimetersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromCentimetersPerMinute(value.ToDouble(null)); + => Speed.FromCentimetersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static Speed CentimetersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromCentimetersPerSecond(double.CreateChecked(value)); + => Speed.FromCentimetersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromCentimetersPerSecond(value.ToDouble(null)); + => Speed.FromCentimetersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static Speed DecimetersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromDecimetersPerMinute(double.CreateChecked(value)); + => Speed.FromDecimetersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromDecimetersPerMinute(value.ToDouble(null)); + => Speed.FromDecimetersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static Speed DecimetersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromDecimetersPerSecond(double.CreateChecked(value)); + => Speed.FromDecimetersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromDecimetersPerSecond(value.ToDouble(null)); + => Speed.FromDecimetersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static Speed FeetPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromFeetPerHour(double.CreateChecked(value)); + => Speed.FromFeetPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromFeetPerHour(value.ToDouble(null)); + => Speed.FromFeetPerHour(value.ToQuantityValue()); #endif - /// + /// public static Speed FeetPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromFeetPerMinute(double.CreateChecked(value)); + => Speed.FromFeetPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromFeetPerMinute(value.ToDouble(null)); + => Speed.FromFeetPerMinute(value.ToQuantityValue()); #endif - /// + /// public static Speed FeetPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromFeetPerSecond(double.CreateChecked(value)); + => Speed.FromFeetPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromFeetPerSecond(value.ToDouble(null)); + => Speed.FromFeetPerSecond(value.ToQuantityValue()); #endif - /// + /// public static Speed InchesPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromInchesPerHour(double.CreateChecked(value)); + => Speed.FromInchesPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromInchesPerHour(value.ToDouble(null)); + => Speed.FromInchesPerHour(value.ToQuantityValue()); #endif - /// + /// public static Speed InchesPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromInchesPerMinute(double.CreateChecked(value)); + => Speed.FromInchesPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromInchesPerMinute(value.ToDouble(null)); + => Speed.FromInchesPerMinute(value.ToQuantityValue()); #endif - /// + /// public static Speed InchesPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromInchesPerSecond(double.CreateChecked(value)); + => Speed.FromInchesPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromInchesPerSecond(value.ToDouble(null)); + => Speed.FromInchesPerSecond(value.ToQuantityValue()); #endif - /// + /// public static Speed KilometersPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromKilometersPerHour(double.CreateChecked(value)); + => Speed.FromKilometersPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromKilometersPerHour(value.ToDouble(null)); + => Speed.FromKilometersPerHour(value.ToQuantityValue()); #endif - /// + /// public static Speed KilometersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromKilometersPerMinute(double.CreateChecked(value)); + => Speed.FromKilometersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromKilometersPerMinute(value.ToDouble(null)); + => Speed.FromKilometersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static Speed KilometersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromKilometersPerSecond(double.CreateChecked(value)); + => Speed.FromKilometersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromKilometersPerSecond(value.ToDouble(null)); + => Speed.FromKilometersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static Speed Knots(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromKnots(double.CreateChecked(value)); + => Speed.FromKnots(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromKnots(value.ToDouble(null)); + => Speed.FromKnots(value.ToQuantityValue()); #endif - /// + /// public static Speed Mach(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromMach(double.CreateChecked(value)); + => Speed.FromMach(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromMach(value.ToDouble(null)); + => Speed.FromMach(value.ToQuantityValue()); #endif - /// + /// public static Speed MetersPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromMetersPerHour(double.CreateChecked(value)); + => Speed.FromMetersPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromMetersPerHour(value.ToDouble(null)); + => Speed.FromMetersPerHour(value.ToQuantityValue()); #endif - /// + /// public static Speed MetersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromMetersPerMinute(double.CreateChecked(value)); + => Speed.FromMetersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromMetersPerMinute(value.ToDouble(null)); + => Speed.FromMetersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static Speed MetersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromMetersPerSecond(double.CreateChecked(value)); + => Speed.FromMetersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromMetersPerSecond(value.ToDouble(null)); + => Speed.FromMetersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static Speed MicrometersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromMicrometersPerMinute(double.CreateChecked(value)); + => Speed.FromMicrometersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromMicrometersPerMinute(value.ToDouble(null)); + => Speed.FromMicrometersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static Speed MicrometersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromMicrometersPerSecond(double.CreateChecked(value)); + => Speed.FromMicrometersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromMicrometersPerSecond(value.ToDouble(null)); + => Speed.FromMicrometersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static Speed MilesPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromMilesPerHour(double.CreateChecked(value)); + => Speed.FromMilesPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromMilesPerHour(value.ToDouble(null)); + => Speed.FromMilesPerHour(value.ToQuantityValue()); #endif - /// + /// public static Speed MillimetersPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromMillimetersPerHour(double.CreateChecked(value)); + => Speed.FromMillimetersPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromMillimetersPerHour(value.ToDouble(null)); + => Speed.FromMillimetersPerHour(value.ToQuantityValue()); #endif - /// + /// public static Speed MillimetersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromMillimetersPerMinute(double.CreateChecked(value)); + => Speed.FromMillimetersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromMillimetersPerMinute(value.ToDouble(null)); + => Speed.FromMillimetersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static Speed MillimetersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromMillimetersPerSecond(double.CreateChecked(value)); + => Speed.FromMillimetersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromMillimetersPerSecond(value.ToDouble(null)); + => Speed.FromMillimetersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static Speed NanometersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromNanometersPerMinute(double.CreateChecked(value)); + => Speed.FromNanometersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromNanometersPerMinute(value.ToDouble(null)); + => Speed.FromNanometersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static Speed NanometersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromNanometersPerSecond(double.CreateChecked(value)); + => Speed.FromNanometersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromNanometersPerSecond(value.ToDouble(null)); + => Speed.FromNanometersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static Speed UsSurveyFeetPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromUsSurveyFeetPerHour(double.CreateChecked(value)); + => Speed.FromUsSurveyFeetPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromUsSurveyFeetPerHour(value.ToDouble(null)); + => Speed.FromUsSurveyFeetPerHour(value.ToQuantityValue()); #endif - /// + /// public static Speed UsSurveyFeetPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromUsSurveyFeetPerMinute(double.CreateChecked(value)); + => Speed.FromUsSurveyFeetPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromUsSurveyFeetPerMinute(value.ToDouble(null)); + => Speed.FromUsSurveyFeetPerMinute(value.ToQuantityValue()); #endif - /// + /// public static Speed UsSurveyFeetPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromUsSurveyFeetPerSecond(double.CreateChecked(value)); + => Speed.FromUsSurveyFeetPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromUsSurveyFeetPerSecond(value.ToDouble(null)); + => Speed.FromUsSurveyFeetPerSecond(value.ToQuantityValue()); #endif - /// + /// public static Speed YardsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromYardsPerHour(double.CreateChecked(value)); + => Speed.FromYardsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromYardsPerHour(value.ToDouble(null)); + => Speed.FromYardsPerHour(value.ToQuantityValue()); #endif - /// + /// public static Speed YardsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromYardsPerMinute(double.CreateChecked(value)); + => Speed.FromYardsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromYardsPerMinute(value.ToDouble(null)); + => Speed.FromYardsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static Speed YardsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Speed.FromYardsPerSecond(double.CreateChecked(value)); + => Speed.FromYardsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => Speed.FromYardsPerSecond(value.ToDouble(null)); + => Speed.FromYardsPerSecond(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToStandardVolumeFlowExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToStandardVolumeFlowExtensions.g.cs index f442ff3bfe..8b9a18370f 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToStandardVolumeFlowExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToStandardVolumeFlowExtensions.g.cs @@ -32,103 +32,103 @@ namespace UnitsNet.NumberExtensions.NumberToStandardVolumeFlow /// public static class NumberToStandardVolumeFlowExtensions { - /// + /// public static StandardVolumeFlow StandardCubicCentimetersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => StandardVolumeFlow.FromStandardCubicCentimetersPerMinute(double.CreateChecked(value)); + => StandardVolumeFlow.FromStandardCubicCentimetersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => StandardVolumeFlow.FromStandardCubicCentimetersPerMinute(value.ToDouble(null)); + => StandardVolumeFlow.FromStandardCubicCentimetersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static StandardVolumeFlow StandardCubicFeetPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => StandardVolumeFlow.FromStandardCubicFeetPerHour(double.CreateChecked(value)); + => StandardVolumeFlow.FromStandardCubicFeetPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => StandardVolumeFlow.FromStandardCubicFeetPerHour(value.ToDouble(null)); + => StandardVolumeFlow.FromStandardCubicFeetPerHour(value.ToQuantityValue()); #endif - /// + /// public static StandardVolumeFlow StandardCubicFeetPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => StandardVolumeFlow.FromStandardCubicFeetPerMinute(double.CreateChecked(value)); + => StandardVolumeFlow.FromStandardCubicFeetPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => StandardVolumeFlow.FromStandardCubicFeetPerMinute(value.ToDouble(null)); + => StandardVolumeFlow.FromStandardCubicFeetPerMinute(value.ToQuantityValue()); #endif - /// + /// public static StandardVolumeFlow StandardCubicFeetPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => StandardVolumeFlow.FromStandardCubicFeetPerSecond(double.CreateChecked(value)); + => StandardVolumeFlow.FromStandardCubicFeetPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => StandardVolumeFlow.FromStandardCubicFeetPerSecond(value.ToDouble(null)); + => StandardVolumeFlow.FromStandardCubicFeetPerSecond(value.ToQuantityValue()); #endif - /// + /// public static StandardVolumeFlow StandardCubicMetersPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => StandardVolumeFlow.FromStandardCubicMetersPerDay(double.CreateChecked(value)); + => StandardVolumeFlow.FromStandardCubicMetersPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => StandardVolumeFlow.FromStandardCubicMetersPerDay(value.ToDouble(null)); + => StandardVolumeFlow.FromStandardCubicMetersPerDay(value.ToQuantityValue()); #endif - /// + /// public static StandardVolumeFlow StandardCubicMetersPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => StandardVolumeFlow.FromStandardCubicMetersPerHour(double.CreateChecked(value)); + => StandardVolumeFlow.FromStandardCubicMetersPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => StandardVolumeFlow.FromStandardCubicMetersPerHour(value.ToDouble(null)); + => StandardVolumeFlow.FromStandardCubicMetersPerHour(value.ToQuantityValue()); #endif - /// + /// public static StandardVolumeFlow StandardCubicMetersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => StandardVolumeFlow.FromStandardCubicMetersPerMinute(double.CreateChecked(value)); + => StandardVolumeFlow.FromStandardCubicMetersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => StandardVolumeFlow.FromStandardCubicMetersPerMinute(value.ToDouble(null)); + => StandardVolumeFlow.FromStandardCubicMetersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static StandardVolumeFlow StandardCubicMetersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => StandardVolumeFlow.FromStandardCubicMetersPerSecond(double.CreateChecked(value)); + => StandardVolumeFlow.FromStandardCubicMetersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => StandardVolumeFlow.FromStandardCubicMetersPerSecond(value.ToDouble(null)); + => StandardVolumeFlow.FromStandardCubicMetersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static StandardVolumeFlow StandardLitersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => StandardVolumeFlow.FromStandardLitersPerMinute(double.CreateChecked(value)); + => StandardVolumeFlow.FromStandardLitersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => StandardVolumeFlow.FromStandardLitersPerMinute(value.ToDouble(null)); + => StandardVolumeFlow.FromStandardLitersPerMinute(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToTemperatureChangeRateExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToTemperatureChangeRateExtensions.g.cs index d236ae0499..e71814b000 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToTemperatureChangeRateExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToTemperatureChangeRateExtensions.g.cs @@ -32,191 +32,191 @@ namespace UnitsNet.NumberExtensions.NumberToTemperatureChangeRate /// public static class NumberToTemperatureChangeRateExtensions { - /// + /// public static TemperatureChangeRate CentidegreesCelsiusPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureChangeRate.FromCentidegreesCelsiusPerSecond(double.CreateChecked(value)); + => TemperatureChangeRate.FromCentidegreesCelsiusPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureChangeRate.FromCentidegreesCelsiusPerSecond(value.ToDouble(null)); + => TemperatureChangeRate.FromCentidegreesCelsiusPerSecond(value.ToQuantityValue()); #endif - /// + /// public static TemperatureChangeRate DecadegreesCelsiusPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureChangeRate.FromDecadegreesCelsiusPerSecond(double.CreateChecked(value)); + => TemperatureChangeRate.FromDecadegreesCelsiusPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureChangeRate.FromDecadegreesCelsiusPerSecond(value.ToDouble(null)); + => TemperatureChangeRate.FromDecadegreesCelsiusPerSecond(value.ToQuantityValue()); #endif - /// + /// public static TemperatureChangeRate DecidegreesCelsiusPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureChangeRate.FromDecidegreesCelsiusPerSecond(double.CreateChecked(value)); + => TemperatureChangeRate.FromDecidegreesCelsiusPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureChangeRate.FromDecidegreesCelsiusPerSecond(value.ToDouble(null)); + => TemperatureChangeRate.FromDecidegreesCelsiusPerSecond(value.ToQuantityValue()); #endif - /// + /// public static TemperatureChangeRate DegreesCelsiusPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureChangeRate.FromDegreesCelsiusPerHour(double.CreateChecked(value)); + => TemperatureChangeRate.FromDegreesCelsiusPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureChangeRate.FromDegreesCelsiusPerHour(value.ToDouble(null)); + => TemperatureChangeRate.FromDegreesCelsiusPerHour(value.ToQuantityValue()); #endif - /// + /// public static TemperatureChangeRate DegreesCelsiusPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureChangeRate.FromDegreesCelsiusPerMinute(double.CreateChecked(value)); + => TemperatureChangeRate.FromDegreesCelsiusPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureChangeRate.FromDegreesCelsiusPerMinute(value.ToDouble(null)); + => TemperatureChangeRate.FromDegreesCelsiusPerMinute(value.ToQuantityValue()); #endif - /// + /// public static TemperatureChangeRate DegreesCelsiusPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureChangeRate.FromDegreesCelsiusPerSecond(double.CreateChecked(value)); + => TemperatureChangeRate.FromDegreesCelsiusPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureChangeRate.FromDegreesCelsiusPerSecond(value.ToDouble(null)); + => TemperatureChangeRate.FromDegreesCelsiusPerSecond(value.ToQuantityValue()); #endif - /// + /// public static TemperatureChangeRate DegreesFahrenheitPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureChangeRate.FromDegreesFahrenheitPerHour(double.CreateChecked(value)); + => TemperatureChangeRate.FromDegreesFahrenheitPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureChangeRate.FromDegreesFahrenheitPerHour(value.ToDouble(null)); + => TemperatureChangeRate.FromDegreesFahrenheitPerHour(value.ToQuantityValue()); #endif - /// + /// public static TemperatureChangeRate DegreesFahrenheitPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureChangeRate.FromDegreesFahrenheitPerMinute(double.CreateChecked(value)); + => TemperatureChangeRate.FromDegreesFahrenheitPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureChangeRate.FromDegreesFahrenheitPerMinute(value.ToDouble(null)); + => TemperatureChangeRate.FromDegreesFahrenheitPerMinute(value.ToQuantityValue()); #endif - /// + /// public static TemperatureChangeRate DegreesFahrenheitPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureChangeRate.FromDegreesFahrenheitPerSecond(double.CreateChecked(value)); + => TemperatureChangeRate.FromDegreesFahrenheitPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureChangeRate.FromDegreesFahrenheitPerSecond(value.ToDouble(null)); + => TemperatureChangeRate.FromDegreesFahrenheitPerSecond(value.ToQuantityValue()); #endif - /// + /// public static TemperatureChangeRate DegreesKelvinPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureChangeRate.FromDegreesKelvinPerHour(double.CreateChecked(value)); + => TemperatureChangeRate.FromDegreesKelvinPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureChangeRate.FromDegreesKelvinPerHour(value.ToDouble(null)); + => TemperatureChangeRate.FromDegreesKelvinPerHour(value.ToQuantityValue()); #endif - /// + /// public static TemperatureChangeRate DegreesKelvinPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureChangeRate.FromDegreesKelvinPerMinute(double.CreateChecked(value)); + => TemperatureChangeRate.FromDegreesKelvinPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureChangeRate.FromDegreesKelvinPerMinute(value.ToDouble(null)); + => TemperatureChangeRate.FromDegreesKelvinPerMinute(value.ToQuantityValue()); #endif - /// + /// public static TemperatureChangeRate DegreesKelvinPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureChangeRate.FromDegreesKelvinPerSecond(double.CreateChecked(value)); + => TemperatureChangeRate.FromDegreesKelvinPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureChangeRate.FromDegreesKelvinPerSecond(value.ToDouble(null)); + => TemperatureChangeRate.FromDegreesKelvinPerSecond(value.ToQuantityValue()); #endif - /// + /// public static TemperatureChangeRate HectodegreesCelsiusPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureChangeRate.FromHectodegreesCelsiusPerSecond(double.CreateChecked(value)); + => TemperatureChangeRate.FromHectodegreesCelsiusPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureChangeRate.FromHectodegreesCelsiusPerSecond(value.ToDouble(null)); + => TemperatureChangeRate.FromHectodegreesCelsiusPerSecond(value.ToQuantityValue()); #endif - /// + /// public static TemperatureChangeRate KilodegreesCelsiusPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureChangeRate.FromKilodegreesCelsiusPerSecond(double.CreateChecked(value)); + => TemperatureChangeRate.FromKilodegreesCelsiusPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureChangeRate.FromKilodegreesCelsiusPerSecond(value.ToDouble(null)); + => TemperatureChangeRate.FromKilodegreesCelsiusPerSecond(value.ToQuantityValue()); #endif - /// + /// public static TemperatureChangeRate MicrodegreesCelsiusPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureChangeRate.FromMicrodegreesCelsiusPerSecond(double.CreateChecked(value)); + => TemperatureChangeRate.FromMicrodegreesCelsiusPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureChangeRate.FromMicrodegreesCelsiusPerSecond(value.ToDouble(null)); + => TemperatureChangeRate.FromMicrodegreesCelsiusPerSecond(value.ToQuantityValue()); #endif - /// + /// public static TemperatureChangeRate MillidegreesCelsiusPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureChangeRate.FromMillidegreesCelsiusPerSecond(double.CreateChecked(value)); + => TemperatureChangeRate.FromMillidegreesCelsiusPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureChangeRate.FromMillidegreesCelsiusPerSecond(value.ToDouble(null)); + => TemperatureChangeRate.FromMillidegreesCelsiusPerSecond(value.ToQuantityValue()); #endif - /// + /// public static TemperatureChangeRate NanodegreesCelsiusPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureChangeRate.FromNanodegreesCelsiusPerSecond(double.CreateChecked(value)); + => TemperatureChangeRate.FromNanodegreesCelsiusPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureChangeRate.FromNanodegreesCelsiusPerSecond(value.ToDouble(null)); + => TemperatureChangeRate.FromNanodegreesCelsiusPerSecond(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToTemperatureDeltaExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToTemperatureDeltaExtensions.g.cs index 3ed118969c..a280c84c87 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToTemperatureDeltaExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToTemperatureDeltaExtensions.g.cs @@ -32,103 +32,103 @@ namespace UnitsNet.NumberExtensions.NumberToTemperatureDelta /// public static class NumberToTemperatureDeltaExtensions { - /// + /// public static TemperatureDelta DegreesCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureDelta.FromDegreesCelsius(double.CreateChecked(value)); + => TemperatureDelta.FromDegreesCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureDelta.FromDegreesCelsius(value.ToDouble(null)); + => TemperatureDelta.FromDegreesCelsius(value.ToQuantityValue()); #endif - /// + /// public static TemperatureDelta DegreesDelisle(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureDelta.FromDegreesDelisle(double.CreateChecked(value)); + => TemperatureDelta.FromDegreesDelisle(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureDelta.FromDegreesDelisle(value.ToDouble(null)); + => TemperatureDelta.FromDegreesDelisle(value.ToQuantityValue()); #endif - /// + /// public static TemperatureDelta DegreesFahrenheit(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureDelta.FromDegreesFahrenheit(double.CreateChecked(value)); + => TemperatureDelta.FromDegreesFahrenheit(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureDelta.FromDegreesFahrenheit(value.ToDouble(null)); + => TemperatureDelta.FromDegreesFahrenheit(value.ToQuantityValue()); #endif - /// + /// public static TemperatureDelta DegreesNewton(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureDelta.FromDegreesNewton(double.CreateChecked(value)); + => TemperatureDelta.FromDegreesNewton(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureDelta.FromDegreesNewton(value.ToDouble(null)); + => TemperatureDelta.FromDegreesNewton(value.ToQuantityValue()); #endif - /// + /// public static TemperatureDelta DegreesRankine(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureDelta.FromDegreesRankine(double.CreateChecked(value)); + => TemperatureDelta.FromDegreesRankine(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureDelta.FromDegreesRankine(value.ToDouble(null)); + => TemperatureDelta.FromDegreesRankine(value.ToQuantityValue()); #endif - /// + /// public static TemperatureDelta DegreesReaumur(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureDelta.FromDegreesReaumur(double.CreateChecked(value)); + => TemperatureDelta.FromDegreesReaumur(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureDelta.FromDegreesReaumur(value.ToDouble(null)); + => TemperatureDelta.FromDegreesReaumur(value.ToQuantityValue()); #endif - /// + /// public static TemperatureDelta DegreesRoemer(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureDelta.FromDegreesRoemer(double.CreateChecked(value)); + => TemperatureDelta.FromDegreesRoemer(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureDelta.FromDegreesRoemer(value.ToDouble(null)); + => TemperatureDelta.FromDegreesRoemer(value.ToQuantityValue()); #endif - /// + /// public static TemperatureDelta Kelvins(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureDelta.FromKelvins(double.CreateChecked(value)); + => TemperatureDelta.FromKelvins(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureDelta.FromKelvins(value.ToDouble(null)); + => TemperatureDelta.FromKelvins(value.ToQuantityValue()); #endif - /// + /// public static TemperatureDelta MillidegreesCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureDelta.FromMillidegreesCelsius(double.CreateChecked(value)); + => TemperatureDelta.FromMillidegreesCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureDelta.FromMillidegreesCelsius(value.ToDouble(null)); + => TemperatureDelta.FromMillidegreesCelsius(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToTemperatureExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToTemperatureExtensions.g.cs index ec97af50a2..66c4f2f357 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToTemperatureExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToTemperatureExtensions.g.cs @@ -32,114 +32,114 @@ namespace UnitsNet.NumberExtensions.NumberToTemperature /// public static class NumberToTemperatureExtensions { - /// + /// public static Temperature DegreesCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Temperature.FromDegreesCelsius(double.CreateChecked(value)); + => Temperature.FromDegreesCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => Temperature.FromDegreesCelsius(value.ToDouble(null)); + => Temperature.FromDegreesCelsius(value.ToQuantityValue()); #endif - /// + /// public static Temperature DegreesDelisle(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Temperature.FromDegreesDelisle(double.CreateChecked(value)); + => Temperature.FromDegreesDelisle(QuantityValue.CreateChecked(value)); #else , IConvertible - => Temperature.FromDegreesDelisle(value.ToDouble(null)); + => Temperature.FromDegreesDelisle(value.ToQuantityValue()); #endif - /// + /// public static Temperature DegreesFahrenheit(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Temperature.FromDegreesFahrenheit(double.CreateChecked(value)); + => Temperature.FromDegreesFahrenheit(QuantityValue.CreateChecked(value)); #else , IConvertible - => Temperature.FromDegreesFahrenheit(value.ToDouble(null)); + => Temperature.FromDegreesFahrenheit(value.ToQuantityValue()); #endif - /// + /// public static Temperature DegreesNewton(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Temperature.FromDegreesNewton(double.CreateChecked(value)); + => Temperature.FromDegreesNewton(QuantityValue.CreateChecked(value)); #else , IConvertible - => Temperature.FromDegreesNewton(value.ToDouble(null)); + => Temperature.FromDegreesNewton(value.ToQuantityValue()); #endif - /// + /// public static Temperature DegreesRankine(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Temperature.FromDegreesRankine(double.CreateChecked(value)); + => Temperature.FromDegreesRankine(QuantityValue.CreateChecked(value)); #else , IConvertible - => Temperature.FromDegreesRankine(value.ToDouble(null)); + => Temperature.FromDegreesRankine(value.ToQuantityValue()); #endif - /// + /// public static Temperature DegreesReaumur(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Temperature.FromDegreesReaumur(double.CreateChecked(value)); + => Temperature.FromDegreesReaumur(QuantityValue.CreateChecked(value)); #else , IConvertible - => Temperature.FromDegreesReaumur(value.ToDouble(null)); + => Temperature.FromDegreesReaumur(value.ToQuantityValue()); #endif - /// + /// public static Temperature DegreesRoemer(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Temperature.FromDegreesRoemer(double.CreateChecked(value)); + => Temperature.FromDegreesRoemer(QuantityValue.CreateChecked(value)); #else , IConvertible - => Temperature.FromDegreesRoemer(value.ToDouble(null)); + => Temperature.FromDegreesRoemer(value.ToQuantityValue()); #endif - /// + /// public static Temperature Kelvins(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Temperature.FromKelvins(double.CreateChecked(value)); + => Temperature.FromKelvins(QuantityValue.CreateChecked(value)); #else , IConvertible - => Temperature.FromKelvins(value.ToDouble(null)); + => Temperature.FromKelvins(value.ToQuantityValue()); #endif - /// + /// public static Temperature MillidegreesCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Temperature.FromMillidegreesCelsius(double.CreateChecked(value)); + => Temperature.FromMillidegreesCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => Temperature.FromMillidegreesCelsius(value.ToDouble(null)); + => Temperature.FromMillidegreesCelsius(value.ToQuantityValue()); #endif - /// + /// public static Temperature SolarTemperatures(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Temperature.FromSolarTemperatures(double.CreateChecked(value)); + => Temperature.FromSolarTemperatures(QuantityValue.CreateChecked(value)); #else , IConvertible - => Temperature.FromSolarTemperatures(value.ToDouble(null)); + => Temperature.FromSolarTemperatures(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToTemperatureGradientExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToTemperatureGradientExtensions.g.cs index 12302bd6a5..39b50cba92 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToTemperatureGradientExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToTemperatureGradientExtensions.g.cs @@ -32,48 +32,48 @@ namespace UnitsNet.NumberExtensions.NumberToTemperatureGradient /// public static class NumberToTemperatureGradientExtensions { - /// + /// public static TemperatureGradient DegreesCelsiusPerKilometer(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureGradient.FromDegreesCelsiusPerKilometer(double.CreateChecked(value)); + => TemperatureGradient.FromDegreesCelsiusPerKilometer(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureGradient.FromDegreesCelsiusPerKilometer(value.ToDouble(null)); + => TemperatureGradient.FromDegreesCelsiusPerKilometer(value.ToQuantityValue()); #endif - /// + /// public static TemperatureGradient DegreesCelsiusPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureGradient.FromDegreesCelsiusPerMeter(double.CreateChecked(value)); + => TemperatureGradient.FromDegreesCelsiusPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureGradient.FromDegreesCelsiusPerMeter(value.ToDouble(null)); + => TemperatureGradient.FromDegreesCelsiusPerMeter(value.ToQuantityValue()); #endif - /// + /// public static TemperatureGradient DegreesFahrenheitPerFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureGradient.FromDegreesFahrenheitPerFoot(double.CreateChecked(value)); + => TemperatureGradient.FromDegreesFahrenheitPerFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureGradient.FromDegreesFahrenheitPerFoot(value.ToDouble(null)); + => TemperatureGradient.FromDegreesFahrenheitPerFoot(value.ToQuantityValue()); #endif - /// + /// public static TemperatureGradient KelvinsPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => TemperatureGradient.FromKelvinsPerMeter(double.CreateChecked(value)); + => TemperatureGradient.FromKelvinsPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => TemperatureGradient.FromKelvinsPerMeter(value.ToDouble(null)); + => TemperatureGradient.FromKelvinsPerMeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToThermalConductivityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToThermalConductivityExtensions.g.cs index 8b9539d7f3..db516aeea2 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToThermalConductivityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToThermalConductivityExtensions.g.cs @@ -32,26 +32,26 @@ namespace UnitsNet.NumberExtensions.NumberToThermalConductivity /// public static class NumberToThermalConductivityExtensions { - /// + /// public static ThermalConductivity BtusPerHourFootFahrenheit(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ThermalConductivity.FromBtusPerHourFootFahrenheit(double.CreateChecked(value)); + => ThermalConductivity.FromBtusPerHourFootFahrenheit(QuantityValue.CreateChecked(value)); #else , IConvertible - => ThermalConductivity.FromBtusPerHourFootFahrenheit(value.ToDouble(null)); + => ThermalConductivity.FromBtusPerHourFootFahrenheit(value.ToQuantityValue()); #endif - /// + /// public static ThermalConductivity WattsPerMeterKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ThermalConductivity.FromWattsPerMeterKelvin(double.CreateChecked(value)); + => ThermalConductivity.FromWattsPerMeterKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => ThermalConductivity.FromWattsPerMeterKelvin(value.ToDouble(null)); + => ThermalConductivity.FromWattsPerMeterKelvin(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToThermalInsulanceExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToThermalInsulanceExtensions.g.cs index 6b90922967..df46662a52 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToThermalInsulanceExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToThermalInsulanceExtensions.g.cs @@ -32,81 +32,81 @@ namespace UnitsNet.NumberExtensions.NumberToThermalInsulance /// public static class NumberToThermalInsulanceExtensions { - /// + /// public static ThermalInsulance HourSquareFeetDegreesFahrenheitPerBtu(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ThermalInsulance.FromHourSquareFeetDegreesFahrenheitPerBtu(double.CreateChecked(value)); + => ThermalInsulance.FromHourSquareFeetDegreesFahrenheitPerBtu(QuantityValue.CreateChecked(value)); #else , IConvertible - => ThermalInsulance.FromHourSquareFeetDegreesFahrenheitPerBtu(value.ToDouble(null)); + => ThermalInsulance.FromHourSquareFeetDegreesFahrenheitPerBtu(value.ToQuantityValue()); #endif - /// + /// public static ThermalInsulance SquareCentimeterHourDegreesCelsiusPerKilocalorie(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ThermalInsulance.FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(double.CreateChecked(value)); + => ThermalInsulance.FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(QuantityValue.CreateChecked(value)); #else , IConvertible - => ThermalInsulance.FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(value.ToDouble(null)); + => ThermalInsulance.FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(value.ToQuantityValue()); #endif - /// + /// public static ThermalInsulance SquareCentimeterKelvinsPerWatt(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ThermalInsulance.FromSquareCentimeterKelvinsPerWatt(double.CreateChecked(value)); + => ThermalInsulance.FromSquareCentimeterKelvinsPerWatt(QuantityValue.CreateChecked(value)); #else , IConvertible - => ThermalInsulance.FromSquareCentimeterKelvinsPerWatt(value.ToDouble(null)); + => ThermalInsulance.FromSquareCentimeterKelvinsPerWatt(value.ToQuantityValue()); #endif - /// + /// public static ThermalInsulance SquareMeterDegreesCelsiusPerWatt(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ThermalInsulance.FromSquareMeterDegreesCelsiusPerWatt(double.CreateChecked(value)); + => ThermalInsulance.FromSquareMeterDegreesCelsiusPerWatt(QuantityValue.CreateChecked(value)); #else , IConvertible - => ThermalInsulance.FromSquareMeterDegreesCelsiusPerWatt(value.ToDouble(null)); + => ThermalInsulance.FromSquareMeterDegreesCelsiusPerWatt(value.ToQuantityValue()); #endif - /// + /// public static ThermalInsulance SquareMeterKelvinsPerKilowatt(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(double.CreateChecked(value)); + => ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(QuantityValue.CreateChecked(value)); #else , IConvertible - => ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(value.ToDouble(null)); + => ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(value.ToQuantityValue()); #endif - /// + /// public static ThermalInsulance SquareMeterKelvinsPerWatt(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ThermalInsulance.FromSquareMeterKelvinsPerWatt(double.CreateChecked(value)); + => ThermalInsulance.FromSquareMeterKelvinsPerWatt(QuantityValue.CreateChecked(value)); #else , IConvertible - => ThermalInsulance.FromSquareMeterKelvinsPerWatt(value.ToDouble(null)); + => ThermalInsulance.FromSquareMeterKelvinsPerWatt(value.ToQuantityValue()); #endif - /// + /// public static ThermalInsulance SquareMillimeterKelvinsPerWatt(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ThermalInsulance.FromSquareMillimeterKelvinsPerWatt(double.CreateChecked(value)); + => ThermalInsulance.FromSquareMillimeterKelvinsPerWatt(QuantityValue.CreateChecked(value)); #else , IConvertible - => ThermalInsulance.FromSquareMillimeterKelvinsPerWatt(value.ToDouble(null)); + => ThermalInsulance.FromSquareMillimeterKelvinsPerWatt(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToThermalResistanceExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToThermalResistanceExtensions.g.cs index b2c18e4c12..d8e96cfa92 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToThermalResistanceExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToThermalResistanceExtensions.g.cs @@ -32,26 +32,26 @@ namespace UnitsNet.NumberExtensions.NumberToThermalResistance /// public static class NumberToThermalResistanceExtensions { - /// + /// public static ThermalResistance DegreesCelsiusPerWatt(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ThermalResistance.FromDegreesCelsiusPerWatt(double.CreateChecked(value)); + => ThermalResistance.FromDegreesCelsiusPerWatt(QuantityValue.CreateChecked(value)); #else , IConvertible - => ThermalResistance.FromDegreesCelsiusPerWatt(value.ToDouble(null)); + => ThermalResistance.FromDegreesCelsiusPerWatt(value.ToQuantityValue()); #endif - /// + /// public static ThermalResistance KelvinsPerWatt(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => ThermalResistance.FromKelvinsPerWatt(double.CreateChecked(value)); + => ThermalResistance.FromKelvinsPerWatt(QuantityValue.CreateChecked(value)); #else , IConvertible - => ThermalResistance.FromKelvinsPerWatt(value.ToDouble(null)); + => ThermalResistance.FromKelvinsPerWatt(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToTorqueExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToTorqueExtensions.g.cs index 8fcea0a9be..9d37ada29f 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToTorqueExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToTorqueExtensions.g.cs @@ -32,279 +32,279 @@ namespace UnitsNet.NumberExtensions.NumberToTorque /// public static class NumberToTorqueExtensions { - /// + /// public static Torque GramForceCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromGramForceCentimeters(double.CreateChecked(value)); + => Torque.FromGramForceCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromGramForceCentimeters(value.ToDouble(null)); + => Torque.FromGramForceCentimeters(value.ToQuantityValue()); #endif - /// + /// public static Torque GramForceMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromGramForceMeters(double.CreateChecked(value)); + => Torque.FromGramForceMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromGramForceMeters(value.ToDouble(null)); + => Torque.FromGramForceMeters(value.ToQuantityValue()); #endif - /// + /// public static Torque GramForceMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromGramForceMillimeters(double.CreateChecked(value)); + => Torque.FromGramForceMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromGramForceMillimeters(value.ToDouble(null)); + => Torque.FromGramForceMillimeters(value.ToQuantityValue()); #endif - /// + /// public static Torque KilogramForceCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromKilogramForceCentimeters(double.CreateChecked(value)); + => Torque.FromKilogramForceCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromKilogramForceCentimeters(value.ToDouble(null)); + => Torque.FromKilogramForceCentimeters(value.ToQuantityValue()); #endif - /// + /// public static Torque KilogramForceMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromKilogramForceMeters(double.CreateChecked(value)); + => Torque.FromKilogramForceMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromKilogramForceMeters(value.ToDouble(null)); + => Torque.FromKilogramForceMeters(value.ToQuantityValue()); #endif - /// + /// public static Torque KilogramForceMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromKilogramForceMillimeters(double.CreateChecked(value)); + => Torque.FromKilogramForceMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromKilogramForceMillimeters(value.ToDouble(null)); + => Torque.FromKilogramForceMillimeters(value.ToQuantityValue()); #endif - /// + /// public static Torque KilonewtonCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromKilonewtonCentimeters(double.CreateChecked(value)); + => Torque.FromKilonewtonCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromKilonewtonCentimeters(value.ToDouble(null)); + => Torque.FromKilonewtonCentimeters(value.ToQuantityValue()); #endif - /// + /// public static Torque KilonewtonMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromKilonewtonMeters(double.CreateChecked(value)); + => Torque.FromKilonewtonMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromKilonewtonMeters(value.ToDouble(null)); + => Torque.FromKilonewtonMeters(value.ToQuantityValue()); #endif - /// + /// public static Torque KilonewtonMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromKilonewtonMillimeters(double.CreateChecked(value)); + => Torque.FromKilonewtonMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromKilonewtonMillimeters(value.ToDouble(null)); + => Torque.FromKilonewtonMillimeters(value.ToQuantityValue()); #endif - /// + /// public static Torque KilopoundForceFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromKilopoundForceFeet(double.CreateChecked(value)); + => Torque.FromKilopoundForceFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromKilopoundForceFeet(value.ToDouble(null)); + => Torque.FromKilopoundForceFeet(value.ToQuantityValue()); #endif - /// + /// public static Torque KilopoundForceInches(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromKilopoundForceInches(double.CreateChecked(value)); + => Torque.FromKilopoundForceInches(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromKilopoundForceInches(value.ToDouble(null)); + => Torque.FromKilopoundForceInches(value.ToQuantityValue()); #endif - /// + /// public static Torque MeganewtonCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromMeganewtonCentimeters(double.CreateChecked(value)); + => Torque.FromMeganewtonCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromMeganewtonCentimeters(value.ToDouble(null)); + => Torque.FromMeganewtonCentimeters(value.ToQuantityValue()); #endif - /// + /// public static Torque MeganewtonMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromMeganewtonMeters(double.CreateChecked(value)); + => Torque.FromMeganewtonMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromMeganewtonMeters(value.ToDouble(null)); + => Torque.FromMeganewtonMeters(value.ToQuantityValue()); #endif - /// + /// public static Torque MeganewtonMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromMeganewtonMillimeters(double.CreateChecked(value)); + => Torque.FromMeganewtonMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromMeganewtonMillimeters(value.ToDouble(null)); + => Torque.FromMeganewtonMillimeters(value.ToQuantityValue()); #endif - /// + /// public static Torque MegapoundForceFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromMegapoundForceFeet(double.CreateChecked(value)); + => Torque.FromMegapoundForceFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromMegapoundForceFeet(value.ToDouble(null)); + => Torque.FromMegapoundForceFeet(value.ToQuantityValue()); #endif - /// + /// public static Torque MegapoundForceInches(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromMegapoundForceInches(double.CreateChecked(value)); + => Torque.FromMegapoundForceInches(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromMegapoundForceInches(value.ToDouble(null)); + => Torque.FromMegapoundForceInches(value.ToQuantityValue()); #endif - /// + /// public static Torque NewtonCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromNewtonCentimeters(double.CreateChecked(value)); + => Torque.FromNewtonCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromNewtonCentimeters(value.ToDouble(null)); + => Torque.FromNewtonCentimeters(value.ToQuantityValue()); #endif - /// + /// public static Torque NewtonMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromNewtonMeters(double.CreateChecked(value)); + => Torque.FromNewtonMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromNewtonMeters(value.ToDouble(null)); + => Torque.FromNewtonMeters(value.ToQuantityValue()); #endif - /// + /// public static Torque NewtonMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromNewtonMillimeters(double.CreateChecked(value)); + => Torque.FromNewtonMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromNewtonMillimeters(value.ToDouble(null)); + => Torque.FromNewtonMillimeters(value.ToQuantityValue()); #endif - /// + /// public static Torque PoundalFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromPoundalFeet(double.CreateChecked(value)); + => Torque.FromPoundalFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromPoundalFeet(value.ToDouble(null)); + => Torque.FromPoundalFeet(value.ToQuantityValue()); #endif - /// + /// public static Torque PoundForceFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromPoundForceFeet(double.CreateChecked(value)); + => Torque.FromPoundForceFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromPoundForceFeet(value.ToDouble(null)); + => Torque.FromPoundForceFeet(value.ToQuantityValue()); #endif - /// + /// public static Torque PoundForceInches(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromPoundForceInches(double.CreateChecked(value)); + => Torque.FromPoundForceInches(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromPoundForceInches(value.ToDouble(null)); + => Torque.FromPoundForceInches(value.ToQuantityValue()); #endif - /// + /// public static Torque TonneForceCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromTonneForceCentimeters(double.CreateChecked(value)); + => Torque.FromTonneForceCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromTonneForceCentimeters(value.ToDouble(null)); + => Torque.FromTonneForceCentimeters(value.ToQuantityValue()); #endif - /// + /// public static Torque TonneForceMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromTonneForceMeters(double.CreateChecked(value)); + => Torque.FromTonneForceMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromTonneForceMeters(value.ToDouble(null)); + => Torque.FromTonneForceMeters(value.ToQuantityValue()); #endif - /// + /// public static Torque TonneForceMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Torque.FromTonneForceMillimeters(double.CreateChecked(value)); + => Torque.FromTonneForceMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Torque.FromTonneForceMillimeters(value.ToDouble(null)); + => Torque.FromTonneForceMillimeters(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToTurbidityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToTurbidityExtensions.g.cs index 8e0c38ad6f..75a0c33069 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToTurbidityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToTurbidityExtensions.g.cs @@ -32,15 +32,15 @@ namespace UnitsNet.NumberExtensions.NumberToTurbidity /// public static class NumberToTurbidityExtensions { - /// + /// public static Turbidity NTU(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Turbidity.FromNTU(double.CreateChecked(value)); + => Turbidity.FromNTU(QuantityValue.CreateChecked(value)); #else , IConvertible - => Turbidity.FromNTU(value.ToDouble(null)); + => Turbidity.FromNTU(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToVitaminAExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToVitaminAExtensions.g.cs index 4a1fe53313..14c93e23b1 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToVitaminAExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToVitaminAExtensions.g.cs @@ -32,15 +32,15 @@ namespace UnitsNet.NumberExtensions.NumberToVitaminA /// public static class NumberToVitaminAExtensions { - /// + /// public static VitaminA InternationalUnits(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VitaminA.FromInternationalUnits(double.CreateChecked(value)); + => VitaminA.FromInternationalUnits(QuantityValue.CreateChecked(value)); #else , IConvertible - => VitaminA.FromInternationalUnits(value.ToDouble(null)); + => VitaminA.FromInternationalUnits(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumeConcentrationExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumeConcentrationExtensions.g.cs index 9ccb786e82..f2f26c5fa1 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumeConcentrationExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumeConcentrationExtensions.g.cs @@ -32,224 +32,224 @@ namespace UnitsNet.NumberExtensions.NumberToVolumeConcentration /// public static class NumberToVolumeConcentrationExtensions { - /// + /// public static VolumeConcentration CentilitersPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromCentilitersPerLiter(double.CreateChecked(value)); + => VolumeConcentration.FromCentilitersPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromCentilitersPerLiter(value.ToDouble(null)); + => VolumeConcentration.FromCentilitersPerLiter(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration CentilitersPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromCentilitersPerMilliliter(double.CreateChecked(value)); + => VolumeConcentration.FromCentilitersPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromCentilitersPerMilliliter(value.ToDouble(null)); + => VolumeConcentration.FromCentilitersPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration DecilitersPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromDecilitersPerLiter(double.CreateChecked(value)); + => VolumeConcentration.FromDecilitersPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromDecilitersPerLiter(value.ToDouble(null)); + => VolumeConcentration.FromDecilitersPerLiter(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration DecilitersPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromDecilitersPerMilliliter(double.CreateChecked(value)); + => VolumeConcentration.FromDecilitersPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromDecilitersPerMilliliter(value.ToDouble(null)); + => VolumeConcentration.FromDecilitersPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration DecimalFractions(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromDecimalFractions(double.CreateChecked(value)); + => VolumeConcentration.FromDecimalFractions(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromDecimalFractions(value.ToDouble(null)); + => VolumeConcentration.FromDecimalFractions(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration LitersPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromLitersPerLiter(double.CreateChecked(value)); + => VolumeConcentration.FromLitersPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromLitersPerLiter(value.ToDouble(null)); + => VolumeConcentration.FromLitersPerLiter(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration LitersPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromLitersPerMilliliter(double.CreateChecked(value)); + => VolumeConcentration.FromLitersPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromLitersPerMilliliter(value.ToDouble(null)); + => VolumeConcentration.FromLitersPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration MicrolitersPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromMicrolitersPerLiter(double.CreateChecked(value)); + => VolumeConcentration.FromMicrolitersPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromMicrolitersPerLiter(value.ToDouble(null)); + => VolumeConcentration.FromMicrolitersPerLiter(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration MicrolitersPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromMicrolitersPerMilliliter(double.CreateChecked(value)); + => VolumeConcentration.FromMicrolitersPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromMicrolitersPerMilliliter(value.ToDouble(null)); + => VolumeConcentration.FromMicrolitersPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration MillilitersPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromMillilitersPerLiter(double.CreateChecked(value)); + => VolumeConcentration.FromMillilitersPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromMillilitersPerLiter(value.ToDouble(null)); + => VolumeConcentration.FromMillilitersPerLiter(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration MillilitersPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromMillilitersPerMilliliter(double.CreateChecked(value)); + => VolumeConcentration.FromMillilitersPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromMillilitersPerMilliliter(value.ToDouble(null)); + => VolumeConcentration.FromMillilitersPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration NanolitersPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromNanolitersPerLiter(double.CreateChecked(value)); + => VolumeConcentration.FromNanolitersPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromNanolitersPerLiter(value.ToDouble(null)); + => VolumeConcentration.FromNanolitersPerLiter(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration NanolitersPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromNanolitersPerMilliliter(double.CreateChecked(value)); + => VolumeConcentration.FromNanolitersPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromNanolitersPerMilliliter(value.ToDouble(null)); + => VolumeConcentration.FromNanolitersPerMilliliter(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration PartsPerBillion(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromPartsPerBillion(double.CreateChecked(value)); + => VolumeConcentration.FromPartsPerBillion(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromPartsPerBillion(value.ToDouble(null)); + => VolumeConcentration.FromPartsPerBillion(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration PartsPerMillion(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromPartsPerMillion(double.CreateChecked(value)); + => VolumeConcentration.FromPartsPerMillion(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromPartsPerMillion(value.ToDouble(null)); + => VolumeConcentration.FromPartsPerMillion(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration PartsPerThousand(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromPartsPerThousand(double.CreateChecked(value)); + => VolumeConcentration.FromPartsPerThousand(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromPartsPerThousand(value.ToDouble(null)); + => VolumeConcentration.FromPartsPerThousand(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration PartsPerTrillion(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromPartsPerTrillion(double.CreateChecked(value)); + => VolumeConcentration.FromPartsPerTrillion(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromPartsPerTrillion(value.ToDouble(null)); + => VolumeConcentration.FromPartsPerTrillion(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration Percent(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromPercent(double.CreateChecked(value)); + => VolumeConcentration.FromPercent(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromPercent(value.ToDouble(null)); + => VolumeConcentration.FromPercent(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration PicolitersPerLiter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromPicolitersPerLiter(double.CreateChecked(value)); + => VolumeConcentration.FromPicolitersPerLiter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromPicolitersPerLiter(value.ToDouble(null)); + => VolumeConcentration.FromPicolitersPerLiter(value.ToQuantityValue()); #endif - /// + /// public static VolumeConcentration PicolitersPerMilliliter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeConcentration.FromPicolitersPerMilliliter(double.CreateChecked(value)); + => VolumeConcentration.FromPicolitersPerMilliliter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeConcentration.FromPicolitersPerMilliliter(value.ToDouble(null)); + => VolumeConcentration.FromPicolitersPerMilliliter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumeExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumeExtensions.g.cs index d425a5ed28..0f12867a4a 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumeExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumeExtensions.g.cs @@ -32,598 +32,598 @@ namespace UnitsNet.NumberExtensions.NumberToVolume /// public static class NumberToVolumeExtensions { - /// + /// public static Volume AcreFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromAcreFeet(double.CreateChecked(value)); + => Volume.FromAcreFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromAcreFeet(value.ToDouble(null)); + => Volume.FromAcreFeet(value.ToQuantityValue()); #endif - /// + /// public static Volume AuTablespoons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromAuTablespoons(double.CreateChecked(value)); + => Volume.FromAuTablespoons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromAuTablespoons(value.ToDouble(null)); + => Volume.FromAuTablespoons(value.ToQuantityValue()); #endif - /// + /// public static Volume BoardFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromBoardFeet(double.CreateChecked(value)); + => Volume.FromBoardFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromBoardFeet(value.ToDouble(null)); + => Volume.FromBoardFeet(value.ToQuantityValue()); #endif - /// + /// public static Volume Centiliters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromCentiliters(double.CreateChecked(value)); + => Volume.FromCentiliters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromCentiliters(value.ToDouble(null)); + => Volume.FromCentiliters(value.ToQuantityValue()); #endif - /// + /// public static Volume CubicCentimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromCubicCentimeters(double.CreateChecked(value)); + => Volume.FromCubicCentimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromCubicCentimeters(value.ToDouble(null)); + => Volume.FromCubicCentimeters(value.ToQuantityValue()); #endif - /// + /// public static Volume CubicDecimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromCubicDecimeters(double.CreateChecked(value)); + => Volume.FromCubicDecimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromCubicDecimeters(value.ToDouble(null)); + => Volume.FromCubicDecimeters(value.ToQuantityValue()); #endif - /// + /// public static Volume CubicFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromCubicFeet(double.CreateChecked(value)); + => Volume.FromCubicFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromCubicFeet(value.ToDouble(null)); + => Volume.FromCubicFeet(value.ToQuantityValue()); #endif - /// + /// public static Volume CubicHectometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromCubicHectometers(double.CreateChecked(value)); + => Volume.FromCubicHectometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromCubicHectometers(value.ToDouble(null)); + => Volume.FromCubicHectometers(value.ToQuantityValue()); #endif - /// + /// public static Volume CubicInches(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromCubicInches(double.CreateChecked(value)); + => Volume.FromCubicInches(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromCubicInches(value.ToDouble(null)); + => Volume.FromCubicInches(value.ToQuantityValue()); #endif - /// + /// public static Volume CubicKilometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromCubicKilometers(double.CreateChecked(value)); + => Volume.FromCubicKilometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromCubicKilometers(value.ToDouble(null)); + => Volume.FromCubicKilometers(value.ToQuantityValue()); #endif - /// + /// public static Volume CubicMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromCubicMeters(double.CreateChecked(value)); + => Volume.FromCubicMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromCubicMeters(value.ToDouble(null)); + => Volume.FromCubicMeters(value.ToQuantityValue()); #endif - /// + /// public static Volume CubicMicrometers(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromCubicMicrometers(double.CreateChecked(value)); + => Volume.FromCubicMicrometers(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromCubicMicrometers(value.ToDouble(null)); + => Volume.FromCubicMicrometers(value.ToQuantityValue()); #endif - /// + /// public static Volume CubicMiles(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromCubicMiles(double.CreateChecked(value)); + => Volume.FromCubicMiles(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromCubicMiles(value.ToDouble(null)); + => Volume.FromCubicMiles(value.ToQuantityValue()); #endif - /// + /// public static Volume CubicMillimeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromCubicMillimeters(double.CreateChecked(value)); + => Volume.FromCubicMillimeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromCubicMillimeters(value.ToDouble(null)); + => Volume.FromCubicMillimeters(value.ToQuantityValue()); #endif - /// + /// public static Volume CubicYards(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromCubicYards(double.CreateChecked(value)); + => Volume.FromCubicYards(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromCubicYards(value.ToDouble(null)); + => Volume.FromCubicYards(value.ToQuantityValue()); #endif - /// + /// public static Volume Decaliters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromDecaliters(double.CreateChecked(value)); + => Volume.FromDecaliters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromDecaliters(value.ToDouble(null)); + => Volume.FromDecaliters(value.ToQuantityValue()); #endif - /// + /// public static Volume DecausGallons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromDecausGallons(double.CreateChecked(value)); + => Volume.FromDecausGallons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromDecausGallons(value.ToDouble(null)); + => Volume.FromDecausGallons(value.ToQuantityValue()); #endif - /// + /// public static Volume Deciliters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromDeciliters(double.CreateChecked(value)); + => Volume.FromDeciliters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromDeciliters(value.ToDouble(null)); + => Volume.FromDeciliters(value.ToQuantityValue()); #endif - /// + /// public static Volume DeciusGallons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromDeciusGallons(double.CreateChecked(value)); + => Volume.FromDeciusGallons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromDeciusGallons(value.ToDouble(null)); + => Volume.FromDeciusGallons(value.ToQuantityValue()); #endif - /// + /// public static Volume HectocubicFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromHectocubicFeet(double.CreateChecked(value)); + => Volume.FromHectocubicFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromHectocubicFeet(value.ToDouble(null)); + => Volume.FromHectocubicFeet(value.ToQuantityValue()); #endif - /// + /// public static Volume HectocubicMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromHectocubicMeters(double.CreateChecked(value)); + => Volume.FromHectocubicMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromHectocubicMeters(value.ToDouble(null)); + => Volume.FromHectocubicMeters(value.ToQuantityValue()); #endif - /// + /// public static Volume Hectoliters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromHectoliters(double.CreateChecked(value)); + => Volume.FromHectoliters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromHectoliters(value.ToDouble(null)); + => Volume.FromHectoliters(value.ToQuantityValue()); #endif - /// + /// public static Volume HectousGallons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromHectousGallons(double.CreateChecked(value)); + => Volume.FromHectousGallons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromHectousGallons(value.ToDouble(null)); + => Volume.FromHectousGallons(value.ToQuantityValue()); #endif - /// + /// public static Volume ImperialBeerBarrels(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromImperialBeerBarrels(double.CreateChecked(value)); + => Volume.FromImperialBeerBarrels(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromImperialBeerBarrels(value.ToDouble(null)); + => Volume.FromImperialBeerBarrels(value.ToQuantityValue()); #endif - /// + /// public static Volume ImperialGallons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromImperialGallons(double.CreateChecked(value)); + => Volume.FromImperialGallons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromImperialGallons(value.ToDouble(null)); + => Volume.FromImperialGallons(value.ToQuantityValue()); #endif - /// + /// public static Volume ImperialOunces(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromImperialOunces(double.CreateChecked(value)); + => Volume.FromImperialOunces(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromImperialOunces(value.ToDouble(null)); + => Volume.FromImperialOunces(value.ToQuantityValue()); #endif - /// + /// public static Volume ImperialPints(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromImperialPints(double.CreateChecked(value)); + => Volume.FromImperialPints(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromImperialPints(value.ToDouble(null)); + => Volume.FromImperialPints(value.ToQuantityValue()); #endif - /// + /// public static Volume ImperialQuarts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromImperialQuarts(double.CreateChecked(value)); + => Volume.FromImperialQuarts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromImperialQuarts(value.ToDouble(null)); + => Volume.FromImperialQuarts(value.ToQuantityValue()); #endif - /// + /// public static Volume KilocubicFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromKilocubicFeet(double.CreateChecked(value)); + => Volume.FromKilocubicFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromKilocubicFeet(value.ToDouble(null)); + => Volume.FromKilocubicFeet(value.ToQuantityValue()); #endif - /// + /// public static Volume KilocubicMeters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromKilocubicMeters(double.CreateChecked(value)); + => Volume.FromKilocubicMeters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromKilocubicMeters(value.ToDouble(null)); + => Volume.FromKilocubicMeters(value.ToQuantityValue()); #endif - /// + /// public static Volume KiloimperialGallons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromKiloimperialGallons(double.CreateChecked(value)); + => Volume.FromKiloimperialGallons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromKiloimperialGallons(value.ToDouble(null)); + => Volume.FromKiloimperialGallons(value.ToQuantityValue()); #endif - /// + /// public static Volume Kiloliters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromKiloliters(double.CreateChecked(value)); + => Volume.FromKiloliters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromKiloliters(value.ToDouble(null)); + => Volume.FromKiloliters(value.ToQuantityValue()); #endif - /// + /// public static Volume KilousGallons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromKilousGallons(double.CreateChecked(value)); + => Volume.FromKilousGallons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromKilousGallons(value.ToDouble(null)); + => Volume.FromKilousGallons(value.ToQuantityValue()); #endif - /// + /// public static Volume Liters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromLiters(double.CreateChecked(value)); + => Volume.FromLiters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromLiters(value.ToDouble(null)); + => Volume.FromLiters(value.ToQuantityValue()); #endif - /// + /// public static Volume MegacubicFeet(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromMegacubicFeet(double.CreateChecked(value)); + => Volume.FromMegacubicFeet(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromMegacubicFeet(value.ToDouble(null)); + => Volume.FromMegacubicFeet(value.ToQuantityValue()); #endif - /// + /// public static Volume MegaimperialGallons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromMegaimperialGallons(double.CreateChecked(value)); + => Volume.FromMegaimperialGallons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromMegaimperialGallons(value.ToDouble(null)); + => Volume.FromMegaimperialGallons(value.ToQuantityValue()); #endif - /// + /// public static Volume Megaliters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromMegaliters(double.CreateChecked(value)); + => Volume.FromMegaliters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromMegaliters(value.ToDouble(null)); + => Volume.FromMegaliters(value.ToQuantityValue()); #endif - /// + /// public static Volume MegausGallons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromMegausGallons(double.CreateChecked(value)); + => Volume.FromMegausGallons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromMegausGallons(value.ToDouble(null)); + => Volume.FromMegausGallons(value.ToQuantityValue()); #endif - /// + /// public static Volume MetricCups(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromMetricCups(double.CreateChecked(value)); + => Volume.FromMetricCups(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromMetricCups(value.ToDouble(null)); + => Volume.FromMetricCups(value.ToQuantityValue()); #endif - /// + /// public static Volume MetricTeaspoons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromMetricTeaspoons(double.CreateChecked(value)); + => Volume.FromMetricTeaspoons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromMetricTeaspoons(value.ToDouble(null)); + => Volume.FromMetricTeaspoons(value.ToQuantityValue()); #endif - /// + /// public static Volume Microliters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromMicroliters(double.CreateChecked(value)); + => Volume.FromMicroliters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromMicroliters(value.ToDouble(null)); + => Volume.FromMicroliters(value.ToQuantityValue()); #endif - /// + /// public static Volume Milliliters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromMilliliters(double.CreateChecked(value)); + => Volume.FromMilliliters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromMilliliters(value.ToDouble(null)); + => Volume.FromMilliliters(value.ToQuantityValue()); #endif - /// + /// public static Volume Nanoliters(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromNanoliters(double.CreateChecked(value)); + => Volume.FromNanoliters(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromNanoliters(value.ToDouble(null)); + => Volume.FromNanoliters(value.ToQuantityValue()); #endif - /// + /// public static Volume OilBarrels(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromOilBarrels(double.CreateChecked(value)); + => Volume.FromOilBarrels(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromOilBarrels(value.ToDouble(null)); + => Volume.FromOilBarrels(value.ToQuantityValue()); #endif - /// + /// public static Volume UkTablespoons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromUkTablespoons(double.CreateChecked(value)); + => Volume.FromUkTablespoons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromUkTablespoons(value.ToDouble(null)); + => Volume.FromUkTablespoons(value.ToQuantityValue()); #endif - /// + /// public static Volume UsBeerBarrels(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromUsBeerBarrels(double.CreateChecked(value)); + => Volume.FromUsBeerBarrels(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromUsBeerBarrels(value.ToDouble(null)); + => Volume.FromUsBeerBarrels(value.ToQuantityValue()); #endif - /// + /// public static Volume UsCustomaryCups(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromUsCustomaryCups(double.CreateChecked(value)); + => Volume.FromUsCustomaryCups(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromUsCustomaryCups(value.ToDouble(null)); + => Volume.FromUsCustomaryCups(value.ToQuantityValue()); #endif - /// + /// public static Volume UsGallons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromUsGallons(double.CreateChecked(value)); + => Volume.FromUsGallons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromUsGallons(value.ToDouble(null)); + => Volume.FromUsGallons(value.ToQuantityValue()); #endif - /// + /// public static Volume UsLegalCups(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromUsLegalCups(double.CreateChecked(value)); + => Volume.FromUsLegalCups(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromUsLegalCups(value.ToDouble(null)); + => Volume.FromUsLegalCups(value.ToQuantityValue()); #endif - /// + /// public static Volume UsOunces(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromUsOunces(double.CreateChecked(value)); + => Volume.FromUsOunces(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromUsOunces(value.ToDouble(null)); + => Volume.FromUsOunces(value.ToQuantityValue()); #endif - /// + /// public static Volume UsPints(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromUsPints(double.CreateChecked(value)); + => Volume.FromUsPints(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromUsPints(value.ToDouble(null)); + => Volume.FromUsPints(value.ToQuantityValue()); #endif - /// + /// public static Volume UsQuarts(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromUsQuarts(double.CreateChecked(value)); + => Volume.FromUsQuarts(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromUsQuarts(value.ToDouble(null)); + => Volume.FromUsQuarts(value.ToQuantityValue()); #endif - /// + /// public static Volume UsTablespoons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromUsTablespoons(double.CreateChecked(value)); + => Volume.FromUsTablespoons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromUsTablespoons(value.ToDouble(null)); + => Volume.FromUsTablespoons(value.ToQuantityValue()); #endif - /// + /// public static Volume UsTeaspoons(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => Volume.FromUsTeaspoons(double.CreateChecked(value)); + => Volume.FromUsTeaspoons(QuantityValue.CreateChecked(value)); #else , IConvertible - => Volume.FromUsTeaspoons(value.ToDouble(null)); + => Volume.FromUsTeaspoons(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumeFlowExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumeFlowExtensions.g.cs index 6a85e5560b..b520d1dfda 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumeFlowExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumeFlowExtensions.g.cs @@ -32,829 +32,829 @@ namespace UnitsNet.NumberExtensions.NumberToVolumeFlow /// public static class NumberToVolumeFlowExtensions { - /// + /// public static VolumeFlow AcreFeetPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromAcreFeetPerDay(double.CreateChecked(value)); + => VolumeFlow.FromAcreFeetPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromAcreFeetPerDay(value.ToDouble(null)); + => VolumeFlow.FromAcreFeetPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow AcreFeetPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromAcreFeetPerHour(double.CreateChecked(value)); + => VolumeFlow.FromAcreFeetPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromAcreFeetPerHour(value.ToDouble(null)); + => VolumeFlow.FromAcreFeetPerHour(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow AcreFeetPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromAcreFeetPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromAcreFeetPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromAcreFeetPerMinute(value.ToDouble(null)); + => VolumeFlow.FromAcreFeetPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow AcreFeetPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromAcreFeetPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromAcreFeetPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromAcreFeetPerSecond(value.ToDouble(null)); + => VolumeFlow.FromAcreFeetPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CentilitersPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCentilitersPerDay(double.CreateChecked(value)); + => VolumeFlow.FromCentilitersPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCentilitersPerDay(value.ToDouble(null)); + => VolumeFlow.FromCentilitersPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CentilitersPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCentilitersPerHour(double.CreateChecked(value)); + => VolumeFlow.FromCentilitersPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCentilitersPerHour(value.ToDouble(null)); + => VolumeFlow.FromCentilitersPerHour(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CentilitersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCentilitersPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromCentilitersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCentilitersPerMinute(value.ToDouble(null)); + => VolumeFlow.FromCentilitersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CentilitersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCentilitersPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromCentilitersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCentilitersPerSecond(value.ToDouble(null)); + => VolumeFlow.FromCentilitersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CubicCentimetersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCubicCentimetersPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromCubicCentimetersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCubicCentimetersPerMinute(value.ToDouble(null)); + => VolumeFlow.FromCubicCentimetersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CubicDecimetersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCubicDecimetersPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromCubicDecimetersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCubicDecimetersPerMinute(value.ToDouble(null)); + => VolumeFlow.FromCubicDecimetersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CubicFeetPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCubicFeetPerHour(double.CreateChecked(value)); + => VolumeFlow.FromCubicFeetPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCubicFeetPerHour(value.ToDouble(null)); + => VolumeFlow.FromCubicFeetPerHour(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CubicFeetPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCubicFeetPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromCubicFeetPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCubicFeetPerMinute(value.ToDouble(null)); + => VolumeFlow.FromCubicFeetPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CubicFeetPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCubicFeetPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromCubicFeetPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCubicFeetPerSecond(value.ToDouble(null)); + => VolumeFlow.FromCubicFeetPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CubicMetersPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCubicMetersPerDay(double.CreateChecked(value)); + => VolumeFlow.FromCubicMetersPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCubicMetersPerDay(value.ToDouble(null)); + => VolumeFlow.FromCubicMetersPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CubicMetersPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCubicMetersPerHour(double.CreateChecked(value)); + => VolumeFlow.FromCubicMetersPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCubicMetersPerHour(value.ToDouble(null)); + => VolumeFlow.FromCubicMetersPerHour(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CubicMetersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCubicMetersPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromCubicMetersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCubicMetersPerMinute(value.ToDouble(null)); + => VolumeFlow.FromCubicMetersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CubicMetersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCubicMetersPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromCubicMetersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCubicMetersPerSecond(value.ToDouble(null)); + => VolumeFlow.FromCubicMetersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CubicMillimetersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCubicMillimetersPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromCubicMillimetersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCubicMillimetersPerSecond(value.ToDouble(null)); + => VolumeFlow.FromCubicMillimetersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CubicYardsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCubicYardsPerDay(double.CreateChecked(value)); + => VolumeFlow.FromCubicYardsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCubicYardsPerDay(value.ToDouble(null)); + => VolumeFlow.FromCubicYardsPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CubicYardsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCubicYardsPerHour(double.CreateChecked(value)); + => VolumeFlow.FromCubicYardsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCubicYardsPerHour(value.ToDouble(null)); + => VolumeFlow.FromCubicYardsPerHour(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CubicYardsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCubicYardsPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromCubicYardsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCubicYardsPerMinute(value.ToDouble(null)); + => VolumeFlow.FromCubicYardsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow CubicYardsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromCubicYardsPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromCubicYardsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromCubicYardsPerSecond(value.ToDouble(null)); + => VolumeFlow.FromCubicYardsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow DecalitersPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromDecalitersPerDay(double.CreateChecked(value)); + => VolumeFlow.FromDecalitersPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromDecalitersPerDay(value.ToDouble(null)); + => VolumeFlow.FromDecalitersPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow DecalitersPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromDecalitersPerHour(double.CreateChecked(value)); + => VolumeFlow.FromDecalitersPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromDecalitersPerHour(value.ToDouble(null)); + => VolumeFlow.FromDecalitersPerHour(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow DecalitersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromDecalitersPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromDecalitersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromDecalitersPerMinute(value.ToDouble(null)); + => VolumeFlow.FromDecalitersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow DecalitersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromDecalitersPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromDecalitersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromDecalitersPerSecond(value.ToDouble(null)); + => VolumeFlow.FromDecalitersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow DecilitersPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromDecilitersPerDay(double.CreateChecked(value)); + => VolumeFlow.FromDecilitersPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromDecilitersPerDay(value.ToDouble(null)); + => VolumeFlow.FromDecilitersPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow DecilitersPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromDecilitersPerHour(double.CreateChecked(value)); + => VolumeFlow.FromDecilitersPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromDecilitersPerHour(value.ToDouble(null)); + => VolumeFlow.FromDecilitersPerHour(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow DecilitersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromDecilitersPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromDecilitersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromDecilitersPerMinute(value.ToDouble(null)); + => VolumeFlow.FromDecilitersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow DecilitersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromDecilitersPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromDecilitersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromDecilitersPerSecond(value.ToDouble(null)); + => VolumeFlow.FromDecilitersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow HectolitersPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromHectolitersPerDay(double.CreateChecked(value)); + => VolumeFlow.FromHectolitersPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromHectolitersPerDay(value.ToDouble(null)); + => VolumeFlow.FromHectolitersPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow HectolitersPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromHectolitersPerHour(double.CreateChecked(value)); + => VolumeFlow.FromHectolitersPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromHectolitersPerHour(value.ToDouble(null)); + => VolumeFlow.FromHectolitersPerHour(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow HectolitersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromHectolitersPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromHectolitersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromHectolitersPerMinute(value.ToDouble(null)); + => VolumeFlow.FromHectolitersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow HectolitersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromHectolitersPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromHectolitersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromHectolitersPerSecond(value.ToDouble(null)); + => VolumeFlow.FromHectolitersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow KilolitersPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromKilolitersPerDay(double.CreateChecked(value)); + => VolumeFlow.FromKilolitersPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromKilolitersPerDay(value.ToDouble(null)); + => VolumeFlow.FromKilolitersPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow KilolitersPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromKilolitersPerHour(double.CreateChecked(value)); + => VolumeFlow.FromKilolitersPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromKilolitersPerHour(value.ToDouble(null)); + => VolumeFlow.FromKilolitersPerHour(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow KilolitersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromKilolitersPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromKilolitersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromKilolitersPerMinute(value.ToDouble(null)); + => VolumeFlow.FromKilolitersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow KilolitersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromKilolitersPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromKilolitersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromKilolitersPerSecond(value.ToDouble(null)); + => VolumeFlow.FromKilolitersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow KilousGallonsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromKilousGallonsPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromKilousGallonsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromKilousGallonsPerMinute(value.ToDouble(null)); + => VolumeFlow.FromKilousGallonsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow LitersPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromLitersPerDay(double.CreateChecked(value)); + => VolumeFlow.FromLitersPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromLitersPerDay(value.ToDouble(null)); + => VolumeFlow.FromLitersPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow LitersPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromLitersPerHour(double.CreateChecked(value)); + => VolumeFlow.FromLitersPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromLitersPerHour(value.ToDouble(null)); + => VolumeFlow.FromLitersPerHour(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow LitersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromLitersPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromLitersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromLitersPerMinute(value.ToDouble(null)); + => VolumeFlow.FromLitersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow LitersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromLitersPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromLitersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromLitersPerSecond(value.ToDouble(null)); + => VolumeFlow.FromLitersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow MegalitersPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromMegalitersPerDay(double.CreateChecked(value)); + => VolumeFlow.FromMegalitersPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromMegalitersPerDay(value.ToDouble(null)); + => VolumeFlow.FromMegalitersPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow MegalitersPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromMegalitersPerHour(double.CreateChecked(value)); + => VolumeFlow.FromMegalitersPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromMegalitersPerHour(value.ToDouble(null)); + => VolumeFlow.FromMegalitersPerHour(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow MegalitersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromMegalitersPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromMegalitersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromMegalitersPerMinute(value.ToDouble(null)); + => VolumeFlow.FromMegalitersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow MegalitersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromMegalitersPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromMegalitersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromMegalitersPerSecond(value.ToDouble(null)); + => VolumeFlow.FromMegalitersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow MegaukGallonsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromMegaukGallonsPerDay(double.CreateChecked(value)); + => VolumeFlow.FromMegaukGallonsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromMegaukGallonsPerDay(value.ToDouble(null)); + => VolumeFlow.FromMegaukGallonsPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow MegaukGallonsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromMegaukGallonsPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromMegaukGallonsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromMegaukGallonsPerSecond(value.ToDouble(null)); + => VolumeFlow.FromMegaukGallonsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow MegausGallonsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromMegausGallonsPerDay(double.CreateChecked(value)); + => VolumeFlow.FromMegausGallonsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromMegausGallonsPerDay(value.ToDouble(null)); + => VolumeFlow.FromMegausGallonsPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow MicrolitersPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromMicrolitersPerDay(double.CreateChecked(value)); + => VolumeFlow.FromMicrolitersPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromMicrolitersPerDay(value.ToDouble(null)); + => VolumeFlow.FromMicrolitersPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow MicrolitersPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromMicrolitersPerHour(double.CreateChecked(value)); + => VolumeFlow.FromMicrolitersPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromMicrolitersPerHour(value.ToDouble(null)); + => VolumeFlow.FromMicrolitersPerHour(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow MicrolitersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromMicrolitersPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromMicrolitersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromMicrolitersPerMinute(value.ToDouble(null)); + => VolumeFlow.FromMicrolitersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow MicrolitersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromMicrolitersPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromMicrolitersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromMicrolitersPerSecond(value.ToDouble(null)); + => VolumeFlow.FromMicrolitersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow MillilitersPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromMillilitersPerDay(double.CreateChecked(value)); + => VolumeFlow.FromMillilitersPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromMillilitersPerDay(value.ToDouble(null)); + => VolumeFlow.FromMillilitersPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow MillilitersPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromMillilitersPerHour(double.CreateChecked(value)); + => VolumeFlow.FromMillilitersPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromMillilitersPerHour(value.ToDouble(null)); + => VolumeFlow.FromMillilitersPerHour(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow MillilitersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromMillilitersPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromMillilitersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromMillilitersPerMinute(value.ToDouble(null)); + => VolumeFlow.FromMillilitersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow MillilitersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromMillilitersPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromMillilitersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromMillilitersPerSecond(value.ToDouble(null)); + => VolumeFlow.FromMillilitersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow MillionUsGallonsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromMillionUsGallonsPerDay(double.CreateChecked(value)); + => VolumeFlow.FromMillionUsGallonsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromMillionUsGallonsPerDay(value.ToDouble(null)); + => VolumeFlow.FromMillionUsGallonsPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow NanolitersPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromNanolitersPerDay(double.CreateChecked(value)); + => VolumeFlow.FromNanolitersPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromNanolitersPerDay(value.ToDouble(null)); + => VolumeFlow.FromNanolitersPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow NanolitersPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromNanolitersPerHour(double.CreateChecked(value)); + => VolumeFlow.FromNanolitersPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromNanolitersPerHour(value.ToDouble(null)); + => VolumeFlow.FromNanolitersPerHour(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow NanolitersPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromNanolitersPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromNanolitersPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromNanolitersPerMinute(value.ToDouble(null)); + => VolumeFlow.FromNanolitersPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow NanolitersPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromNanolitersPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromNanolitersPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromNanolitersPerSecond(value.ToDouble(null)); + => VolumeFlow.FromNanolitersPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow OilBarrelsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromOilBarrelsPerDay(double.CreateChecked(value)); + => VolumeFlow.FromOilBarrelsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromOilBarrelsPerDay(value.ToDouble(null)); + => VolumeFlow.FromOilBarrelsPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow OilBarrelsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromOilBarrelsPerHour(double.CreateChecked(value)); + => VolumeFlow.FromOilBarrelsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromOilBarrelsPerHour(value.ToDouble(null)); + => VolumeFlow.FromOilBarrelsPerHour(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow OilBarrelsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromOilBarrelsPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromOilBarrelsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromOilBarrelsPerMinute(value.ToDouble(null)); + => VolumeFlow.FromOilBarrelsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow OilBarrelsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromOilBarrelsPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromOilBarrelsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromOilBarrelsPerSecond(value.ToDouble(null)); + => VolumeFlow.FromOilBarrelsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow UkGallonsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromUkGallonsPerDay(double.CreateChecked(value)); + => VolumeFlow.FromUkGallonsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromUkGallonsPerDay(value.ToDouble(null)); + => VolumeFlow.FromUkGallonsPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow UkGallonsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromUkGallonsPerHour(double.CreateChecked(value)); + => VolumeFlow.FromUkGallonsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromUkGallonsPerHour(value.ToDouble(null)); + => VolumeFlow.FromUkGallonsPerHour(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow UkGallonsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromUkGallonsPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromUkGallonsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromUkGallonsPerMinute(value.ToDouble(null)); + => VolumeFlow.FromUkGallonsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow UkGallonsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromUkGallonsPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromUkGallonsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromUkGallonsPerSecond(value.ToDouble(null)); + => VolumeFlow.FromUkGallonsPerSecond(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow UsGallonsPerDay(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromUsGallonsPerDay(double.CreateChecked(value)); + => VolumeFlow.FromUsGallonsPerDay(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromUsGallonsPerDay(value.ToDouble(null)); + => VolumeFlow.FromUsGallonsPerDay(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow UsGallonsPerHour(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromUsGallonsPerHour(double.CreateChecked(value)); + => VolumeFlow.FromUsGallonsPerHour(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromUsGallonsPerHour(value.ToDouble(null)); + => VolumeFlow.FromUsGallonsPerHour(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow UsGallonsPerMinute(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromUsGallonsPerMinute(double.CreateChecked(value)); + => VolumeFlow.FromUsGallonsPerMinute(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromUsGallonsPerMinute(value.ToDouble(null)); + => VolumeFlow.FromUsGallonsPerMinute(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlow UsGallonsPerSecond(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlow.FromUsGallonsPerSecond(double.CreateChecked(value)); + => VolumeFlow.FromUsGallonsPerSecond(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlow.FromUsGallonsPerSecond(value.ToDouble(null)); + => VolumeFlow.FromUsGallonsPerSecond(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumeFlowPerAreaExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumeFlowPerAreaExtensions.g.cs index f77cb69c07..903849d52d 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumeFlowPerAreaExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumeFlowPerAreaExtensions.g.cs @@ -32,26 +32,26 @@ namespace UnitsNet.NumberExtensions.NumberToVolumeFlowPerArea /// public static class NumberToVolumeFlowPerAreaExtensions { - /// + /// public static VolumeFlowPerArea CubicFeetPerMinutePerSquareFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlowPerArea.FromCubicFeetPerMinutePerSquareFoot(double.CreateChecked(value)); + => VolumeFlowPerArea.FromCubicFeetPerMinutePerSquareFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlowPerArea.FromCubicFeetPerMinutePerSquareFoot(value.ToDouble(null)); + => VolumeFlowPerArea.FromCubicFeetPerMinutePerSquareFoot(value.ToQuantityValue()); #endif - /// + /// public static VolumeFlowPerArea CubicMetersPerSecondPerSquareMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(double.CreateChecked(value)); + => VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(value.ToDouble(null)); + => VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumePerLengthExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumePerLengthExtensions.g.cs index a2e143dcc6..a816a68fe1 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumePerLengthExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumePerLengthExtensions.g.cs @@ -32,103 +32,103 @@ namespace UnitsNet.NumberExtensions.NumberToVolumePerLength /// public static class NumberToVolumePerLengthExtensions { - /// + /// public static VolumePerLength CubicMetersPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumePerLength.FromCubicMetersPerMeter(double.CreateChecked(value)); + => VolumePerLength.FromCubicMetersPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumePerLength.FromCubicMetersPerMeter(value.ToDouble(null)); + => VolumePerLength.FromCubicMetersPerMeter(value.ToQuantityValue()); #endif - /// + /// public static VolumePerLength CubicYardsPerFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumePerLength.FromCubicYardsPerFoot(double.CreateChecked(value)); + => VolumePerLength.FromCubicYardsPerFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumePerLength.FromCubicYardsPerFoot(value.ToDouble(null)); + => VolumePerLength.FromCubicYardsPerFoot(value.ToQuantityValue()); #endif - /// + /// public static VolumePerLength CubicYardsPerUsSurveyFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumePerLength.FromCubicYardsPerUsSurveyFoot(double.CreateChecked(value)); + => VolumePerLength.FromCubicYardsPerUsSurveyFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumePerLength.FromCubicYardsPerUsSurveyFoot(value.ToDouble(null)); + => VolumePerLength.FromCubicYardsPerUsSurveyFoot(value.ToQuantityValue()); #endif - /// + /// public static VolumePerLength ImperialGallonsPerMile(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumePerLength.FromImperialGallonsPerMile(double.CreateChecked(value)); + => VolumePerLength.FromImperialGallonsPerMile(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumePerLength.FromImperialGallonsPerMile(value.ToDouble(null)); + => VolumePerLength.FromImperialGallonsPerMile(value.ToQuantityValue()); #endif - /// + /// public static VolumePerLength LitersPerKilometer(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumePerLength.FromLitersPerKilometer(double.CreateChecked(value)); + => VolumePerLength.FromLitersPerKilometer(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumePerLength.FromLitersPerKilometer(value.ToDouble(null)); + => VolumePerLength.FromLitersPerKilometer(value.ToQuantityValue()); #endif - /// + /// public static VolumePerLength LitersPerMeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumePerLength.FromLitersPerMeter(double.CreateChecked(value)); + => VolumePerLength.FromLitersPerMeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumePerLength.FromLitersPerMeter(value.ToDouble(null)); + => VolumePerLength.FromLitersPerMeter(value.ToQuantityValue()); #endif - /// + /// public static VolumePerLength LitersPerMillimeter(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumePerLength.FromLitersPerMillimeter(double.CreateChecked(value)); + => VolumePerLength.FromLitersPerMillimeter(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumePerLength.FromLitersPerMillimeter(value.ToDouble(null)); + => VolumePerLength.FromLitersPerMillimeter(value.ToQuantityValue()); #endif - /// + /// public static VolumePerLength OilBarrelsPerFoot(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumePerLength.FromOilBarrelsPerFoot(double.CreateChecked(value)); + => VolumePerLength.FromOilBarrelsPerFoot(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumePerLength.FromOilBarrelsPerFoot(value.ToDouble(null)); + => VolumePerLength.FromOilBarrelsPerFoot(value.ToQuantityValue()); #endif - /// + /// public static VolumePerLength UsGallonsPerMile(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumePerLength.FromUsGallonsPerMile(double.CreateChecked(value)); + => VolumePerLength.FromUsGallonsPerMile(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumePerLength.FromUsGallonsPerMile(value.ToDouble(null)); + => VolumePerLength.FromUsGallonsPerMile(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumetricHeatCapacityExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumetricHeatCapacityExtensions.g.cs index 3f0be5fd73..eb2b89d601 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumetricHeatCapacityExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToVolumetricHeatCapacityExtensions.g.cs @@ -32,103 +32,103 @@ namespace UnitsNet.NumberExtensions.NumberToVolumetricHeatCapacity /// public static class NumberToVolumetricHeatCapacityExtensions { - /// + /// public static VolumetricHeatCapacity BtusPerCubicFootDegreeFahrenheit(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumetricHeatCapacity.FromBtusPerCubicFootDegreeFahrenheit(double.CreateChecked(value)); + => VolumetricHeatCapacity.FromBtusPerCubicFootDegreeFahrenheit(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumetricHeatCapacity.FromBtusPerCubicFootDegreeFahrenheit(value.ToDouble(null)); + => VolumetricHeatCapacity.FromBtusPerCubicFootDegreeFahrenheit(value.ToQuantityValue()); #endif - /// + /// public static VolumetricHeatCapacity CaloriesPerCubicCentimeterDegreeCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumetricHeatCapacity.FromCaloriesPerCubicCentimeterDegreeCelsius(double.CreateChecked(value)); + => VolumetricHeatCapacity.FromCaloriesPerCubicCentimeterDegreeCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumetricHeatCapacity.FromCaloriesPerCubicCentimeterDegreeCelsius(value.ToDouble(null)); + => VolumetricHeatCapacity.FromCaloriesPerCubicCentimeterDegreeCelsius(value.ToQuantityValue()); #endif - /// + /// public static VolumetricHeatCapacity JoulesPerCubicMeterDegreeCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumetricHeatCapacity.FromJoulesPerCubicMeterDegreeCelsius(double.CreateChecked(value)); + => VolumetricHeatCapacity.FromJoulesPerCubicMeterDegreeCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumetricHeatCapacity.FromJoulesPerCubicMeterDegreeCelsius(value.ToDouble(null)); + => VolumetricHeatCapacity.FromJoulesPerCubicMeterDegreeCelsius(value.ToQuantityValue()); #endif - /// + /// public static VolumetricHeatCapacity JoulesPerCubicMeterKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(double.CreateChecked(value)); + => VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(value.ToDouble(null)); + => VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(value.ToQuantityValue()); #endif - /// + /// public static VolumetricHeatCapacity KilocaloriesPerCubicCentimeterDegreeCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumetricHeatCapacity.FromKilocaloriesPerCubicCentimeterDegreeCelsius(double.CreateChecked(value)); + => VolumetricHeatCapacity.FromKilocaloriesPerCubicCentimeterDegreeCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumetricHeatCapacity.FromKilocaloriesPerCubicCentimeterDegreeCelsius(value.ToDouble(null)); + => VolumetricHeatCapacity.FromKilocaloriesPerCubicCentimeterDegreeCelsius(value.ToQuantityValue()); #endif - /// + /// public static VolumetricHeatCapacity KilojoulesPerCubicMeterDegreeCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumetricHeatCapacity.FromKilojoulesPerCubicMeterDegreeCelsius(double.CreateChecked(value)); + => VolumetricHeatCapacity.FromKilojoulesPerCubicMeterDegreeCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumetricHeatCapacity.FromKilojoulesPerCubicMeterDegreeCelsius(value.ToDouble(null)); + => VolumetricHeatCapacity.FromKilojoulesPerCubicMeterDegreeCelsius(value.ToQuantityValue()); #endif - /// + /// public static VolumetricHeatCapacity KilojoulesPerCubicMeterKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumetricHeatCapacity.FromKilojoulesPerCubicMeterKelvin(double.CreateChecked(value)); + => VolumetricHeatCapacity.FromKilojoulesPerCubicMeterKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumetricHeatCapacity.FromKilojoulesPerCubicMeterKelvin(value.ToDouble(null)); + => VolumetricHeatCapacity.FromKilojoulesPerCubicMeterKelvin(value.ToQuantityValue()); #endif - /// + /// public static VolumetricHeatCapacity MegajoulesPerCubicMeterDegreeCelsius(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumetricHeatCapacity.FromMegajoulesPerCubicMeterDegreeCelsius(double.CreateChecked(value)); + => VolumetricHeatCapacity.FromMegajoulesPerCubicMeterDegreeCelsius(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumetricHeatCapacity.FromMegajoulesPerCubicMeterDegreeCelsius(value.ToDouble(null)); + => VolumetricHeatCapacity.FromMegajoulesPerCubicMeterDegreeCelsius(value.ToQuantityValue()); #endif - /// + /// public static VolumetricHeatCapacity MegajoulesPerCubicMeterKelvin(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => VolumetricHeatCapacity.FromMegajoulesPerCubicMeterKelvin(double.CreateChecked(value)); + => VolumetricHeatCapacity.FromMegajoulesPerCubicMeterKelvin(QuantityValue.CreateChecked(value)); #else , IConvertible - => VolumetricHeatCapacity.FromMegajoulesPerCubicMeterKelvin(value.ToDouble(null)); + => VolumetricHeatCapacity.FromMegajoulesPerCubicMeterKelvin(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/GeneratedCode/NumberToWarpingMomentOfInertiaExtensions.g.cs b/UnitsNet.NumberExtensions/GeneratedCode/NumberToWarpingMomentOfInertiaExtensions.g.cs index 460a3c2a8d..54f3e523cc 100644 --- a/UnitsNet.NumberExtensions/GeneratedCode/NumberToWarpingMomentOfInertiaExtensions.g.cs +++ b/UnitsNet.NumberExtensions/GeneratedCode/NumberToWarpingMomentOfInertiaExtensions.g.cs @@ -32,70 +32,70 @@ namespace UnitsNet.NumberExtensions.NumberToWarpingMomentOfInertia /// public static class NumberToWarpingMomentOfInertiaExtensions { - /// + /// public static WarpingMomentOfInertia CentimetersToTheSixth(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => WarpingMomentOfInertia.FromCentimetersToTheSixth(double.CreateChecked(value)); + => WarpingMomentOfInertia.FromCentimetersToTheSixth(QuantityValue.CreateChecked(value)); #else , IConvertible - => WarpingMomentOfInertia.FromCentimetersToTheSixth(value.ToDouble(null)); + => WarpingMomentOfInertia.FromCentimetersToTheSixth(value.ToQuantityValue()); #endif - /// + /// public static WarpingMomentOfInertia DecimetersToTheSixth(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => WarpingMomentOfInertia.FromDecimetersToTheSixth(double.CreateChecked(value)); + => WarpingMomentOfInertia.FromDecimetersToTheSixth(QuantityValue.CreateChecked(value)); #else , IConvertible - => WarpingMomentOfInertia.FromDecimetersToTheSixth(value.ToDouble(null)); + => WarpingMomentOfInertia.FromDecimetersToTheSixth(value.ToQuantityValue()); #endif - /// + /// public static WarpingMomentOfInertia FeetToTheSixth(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => WarpingMomentOfInertia.FromFeetToTheSixth(double.CreateChecked(value)); + => WarpingMomentOfInertia.FromFeetToTheSixth(QuantityValue.CreateChecked(value)); #else , IConvertible - => WarpingMomentOfInertia.FromFeetToTheSixth(value.ToDouble(null)); + => WarpingMomentOfInertia.FromFeetToTheSixth(value.ToQuantityValue()); #endif - /// + /// public static WarpingMomentOfInertia InchesToTheSixth(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => WarpingMomentOfInertia.FromInchesToTheSixth(double.CreateChecked(value)); + => WarpingMomentOfInertia.FromInchesToTheSixth(QuantityValue.CreateChecked(value)); #else , IConvertible - => WarpingMomentOfInertia.FromInchesToTheSixth(value.ToDouble(null)); + => WarpingMomentOfInertia.FromInchesToTheSixth(value.ToQuantityValue()); #endif - /// + /// public static WarpingMomentOfInertia MetersToTheSixth(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => WarpingMomentOfInertia.FromMetersToTheSixth(double.CreateChecked(value)); + => WarpingMomentOfInertia.FromMetersToTheSixth(QuantityValue.CreateChecked(value)); #else , IConvertible - => WarpingMomentOfInertia.FromMetersToTheSixth(value.ToDouble(null)); + => WarpingMomentOfInertia.FromMetersToTheSixth(value.ToQuantityValue()); #endif - /// + /// public static WarpingMomentOfInertia MillimetersToTheSixth(this T value) where T : notnull #if NET7_0_OR_GREATER , INumber - => WarpingMomentOfInertia.FromMillimetersToTheSixth(double.CreateChecked(value)); + => WarpingMomentOfInertia.FromMillimetersToTheSixth(QuantityValue.CreateChecked(value)); #else , IConvertible - => WarpingMomentOfInertia.FromMillimetersToTheSixth(value.ToDouble(null)); + => WarpingMomentOfInertia.FromMillimetersToTheSixth(value.ToQuantityValue()); #endif } diff --git a/UnitsNet.NumberExtensions/UnitsNet.NumberExtensions.csproj b/UnitsNet.NumberExtensions/UnitsNet.NumberExtensions.csproj index 161d60e045..9a6761f612 100644 --- a/UnitsNet.NumberExtensions/UnitsNet.NumberExtensions.csproj +++ b/UnitsNet.NumberExtensions/UnitsNet.NumberExtensions.csproj @@ -1,8 +1,8 @@ - + UnitsNet.NumberExtensions - 6.0.0-pre017 + 6.0.0-pre018 Andreas Gullberg Larsen, Lu Li, Jon Suda Units.NET NumberExtensions Adds extension methods to number types to more easily create quantities, such as 5.Meters() instead of Length.FromMeters(5). @@ -25,6 +25,7 @@ $(VersionNoSuffix) latest enable + enable UnitsNet netstandard2.0;net8.0;net9.0 true @@ -34,6 +35,10 @@ + + + + ../UnitsNet.snk @@ -51,4 +56,8 @@ + + + + diff --git a/UnitsNet.Serialization.JsonNet.Tests/AbbreviatedUnitsConverterTests.cs b/UnitsNet.Serialization.JsonNet.Tests/AbbreviatedUnitsConverterTests.cs index 78e1e0326b..404de05125 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/AbbreviatedUnitsConverterTests.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/AbbreviatedUnitsConverterTests.cs @@ -12,7 +12,9 @@ namespace UnitsNet.Serialization.JsonNet.Tests { public class AbbreviatedUnitsConverterTests : JsonNetSerializationTestsBase { - public AbbreviatedUnitsConverterTests() : base(new AbbreviatedUnitsConverter()) + public AbbreviatedUnitsConverterTests() + : base(new AbbreviatedUnitsConverter( + new QuantityValueFormatOptions(QuantityValueSerializationFormat.DoublePrecision, QuantityValueDeserializationFormat.RoundedDouble))) { } @@ -72,7 +74,7 @@ public void NonNullNullableValueNestedInObject_ExpectJsonUnaffected() NonNullableFrequency = Frequency.FromHertz(10) }; - string expectedJson = """{"NullableFrequency":{"Value":10.0,"Unit":"Hz","Type":"Frequency"},"NonNullableFrequency":{"Value":10.0,"Unit":"Hz","Type":"Frequency"}}"""; + string expectedJson = """{"NullableFrequency":{"Value":10,"Unit":"Hz","Type":"Frequency"},"NonNullableFrequency":{"Value":10,"Unit":"Hz","Type":"Frequency"}}"""; string json = SerializeObject(testObj); @@ -87,7 +89,7 @@ public void NullQuantityNestedInObject_SerializesAsNull() NonNullableFrequency = Frequency.FromHertz(10) }; - string expectedJson = """{"NullableFrequency":null,"NonNullableFrequency":{"Value":10.0,"Unit":"Hz","Type":"Frequency"}}"""; + string expectedJson = """{"NullableFrequency":null,"NonNullableFrequency":{"Value":10,"Unit":"Hz","Type":"Frequency"}}"""; string json = SerializeObject(testObj); @@ -123,6 +125,24 @@ public void Serializing_UnknownQuantity_ThrowsUnitNotFoundException() Assert.Throws(() => SerializeObject(HowMuch.From(1, HowMuchUnit.Some))); } + [Fact] + public void Serializing_CustomQuantity_ReturnsTheExpectedResult() + { + // Arrange + var unitAbbreviationsCache = new UnitAbbreviationsCache([HowMuch.Info]); + unitAbbreviationsCache.MapUnitToDefaultAbbreviation(HowMuchUnit.Some, "s"); + var settings = new JsonSerializerSettings { Converters = [new AbbreviatedUnitsConverter(new UnitParser(unitAbbreviationsCache))] }; + + var quantity = HowMuch.From(1.2, HowMuchUnit.Some); + const string expectedJson = """{"Value":1.2,"Unit":"s","Type":"HowMuch"}"""; + + // Act + var result = JsonConvert.SerializeObject(quantity, settings); + + // Assert + Assert.Equal(expectedJson, result); + } + #endregion #region Deserialization tests @@ -138,6 +158,18 @@ public void DoubleIQuantity_DeserializedFromDoubleValueAndAbbreviatedUnit() Assert.Equal(MassUnit.Milligram, quantity.Unit); } + [Fact] + public void DoubleQuantity_DeserializedFromVeryPreciseValueAndAbbreviatedUnit() + { + var json = """{"Value":12345678901234567890.1234567890123456789,"Unit":"mg","Type":"Mass"}"""; + var expectedValue = QuantityValue.FromDoubleRounded(1.234567890123456E+19); + + var quantity = DeserializeObject(json); + + Assert.Equal(expectedValue, quantity.Value); + Assert.Equal(MassUnit.Milligram, quantity.Unit); + } + [Fact] public void DoubleQuantity_DeserializedFromDoubleValueAndAbbreviatedUnit() { @@ -160,14 +192,6 @@ public void DoubleIQuantity_DeserializedFromDoubleValueAndNonAmbiguousAbbreviate Assert.Equal(MassUnit.EarthMass, quantity.Unit); } - [Fact] - public void ThrowsAmbiguousUnitParseException_WhenDeserializingAmbiguousAbbreviation_WithoutQuantityType() - { - var json = """{"Value":1.2,"Unit":"mg"}"""; - - Assert.Throws(() => DeserializeObject(json)); - } - [Fact] public void DoubleIQuantity_DeserializedFromDoubleValueAndAbbreviatedUnit_CaseInsensitive() { @@ -204,6 +228,23 @@ public void Converter_IgnoresUnknownProperties() Assert.Equal(MassUnit.Milligram, quantity.Unit); } + [Fact] + public void Converter_WithAdditionalProperties_AndMissingMemberHandlingAsError_ThrowsJsonException() + { + var json = """{"Value":1.2,"Something":"Else","Unit":"mg","Type":"Mass"}"""; + var options = new JsonSerializerSettings { Converters = [new AbbreviatedUnitsConverter()], MissingMemberHandling = MissingMemberHandling.Error}; + + Assert.Throws(() => JsonConvert.DeserializeObject(json, options)); + } + + [Fact] + public void Deserializing_FromUnknownQuantityType_ThrowsQuantityNotFoundException() + { + var json = """{"Value":1.2,"Unit":"mg","Type":"invalid"}"""; + + Assert.Throws(() => DeserializeObject(json)); + } + [Fact] public void Deserializing_FromUnknownUnitForTargetQuantity_ThrowsUnitsNotFoundException() { @@ -334,6 +375,38 @@ public void DoubleZeroBaseQuantity_DeserializedFromEmptyInput() Assert.Equal(Mass.BaseUnit, quantity.Unit); } + [Fact] + public void Deserializing_CustomQuantity_ReturnsTheExpectedResult() + { + // Arrange + var unitAbbreviationsCache = new UnitAbbreviationsCache([HowMuch.Info]); + unitAbbreviationsCache.MapUnitToDefaultAbbreviation(HowMuchUnit.Some, "s"); + var settings = new JsonSerializerSettings { Converters = [new AbbreviatedUnitsConverter(new UnitParser(unitAbbreviationsCache))] }; + + const string json = """{"Value":1.2,"Unit":"s","Type":"HowMuch"}"""; + var expectedQuantity = HowMuch.From(1.2, HowMuchUnit.Some); + + // Act + HowMuch result = JsonConvert.DeserializeObject(json, settings); + + // Assert + Assert.Equal(expectedQuantity, result); + } + + [Fact] + public void Deserializing_NullValue_ThrowsJsonSerializationException() + { + const string json = """{"Value":null,"Unit":"mg","Type":"Mass"}"""; + Assert.Throws(() => DeserializeObject(json)); + } + + [Fact] + public void Deserializing_EmptyValue_ThrowsJsonSerializationException() + { + const string json = """{"Value":"","Unit":"mg","Type":"Mass"}"""; + Assert.Throws(() => DeserializeObject(json)); + } + #endregion } } diff --git a/UnitsNet.Serialization.JsonNet.Tests/AbbreviatedUnitsConverterWithCustomFormatOptionsTests.cs b/UnitsNet.Serialization.JsonNet.Tests/AbbreviatedUnitsConverterWithCustomFormatOptionsTests.cs new file mode 100644 index 0000000000..fc20f433b4 --- /dev/null +++ b/UnitsNet.Serialization.JsonNet.Tests/AbbreviatedUnitsConverterWithCustomFormatOptionsTests.cs @@ -0,0 +1,17 @@ +// 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.Serialization.JsonNet.Value; + +namespace UnitsNet.Serialization.JsonNet.Tests; + +public class AbbreviatedUnitsConverterWithCustomFormatOptionsTests : JsonNetSerializationTestsBase +{ + public AbbreviatedUnitsConverterWithCustomFormatOptionsTests() + : base( + new AbbreviatedUnitsConverter( + new QuantityValueFormatOptions(QuantityValueSerializationFormat.Custom, QuantityValueDeserializationFormat.Custom)), + new QuantityValueFractionalNotationConverter()) + { + } +} diff --git a/UnitsNet.Serialization.JsonNet.Tests/AbbreviatedUnitsConverterWithDecimalPrecisionFormatOptionsTests.cs b/UnitsNet.Serialization.JsonNet.Tests/AbbreviatedUnitsConverterWithDecimalPrecisionFormatOptionsTests.cs new file mode 100644 index 0000000000..22d03d26a9 --- /dev/null +++ b/UnitsNet.Serialization.JsonNet.Tests/AbbreviatedUnitsConverterWithDecimalPrecisionFormatOptionsTests.cs @@ -0,0 +1,69 @@ +// 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 System.Globalization; +using Newtonsoft.Json; +using UnitsNet.Units; +using Xunit; + +namespace UnitsNet.Serialization.JsonNet.Tests; + +public class AbbreviatedUnitsConverterWithDecimalPrecisionFormatOptionsTests : JsonNetSerializationTestsBase +{ + public AbbreviatedUnitsConverterWithDecimalPrecisionFormatOptionsTests() + : base(new AbbreviatedUnitsConverter(new QuantityValueFormatOptions + { + // all values should be serialized as G29 + SerializationFormat = QuantityValueSerializationFormat.DecimalPrecision, + // all values should be converted from their exact decimal representation (any number of digits) + DeserializationFormat = QuantityValueDeserializationFormat.ExactNumber + })) + { + } + + [Fact] + public void LargeQuantity_SerializedWithHighPrecisionAndAbbreviatedUnit() + { + // Arrange + var value = Mass.FromMilligrams(QuantityValue.Parse("12345678901234567890.1234567890123456789", CultureInfo.InvariantCulture)); + const string expectedJson = """{"Value":12345678901234567890.123456789,"Unit":"mg","Type":"Mass"}"""; + + // Act + var result = SerializeObject(value); + + //Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Quantity_DeserializedFromVeryPreciseValueAndAbbreviatedUnit() + { + // Arrange + const string json = """{"Value":12345678901234567890.1234567890123456789,"Unit":"mg","Type":"Mass"}"""; + var expectedValue = QuantityValue.Parse("12345678901234567890.1234567890123456789", CultureInfo.InvariantCulture); + + // Act + Mass quantity = DeserializeObject(json); + + //Assert + Assert.Equal(expectedValue, quantity.Value); + Assert.Equal(MassUnit.Milligram, quantity.Unit); + } + + [Fact] + public void Deserializing_WithNullValue_ThrowsJsonSerializationException() + { + const string json = """{"Value":null,"Unit":"mg","Type":"Mass"}"""; + + Assert.Throws(() => DeserializeObject(json)); + } + + [Fact] + public void Deserializing_WithEmptyValue_ThrowsJsonSerializationException() + { + const string json = """{"Value":"","Unit":"mg","Type":"Mass"}"""; + + Assert.Throws(() => DeserializeObject(json)); + } +} diff --git a/UnitsNet.Serialization.JsonNet.Tests/AbbreviatedUnitsConverterWithRoundTrippingFormatOptionsTests.cs b/UnitsNet.Serialization.JsonNet.Tests/AbbreviatedUnitsConverterWithRoundTrippingFormatOptionsTests.cs new file mode 100644 index 0000000000..05f04dec3f --- /dev/null +++ b/UnitsNet.Serialization.JsonNet.Tests/AbbreviatedUnitsConverterWithRoundTrippingFormatOptionsTests.cs @@ -0,0 +1,203 @@ +// 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 System.Globalization; +using System.Linq; +using System.Numerics; +using Newtonsoft.Json; +using UnitsNet.Units; +using Xunit; + +namespace UnitsNet.Serialization.JsonNet.Tests; + +public class AbbreviatedUnitsConverterWithRoundTrippingFormatOptionsTests : JsonNetSerializationTestsBase +{ + public AbbreviatedUnitsConverterWithRoundTrippingFormatOptionsTests() + : base(new AbbreviatedUnitsConverter( + new QuantityValueFormatOptions(QuantityValueSerializationFormat.RoundTripping, QuantityValueDeserializationFormat.RoundTripping))) + { + } + + [Fact] + public void Serializing_Quantity_WithDecimalNotationAndAbbreviatedUnit() + { + // Arrange + var value = Mass.FromMilligrams(4.25m); + const string expectedJson = """{"Value":4.25,"Unit":"mg","Type":"Mass"}"""; + + // Act + var result = SerializeObject(value); + + //Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Serializing_LargeQuantity_WithHighPrecisionAndAbbreviatedUnit() + { + // Arrange + var value = Mass.FromMilligrams(QuantityValue.Parse("12345678901234567890.1234567890123456789", CultureInfo.InvariantCulture)); + const string expectedJson = """{"Value":12345678901234567890.1234567890123456789,"Unit":"mg","Type":"Mass"}"""; + + // Act + var result = SerializeObject(value); + + //Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Serializing_Quantity_WithFractionalFormatAndAbbreviatedUnit() + { + // Arrange + var value = Mass.FromMilligrams(QuantityValue.FromTerms(1, 3)); + const string expectedJson = """{"Value":"1/3","Unit":"mg","Type":"Mass"}"""; + + // Act + var result = SerializeObject(value); + + //Assert + Assert.Equal(expectedJson, result); + } + + [Theory] + [InlineData(510)] + [InlineData(511)] + public void Serialize_VeryLargeDecimalNumber_ReturnsTheExpectedResult(int nbZeros) + { + // Arrange: 10000[...]4.2 (written as a decimal, with all its zeros) + var valueString = $"1{new string(Enumerable.Repeat('0', nbZeros).ToArray())}4.2"; + var value = Mass.FromMilligrams(QuantityValue.FromTerms(42 + BigInteger.Pow(10, nbZeros + 2), 10)); + var expectedJson = $$"""{"Value":{{valueString}},"Unit":"mg","Type":"Mass"}"""; + + // Act + var result = SerializeObject(value); + + // Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Serialize_VeryPreciseDecimalNumber_ReturnsTheExpectedResult() + { + // Arrange: 4.2e-255 (written as a decimal, with all its zeros) + var valueString = "0." + new string(Enumerable.Repeat('0', 512).ToArray()) + "42"; + var expectedJson = $$"""{"Value":{{valueString}},"Unit":"mg","Type":"Mass"}"""; + var value = Mass.FromMilligrams(QuantityValue.FromPowerOfTen(42, -514)); + + // Act + var result = SerializeObject(value); + + // Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Serialize_VeryLargeFractionalNumber_ReturnsTheExpectedResult() + { + // Arrange: (1/3)e256 (written as a fraction, with all its zeros) + var numeratorString = new string(Enumerable.Repeat('0', 255).Prepend('1').ToArray()); + var expectedJson = $$"""{"Value":"{{numeratorString}}/3","Unit":"mg","Type":"Mass"}"""; + var value = Mass.FromMilligrams(QuantityValue.FromPowerOfTen(1, 3, 255)); + + // Act + var result = SerializeObject(value); + + // Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Serializing_NaN_WithSymbolAndAbbreviatedUnit() + { + // Arrange + var value = Mass.FromMilligrams(QuantityValue.NaN); + const string expectedJson = """{"Value":"NaN","Unit":"mg","Type":"Mass"}"""; + + // Act + var result = SerializeObject(value); + + //Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Serializing_PositiveInfinity_WithSymbolAndAbbreviatedUnit() + { + // Arrange + var value = Mass.FromMilligrams(QuantityValue.PositiveInfinity); + const string expectedJson = """{"Value":"Infinity","Unit":"mg","Type":"Mass"}"""; + + // Act + var result = SerializeObject(value); + + //Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Serializing_NegativeInfinity_WithSymbolAndAbbreviatedUnit() + { + // Arrange + var value = Mass.FromMilligrams(QuantityValue.NegativeInfinity); + const string expectedJson = """{"Value":"-Infinity","Unit":"mg","Type":"Mass"}"""; + + // Act + var result = SerializeObject(value); + + //Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Deserializing_Quantity_FromVeryPreciseValueAndAbbreviatedUnit() + { + // Arrange + const string json = """{"Value":12345678901234567890.1234567890123456789,"Unit":"mg","Type":"Mass"}"""; + var expectedValue = QuantityValue.Parse("12345678901234567890.1234567890123456789", CultureInfo.InvariantCulture); + + // Act + Mass quantity = DeserializeObject(json); + + //Assert + Assert.Equal(expectedValue, quantity.Value); + Assert.Equal(MassUnit.Milligram, quantity.Unit); + } + + [Fact] + public void Deserializing_Quantity_WithFractionalFormatAndAbbreviatedUnit() + { + // Arrange + const string json = """{"Value":"1/3","Unit":"mg","Type":"Mass"}"""; + var expectedValue = QuantityValue.FromTerms(1, 3); + + // Act + Mass quantity = DeserializeObject(json); + + //Assert + Assert.Equal(expectedValue, quantity.Value); + Assert.Equal(MassUnit.Milligram, quantity.Unit); + } + + [Fact] + public void Deserializing_NullValue_ThrowsJsonSerializationException() + { + const string json = """{"Value":null,"Unit":"mg","Type":"Mass"}"""; + Assert.Throws(() => DeserializeObject(json)); + } + + [Fact] + public void Deserializing_EmptyValue_ThrowsJsonSerializationException() + { + const string json = """{"Value":"","Unit":"mg","Type":"Mass"}"""; + Assert.Throws(() => DeserializeObject(json)); + } + + [Fact] + public void Deserializing_InvalidFractionFormat_ThrowsFormatException() + { + const string json = """{"Value":"1/3invalid","Unit":"mg","Type":"Mass"}"""; + Assert.Throws(() => DeserializeObject(json)); + } +} diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj b/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj index b50af19181..5aea6b40f1 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNet.Serialization.JsonNet.Tests.csproj @@ -1,7 +1,8 @@  - net8.0;net9.0 + net48;net8.0;net9.0 + latest UnitsNet.Serialization.JsonNet.Tests true CS0618 @@ -14,6 +15,7 @@ + diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetBaseJsonConverterTest.cs b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetBaseJsonConverterTest.cs index b07bf62272..7465b7040d 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetBaseJsonConverterTest.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetBaseJsonConverterTest.cs @@ -33,8 +33,7 @@ public void UnitsNetBaseJsonConverter_ConvertIQuantity_works_with_double_type() public void UnitsNetBaseJsonConverter_ConvertIQuantity_throws_ArgumentNullException_when_quantity_is_NULL() { var result = Assert.Throws(() => _sut.Test_ConvertDoubleIQuantity(null)); - - Assert.Equal("Value cannot be null. (Parameter 'quantity')", result.Message); + Assert.Equal("quantity", result.ParamName); } [Fact] diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIComparableJsonConverterTest.cs b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIComparableJsonConverterTest.cs index ccbbc220e1..8e0ac3374a 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIComparableJsonConverterTest.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIComparableJsonConverterTest.cs @@ -50,8 +50,8 @@ public void UnitsNetIComparableJsonConverter_CanRead_returns_true() public void UnitsNetIComparableJsonConverter_ReadJson_throws_ArgumentNullException_when_arguments_are_null(JsonReader reader, JsonSerializer serializer, string paramName) { var exception = Assert.Throws(() => _sut.ReadJson(reader, typeof(IQuantity), null, false, serializer)); - - Assert.Equal($"Value cannot be null. (Parameter '{paramName}')", exception.Message); + + Assert.Equal(paramName, exception.ParamName); } [Fact] diff --git a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIQuantityJsonConverterTest.cs b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIQuantityJsonConverterTest.cs index 613f791cef..f024782d31 100644 --- a/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIQuantityJsonConverterTest.cs +++ b/UnitsNet.Serialization.JsonNet.Tests/UnitsNetIQuantityJsonConverterTest.cs @@ -37,8 +37,8 @@ public void UnitsNetIQuantityJsonConverter_WriteJson_throws_ArgumentNullException_when_arguments_are_null(JsonWriter writer, JsonSerializer serializer, string parameterName) { var exception = Assert.Throws(() => _sut.WriteJson(writer, Power.FromWatts(10D), serializer)); - - Assert.Equal($"Value cannot be null. (Parameter '{parameterName}')", exception.Message); + + Assert.Equal(parameterName, exception.ParamName); } [Fact] @@ -85,8 +85,8 @@ public void UnitsNetIQuantityJsonConverter_CanRead_returns_true() public void UnitsNetIQuantityJsonConverter_ReadJson_throws_ArgumentNullException_when_arguments_are_null(JsonReader reader, JsonSerializer serializer, string paramName) { var exception = Assert.Throws(() => _sut.ReadJson(reader, typeof(IQuantity), null, false, serializer)); - - Assert.Equal($"Value cannot be null. (Parameter '{paramName}')", exception.Message); + + Assert.Equal(paramName, exception.ParamName); } [Fact] diff --git a/UnitsNet.Serialization.JsonNet.Tests/Value/QuantityValueFractionalNotationConverterTests.cs b/UnitsNet.Serialization.JsonNet.Tests/Value/QuantityValueFractionalNotationConverterTests.cs new file mode 100644 index 0000000000..6e7a8283b6 --- /dev/null +++ b/UnitsNet.Serialization.JsonNet.Tests/Value/QuantityValueFractionalNotationConverterTests.cs @@ -0,0 +1,299 @@ +// 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 JetBrains.Annotations; +using Newtonsoft.Json; +using UnitsNet.Serialization.JsonNet.Value; +using Xunit; + +namespace UnitsNet.Serialization.JsonNet.Tests.Value; + +[TestSubject(typeof(QuantityValueFractionalNotationConverter))] +public class QuantityValueFractionalNotationConverterTests +{ + private static JsonSerializerSettings CreateDefaultOptions() + { + var options = new JsonSerializerSettings(); + options.Converters.Add(QuantityValueFractionalNotationConverter.Default); + return options; + } + + [Fact] + public void Serialize_ReturnsTheExpectedResult() + { + // Arrange + var json = """{"N":42,"D":10}"""; + QuantityValue value = 4.2m; + JsonSerializerSettings options = CreateDefaultOptions(); + + // Act + var result = JsonConvert.SerializeObject(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_WithReduction_ReturnsTheExpectedResult() + { + // Arrange + var json = """{"N":21,"D":5}"""; + QuantityValue value = 4.2m; + var options = new JsonSerializerSettings(); + options.Converters.Add(QuantityValueFractionalNotationConverter.Reducing); + + // Act + var result = JsonConvert.SerializeObject(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_Zero_WithDefaultSettings_ReturnsBothTerms() + { + // Arrange + var json = """{"N":0,"D":1}"""; + var value = QuantityValue.Zero; + JsonSerializerSettings options = CreateDefaultOptions(); + + // Act + var result = JsonConvert.SerializeObject(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_Zero_IgnoringDefaultValues_ReturnsAnEmptyObject() + { + // Arrange + var json = "{}"; + var value = QuantityValue.Zero; + JsonSerializerSettings options = CreateDefaultOptions(); + options.DefaultValueHandling = DefaultValueHandling.Ignore; + + // Act + var result = JsonConvert.SerializeObject(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_IntegerNumber_WithIgnoreCondition_WhenWritingDefault_ReturnsTheNumerator() + { + // Arrange + var json = """{"N":5}"""; + QuantityValue value = 5; + JsonSerializerSettings options = CreateDefaultOptions(); + options.DefaultValueHandling = DefaultValueHandling.Ignore; + + // Act + var result = JsonConvert.SerializeObject(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_DecimalNumber_WithIgnoreCondition_WhenWritingDefault_ReturnsBothTerms() + { + // Arrange + var json = """{"N":42,"D":10}"""; + QuantityValue value = 4.2m; + JsonSerializerSettings options = CreateDefaultOptions(); + options.DefaultValueHandling = DefaultValueHandling.Ignore; + + // Act + var result = JsonConvert.SerializeObject(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Deserialize_ValidJson_ReturnsTheExpectedValue() + { + // Arrange + var json = """{"N":42,"D":10}"""; + QuantityValue expected = 4.2m; + JsonSerializerSettings options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonConvert.DeserializeObject(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_ValidJson_WithCaseInsensitiveMatching_ReturnsTheExpectedValue() + { + // Arrange + var json = """{"N":42,"d":10}"""; + QuantityValue expected = 4.2m; + JsonSerializerSettings options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonConvert.DeserializeObject(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_ValidJson_WithAdditionalProperties_ReturnsTheExpectedValue() + { + // Arrange + var json = """{"N":42,"something":2,"D":10}"""; + QuantityValue expected = 4.2m; + JsonSerializerSettings options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonConvert.DeserializeObject(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_Json_WithAdditionalProperties_AndMissingMemberHandlingAsError_ThrowsJsonException() + { + // Arrange + var json = """{"N":42,"something":2,"D":10}"""; + JsonSerializerSettings options = CreateDefaultOptions(); + options.MissingMemberHandling = MissingMemberHandling.Error; + + // Assert + Assert.Throws(() => JsonConvert.DeserializeObject(json, options)); + } + + [Fact] + public void Deserialize_ValidJsonWithQuotedTerms_ReturnsTheExpectedValue() + { + // Arrange + var json = """{"N":"42","D":"10"}"""; + QuantityValue expected = 4.2m; + JsonSerializerSettings options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonConvert.DeserializeObject(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_WithoutDenominator_ReturnsTheExpectedIntegerValue() + { + // Arrange + var json = """{"N":42}"""; + QuantityValue expected = 42; + JsonSerializerSettings options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonConvert.DeserializeObject(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_WithoutNumeratorAndDenominator_ReturnsZero() + { + // Arrange + var json = "{}"; + QuantityValue expected = QuantityValue.Zero; + JsonSerializerSettings options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonConvert.DeserializeObject(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_WithoutNumeratorAndNonZeroDenominator_ReturnsZero() + { + // Arrange + var json = """{"D":1}"""; + QuantityValue expected = QuantityValue.Zero; + JsonSerializerSettings options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonConvert.DeserializeObject(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_WithoutNumeratorAndZeroDenominator_ReturnsNaN() + { + // Arrange + var json = """{"D":0}"""; + QuantityValue expected = QuantityValue.NaN; + JsonSerializerSettings options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonConvert.DeserializeObject(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_WithoutPositiveNumeratorAndZeroDenominator_ReturnsPositiveInfinity() + { + // Arrange + var json = """{"N":1,"D":0}"""; + QuantityValue expected = QuantityValue.PositiveInfinity; + JsonSerializerSettings options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonConvert.DeserializeObject(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_WithNegativeNumeratorAndZeroDenominator_ReturnsNegativeInfinity() + { + // Arrange + var json = """{"N":-1,"D":0}"""; + QuantityValue expected = QuantityValue.NegativeInfinity; + JsonSerializerSettings options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonConvert.DeserializeObject(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserializing_WithInvalidString_ThrowsFormatException() + { + // Arrange + var json = """{"N":"4invalid2","D":"10"}"""; + JsonSerializerSettings options = CreateDefaultOptions(); + + // Assert + Assert.Throws(() => JsonConvert.DeserializeObject(json, options)); + } + + [Theory] + [InlineData("43")] + public void Deserializing_WithInvalidJsonString_ThrowsJsonException(string invalidJson) + { + // Arrange + JsonSerializerSettings options = CreateDefaultOptions(); + + // Assert + Assert.Throws(() => JsonConvert.DeserializeObject(invalidJson, options)); + } +} diff --git a/UnitsNet.Serialization.JsonNet/AbbreviatedUnitsConverter.cs b/UnitsNet.Serialization.JsonNet/AbbreviatedUnitsConverter.cs index 10fc5b9b19..61a403d908 100644 --- a/UnitsNet.Serialization.JsonNet/AbbreviatedUnitsConverter.cs +++ b/UnitsNet.Serialization.JsonNet/AbbreviatedUnitsConverter.cs @@ -1,9 +1,6 @@ using System; using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Globalization; using Newtonsoft.Json; -using UnitsNet.Units; namespace UnitsNet.Serialization.JsonNet { @@ -14,7 +11,7 @@ namespace UnitsNet.Serialization.JsonNet /// /// /// { - /// "Value": 1.20, + /// "Value": 1.2, /// "Unit": "mg", /// "Type": "Mass" /// } @@ -27,42 +24,85 @@ public class AbbreviatedUnitsConverter : NullableQuantityConverter private const string UnitProperty = "Unit"; private const string TypeProperty = "Type"; - private readonly UnitAbbreviationsCache _abbreviations; + private readonly QuantityValueSerializationFormat _valueSerializationFormat; + private readonly QuantityValueDeserializationFormat _valueDeserializationFormat; private readonly IEqualityComparer _propertyComparer; - private readonly IReadOnlyDictionary _quantities; - private readonly UnitParser _unitParser; + private readonly UnitParser _unitParser; + /// - /// Construct a converter using the default list of quantities (case insensitive) and unit abbreviation provider + /// Initializes a new instance of the class using the default + /// case-insensitive comparer and the specified . /// - public AbbreviatedUnitsConverter() - : this(StringComparer.OrdinalIgnoreCase) + /// + /// The options for formatting quantity values during serialization and deserialization. + /// Defaults to a new instance of if not specified. + /// + public AbbreviatedUnitsConverter(QuantityValueFormatOptions valueFormatOptions = new()) + : this(StringComparer.OrdinalIgnoreCase, valueFormatOptions) { } /// - /// Construct a converter using the default list of quantities and unit abbreviation provider + /// Initializes a new instance of the class. /// - /// The comparer used to compare the property/quantity names (e.g. StringComparer.OrdinalIgnoreCase) - public AbbreviatedUnitsConverter(IEqualityComparer comparer) - : this(Quantity.ByName, UnitsNetSetup.Default.UnitAbbreviations, comparer) + /// + /// The equality comparer used to compare property or quantity names, such as + /// . + /// + /// + /// Options for formatting the quantity value during serialization and deserialization. + /// + /// + /// The is used exclusively for property name matching. + /// Quantity names are matched using the default comparer of , + /// which is currently . + /// + public AbbreviatedUnitsConverter(IEqualityComparer comparer, QuantityValueFormatOptions valueFormatOptions = new()) + : this(UnitParser.Default, comparer, valueFormatOptions) { } /// - /// Construct a converter using the provided map of {name : quantity} + /// Initializes a new instance of the class. /// - /// The dictionary of quantity names - /// The unit abbreviations used for the serialization - /// The comparer used to compare the property names (e.g. StringComparer.OrdinalIgnoreCase) - public AbbreviatedUnitsConverter(IReadOnlyDictionary quantities, UnitAbbreviationsCache abbreviations, IEqualityComparer propertyComparer) + /// + /// The used for deserializing an abbreviation back into its + /// corresponding unit. + /// + /// + /// The options specifying how values should be serialized and deserialized. + /// Defaults to a new instance of if not provided. + /// + public AbbreviatedUnitsConverter(UnitParser unitParser, QuantityValueFormatOptions valueFormatOptions = new()) + : this(unitParser, StringComparer.OrdinalIgnoreCase, valueFormatOptions) { - _quantities = quantities; - _abbreviations = abbreviations; - _propertyComparer = propertyComparer; - _unitParser = new UnitParser(abbreviations); } + /// + /// Initializes a new instance of the class. + /// + /// + /// The used for deserializing an abbreviation back into its + /// corresponding unit. + /// + /// + /// The comparer used to compare property names during serialization and deserialization. + /// For example, can be used for case-insensitive comparisons. + /// + /// + /// The options specifying how values should be serialized and deserialized. + /// Defaults to a new instance of if not provided. + /// + public AbbreviatedUnitsConverter(UnitParser unitParser, IEqualityComparer propertyComparer, + QuantityValueFormatOptions valueFormatOptions = new()) + { + _unitParser = unitParser ?? throw new ArgumentNullException(nameof(unitParser)); + _propertyComparer = propertyComparer?? throw new ArgumentNullException(nameof(propertyComparer)); + _valueSerializationFormat = valueFormatOptions.SerializationFormat; + _valueDeserializationFormat = valueFormatOptions.DeserializationFormat; + } + /// public override void WriteJson(JsonWriter writer, IQuantity? quantity, JsonSerializer serializer) { @@ -71,47 +111,123 @@ public override void WriteJson(JsonWriter writer, IQuantity? quantity, JsonSeria writer.WriteNull(); return; } + + writer.WriteStartObject(); - var unit = GetUnitAbbreviation(quantity.Unit); // by default this should be equal to quantity.ToString("a", CultureInfo.InvariantCulture); - var quantityType = GetQuantityType(quantity); // by default this should be equal to quantity.QuantityInfo.Name + WriteValueProperty(writer, quantity, serializer); + WriteUnitProperty(writer, quantity, serializer); + WriteTypeProperty(writer, quantity, serializer); - writer.WriteStartObject(); + writer.WriteEndObject(); + } - // write the 'Value' using the actual type + /// + /// Writes the 'Value' property of the specified quantity to the JSON output. + /// + /// The used to write the JSON data. + /// The instance whose 'Value' property is to be written. + /// The calling serializer. + /// + /// This method writes the numerical value of the quantity using the general ("G") format and invariant culture. + /// It can be overridden to customize the representation of the value, such as using a fractional format or a different numeric type. + /// + protected virtual void WriteValueProperty(JsonWriter writer, IQuantity quantity, JsonSerializer serializer) + { writer.WritePropertyName(ValueProperty); - writer.WriteValue((double)quantity.Value); + writer.WriteValue(quantity.Value, serializer, _valueSerializationFormat); + } - // write the 'Unit' abbreviation + /// + /// Writes the 'Unit' property to the JSON output. + /// + /// The used to write the JSON content. + /// The instance whose unit is being written. + /// The calling serializer. + /// + /// This method can be overridden to customize the format or type of the 'Unit' property in the JSON payload. + /// + protected virtual void WriteUnitProperty(JsonWriter writer, IQuantity quantity, JsonSerializer serializer) + { writer.WritePropertyName(UnitProperty); - writer.WriteValue(unit); + writer.WriteValue(_unitParser.Abbreviations.GetDefaultAbbreviation(quantity.UnitKey, serializer.Culture)); + } - // write the quantity 'Type' + /// + /// Writes the 'Type' property. + /// + /// The JsonWriter to write to. + /// + /// The calling serializer. + /// + /// This method can be overridden to customize the payload type or format. + /// + protected virtual void WriteTypeProperty(JsonWriter writer, IQuantity quantity, JsonSerializer serializer) + { writer.WritePropertyName(TypeProperty); - writer.WriteValue(quantityType); + writer.WriteValue(quantity.QuantityInfo.Name); + } - writer.WriteEndObject(); + /// + /// Reads the "Value" property from the JSON reader and converts it to a . + /// + /// The to read the value from. + /// The type of the object to deserialize. + /// The used for deserialization. + /// The parsed . + /// + /// Thrown if the value cannot be read or converted to a . + /// + protected virtual QuantityValue ReadValueProperty(JsonReader reader, Type objectType, JsonSerializer serializer) + { + return reader.ReadValue(serializer, _valueDeserializationFormat); } /// - /// Get the string representation associated with the given quantity + /// Reads the unit abbreviation property from the JSON reader. /// - /// The quantity that is being serialized - /// The string representation associated with the given quantity - protected string GetQuantityType(IQuantity quantity) + /// The instance to read from. + /// The type of the object to deserialize. + /// The used for deserialization. + /// + /// The unit abbreviation as a if present; otherwise, null. + /// + /// + /// Thrown if the JSON reader is not positioned at a valid string value for the unit abbreviation. + /// + protected virtual string? ReadUnitAbbreviationProperty(JsonReader reader, Type objectType, JsonSerializer serializer) { - return _quantities[quantity.QuantityInfo.Name].Name; + return reader.ReadAsString(); } + /// + /// Reads the quantity name property from the JSON reader. + /// + /// The instance used to read the JSON data. + /// The type of the object to deserialize. + /// The used for deserialization. + /// + /// The quantity name as a string, or null if the value is not present or cannot be read. + /// + /// + /// This method is used to extract the name of the quantity type from the JSON data. + /// The quantity name is typically used to identify the type of measurement (e.g., "Mass", "Length"). + /// + protected virtual string? ReadQuantityNameProperty(JsonReader reader, Type objectType, JsonSerializer serializer) + { + return reader.ReadAsString(); + } + /// public override IQuantity? ReadJson(JsonReader reader, Type objectType, IQuantity? existingValue, bool hasExistingValue, JsonSerializer serializer) { - QuantityInfo? quantityInfo; if (reader.TokenType == JsonToken.Null) { - return TryGetQuantity(objectType.Name, out quantityInfo) ? quantityInfo.Zero : default; + return objectType == typeof(IQuantity) || typeof(IQuantity).IsAssignableFrom(Nullable.GetUnderlyingType(objectType)) + ? null + : _unitParser.Quantities.GetQuantityInfo(objectType).Zero; } - string? valueToken = null; + QuantityValue value = QuantityValue.Zero; string? unitAbbreviation = null, quantityName = null; if (reader.TokenType == JsonToken.StartObject) { @@ -122,201 +238,53 @@ protected string GetQuantityType(IQuantity quantity) var propertyName = reader.Value as string; if (_propertyComparer.Equals(propertyName, ValueProperty)) { - valueToken = reader.ReadAsString(); + value = ReadValueProperty(reader, objectType, serializer); } else if (_propertyComparer.Equals(propertyName, UnitProperty)) { - unitAbbreviation = reader.ReadAsString(); + unitAbbreviation = ReadUnitAbbreviationProperty(reader, objectType, serializer); } else if (_propertyComparer.Equals(propertyName, TypeProperty)) { - quantityName = reader.ReadAsString(); + quantityName = ReadQuantityNameProperty(reader, objectType, serializer); } - else + else if (serializer.MissingMemberHandling == MissingMemberHandling.Ignore) { reader.Skip(); } + else + { + throw new JsonException($"'{propertyName}' was no found in the list of members of '{objectType}'."); + } } } } - - - Enum unit; - if (quantityName is null) + + UnitInfo unitInfo; + if (quantityName != null && unitAbbreviation != null) { - if (TryGetQuantity(objectType.Name, out quantityInfo)) - { - unit = GetUnitOrDefault(unitAbbreviation, quantityInfo); - } - else if (unitAbbreviation != null) // the objectType doesn't match any concrete quantity type (likely it is an IQuantity) - { - // failing back to an exhaustive search (it is possible that this converter was created with a short-list of non-ambiguous quantities - unit = FindUnit(unitAbbreviation, out quantityInfo); - } - else - { - throw new FormatException("No unit abbreviation found in JSON."); - } + unitInfo = _unitParser.GetUnitFromAbbreviation(quantityName, unitAbbreviation, serializer.Culture); } - else + else if (unitAbbreviation != null) { - quantityInfo = GetQuantityInfo(quantityName); - unit = GetUnitOrDefault(unitAbbreviation, quantityInfo); + unitInfo = objectType == typeof(IQuantity) + ? _unitParser.GetUnitFromAbbreviation(unitAbbreviation, serializer.Culture) + : _unitParser.GetUnitFromAbbreviation(Nullable.GetUnderlyingType(objectType) ?? objectType, unitAbbreviation, serializer.Culture); } - - double value; - if (valueToken is null) + else if (quantityName != null) { - value = default; + unitInfo = _unitParser.Quantities.GetQuantityByName(quantityName).BaseUnitInfo; } - else + else if (objectType != typeof(IQuantity)) { - value = double.Parse(valueToken, CultureInfo.InvariantCulture); + unitInfo = _unitParser.Quantities.GetQuantityInfo(Nullable.GetUnderlyingType(objectType) ?? objectType).BaseUnitInfo; } - - return Quantity.From(value, unit); - } - - /// - /// Attempt to find a unique (non-ambiguous) unit matching the provided abbreviation. - /// - /// An exhaustive search using all quantities is very likely to fail with an - /// , so make sure you're using the minimum set of supported quantities. - /// - /// - /// The unit abbreviation - /// The quantity type where the resulting unit was found - /// The unit associated with the given - /// - /// - protected virtual Enum FindUnit(string unitAbbreviation, out QuantityInfo quantityInfo) - { - if (unitAbbreviation is null) // we could assume string.Empty instead - { - throw new UnitNotFoundException("The unit abbreviation and quantity type cannot both be null"); - } - - Enum? unit = null; - QuantityInfo? tempQuantityInfo = default; - foreach (var targetQuantity in _quantities.Values) - { - if (!TryParse(unitAbbreviation, targetQuantity, out var unitMatched)) - { - continue; - } - - if (unit != null && - !(targetQuantity == tempQuantityInfo && Equals(unit, unitMatched))) // it is possible to have "synonyms": e.g. "Mass" and "Weight" - { - throw new AmbiguousUnitParseException($"Multiple quantities found matching the provided abbreviation: {unit}, {unitMatched}"); - } - - tempQuantityInfo = targetQuantity; - unit = unitMatched; - } - - if (unit is null || tempQuantityInfo is null) - { - throw new UnitNotFoundException($"No quantity found with abbreviation [{unitAbbreviation}]."); - } - - quantityInfo = tempQuantityInfo; - return unit; - } - - - /// - /// Get the unit abbreviation associated with the given unit - /// - /// Unit enum value, such as . - /// The default abbreviation as provided by the associated - protected string GetUnitAbbreviation(Enum unit) - { - return _abbreviations.GetDefaultAbbreviation(unit, CultureInfo.InvariantCulture); - } - - /// - /// If the unit abbreviation is unspecified: returns the default (BaseUnit) unit for the - /// , otherwise attempts to the - /// - /// - /// - /// Unit abbreviation, such as "kg" or "m" for and - /// respectively. - /// - /// The associated quantity info - /// Unit enum value, such as . - /// No units match the abbreviation. - /// More than one unit matches the abbreviation. - protected virtual Enum GetUnitOrDefault(string? unitAbbreviation, QuantityInfo quantityInfo) - { - return unitAbbreviation == null - ? quantityInfo.BaseUnitInfo.Value - : _unitParser.Parse(unitAbbreviation, quantityInfo.UnitType, CultureInfo.InvariantCulture); - } - - /// - /// Unit abbreviation, such as "kg" or "m" for and - /// respectively. - /// - /// The associated quantity info - /// Unit enum value, such as . - /// No units match the abbreviation. - /// More than one unit matches the abbreviation. - protected Enum Parse(string unitAbbreviation, QuantityInfo quantityInfo) - { - return _unitParser.Parse(unitAbbreviation, quantityInfo.UnitType, CultureInfo.InvariantCulture); - } - - /// - /// Unit abbreviation, such as "kg" or "m" for and - /// respectively. - /// - /// The associated quantity info - /// The unit enum value as out result. - /// True if successful. - /// No units match the abbreviation. - /// More than one unit matches the abbreviation. - protected bool TryParse(string? unitAbbreviation, QuantityInfo quantityInfo, [NotNullWhen(true)] out Enum? unit) - { - return _unitParser.TryParse(unitAbbreviation, quantityInfo.UnitType, CultureInfo.InvariantCulture, out unit); - } - - /// - /// Try to get the quantity info associated with a given quantity name - /// - /// The name of the quantity: i.e. - /// The quantity information associated with the given quantity name - /// - /// true - /// if a matching quantity is found or - /// false - /// otherwise - /// - protected bool TryGetQuantity(string quantityName, [NotNullWhen(true)] out QuantityInfo? quantityInfo) - { - return _quantities.TryGetValue(quantityName, out quantityInfo); - } - - /// - /// Get the quantity info associated with a given quantity name - /// - /// The name of the quantity: i.e. - /// - /// true - /// if a matching quantity is found or - /// false - /// otherwise - /// - /// Quantity not found exception is thrown if no match found - protected QuantityInfo GetQuantityInfo(string quantityName) - { - if (!TryGetQuantity(quantityName, out var quantityInfo)) + else { - throw new UnitsNetException($"Failed to find the quantity type: {quantityName}.") { Data = { ["type"] = quantityName } }; + throw new FormatException("The target unit cannot be determined from the provided JSON."); } - return quantityInfo; + return unitInfo.From(value); } } } diff --git a/UnitsNet.Serialization.JsonNet/QuantityValueExtensions.cs b/UnitsNet.Serialization.JsonNet/QuantityValueExtensions.cs new file mode 100644 index 0000000000..9a8cfa63bc --- /dev/null +++ b/UnitsNet.Serialization.JsonNet/QuantityValueExtensions.cs @@ -0,0 +1,282 @@ +// 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 System.Globalization; +using System.Numerics; +using Newtonsoft.Json; +#if NETSTANDARD2_0 +using System.Text; +#endif + +namespace UnitsNet.Serialization.JsonNet; + +internal static class QuantityValueExtensions +{ + public static void WriteValue(this JsonWriter writer, QuantityValue value, JsonSerializer serializer, QuantityValueSerializationFormat format) + { + switch (format) + { + case QuantityValueSerializationFormat.DoublePrecision: + writer.WriteValueWithDoublePrecision(value); + break; + case QuantityValueSerializationFormat.DecimalPrecision: + writer.WriteValueWithDecimalPrecision(value); + break; + case QuantityValueSerializationFormat.RoundTripping: + writer.WriteValueRoundTripping(value); + break; + case QuantityValueSerializationFormat.Custom: + default: + serializer.Serialize(writer, value); + break; + } + } + + // public static void WriteValueAsDouble(this JsonWriter writer, QuantityValue value) + // { + // writer.WriteValue(value.ToDouble()); + // } + + public static void WriteValueWithDoublePrecision(this JsonWriter writer, QuantityValue value) + { + writer.WriteRawValue(value.ToString(CultureInfo.InvariantCulture)); + } + + public static void WriteValueWithDecimalPrecision(this JsonWriter writer, QuantityValue value) + { + writer.WriteRawValue(value.ToString("G29", CultureInfo.InvariantCulture)); + } + + public static void WriteValueRoundTripping(this JsonWriter writer, QuantityValue value) + { + (BigInteger numerator, BigInteger denominator) = QuantityValue.Reduce(value); + // TODO see about using exponential notation + if (denominator <= long.MaxValue / 10) + { + if (numerator <= long.MaxValue && numerator >= long.MinValue) + { + WriteSmallTerms(writer, (long)numerator, (long)denominator); + return; + } + + if (denominator.IsOne) + { + writer.WriteValue(numerator); + return; + } + } + + if (!QuantityValue.HasNonDecimalFactors(denominator)) + { + // failed to format the value as a decimal number + writer.WriteValue($"{numerator}/{denominator}"); + return; + } + + // decimal number + var quotient = BigInteger.DivRem(numerator, denominator, out BigInteger remainder); + +#if NET + var bufferSize = 512; + Span charBuffer = stackalloc char[bufferSize]; + int charsWritten; + while (!quotient.TryFormat(charBuffer, out charsWritten)) + { + bufferSize *= 4; + charBuffer = new char[bufferSize]; + } + + if (charsWritten + 2 > bufferSize) + { + bufferSize *= 2; + var extendedBuffer = new char[bufferSize * 2]; + charBuffer.CopyTo(extendedBuffer); + charBuffer = extendedBuffer; + } + + BigInteger ten = 10; + charBuffer[charsWritten++] = '.'; + remainder = BigInteger.Abs(remainder); + do + { + var digit = (int)BigInteger.DivRem(remainder * ten, denominator, out remainder); + if (charsWritten == bufferSize) + { + // extend the buffer + bufferSize *= 2; + var extendedBuffer = new char[bufferSize * 2]; + charBuffer.CopyTo(extendedBuffer); + charBuffer = extendedBuffer; + } + + charBuffer[charsWritten++] = (char)('0' + digit); + } while (!remainder.IsZero); + + writer.WriteRawValue(new string(charBuffer[..charsWritten])); +#else + // decimal number + StringBuilder sb = new StringBuilder(quotient.ToString()).Append('.'); + BigInteger ten = 10; + remainder = BigInteger.Abs(remainder); + do + { + var digit = (int)BigInteger.DivRem(remainder * ten, denominator, out remainder); + sb.Append((char)('0' + digit)); + } while (!remainder.IsZero); + + writer.WriteRawValue(sb.ToString()); +#endif + + static void WriteSmallTerms(JsonWriter writer, long numerator, long denominator) + { + switch (denominator) + { + case 0: + // NaN or Infinity + switch (numerator) + { + case > 0: + writer.WriteValue(NumberFormatInfo.InvariantInfo.PositiveInfinitySymbol); + return; + case < 0: + writer.WriteValue(NumberFormatInfo.InvariantInfo.NegativeInfinitySymbol); + return; + default: + writer.WriteValue(NumberFormatInfo.InvariantInfo.NaNSymbol); + return; + } + case 1: + writer.WriteValue(numerator); + return; + } + + var quotient = Math.DivRem(numerator, denominator, out var remainder); + + // decimal number + const int bufferSize = 45; +#if NET + Span charBuffer = stackalloc char[bufferSize]; + + quotient.TryFormat(charBuffer, out var charsWritten); +#else + var charBuffer = new char[bufferSize]; + var quotientString = quotient.ToString(); + quotientString.CopyTo(0, charBuffer, 0, quotientString.Length); + var charsWritten = quotientString.Length; +#endif + charBuffer[charsWritten++] = '.'; + remainder = Math.Abs(remainder); + do + { + var digit = Math.DivRem(remainder * 10, denominator, out remainder); + + charBuffer[charsWritten++] = (char)(digit + '0'); + if (remainder == 0) + { + #if NET + writer.WriteRawValue(new string(charBuffer[..charsWritten])); + #else + writer.WriteRawValue(new string(charBuffer, 0, charsWritten)); + #endif + return; + } + } while (charsWritten < bufferSize); + + // failed to format the value as a decimal number + writer.WriteValue($"{numerator}/{denominator}"); + } + } + + public static QuantityValue ReadValue(this JsonReader reader, JsonSerializer serializer, QuantityValueDeserializationFormat format) + { + switch (format) + { + case QuantityValueDeserializationFormat.ExactNumber: + return reader.ReadExactNumber(); + case QuantityValueDeserializationFormat.RoundedDouble: + return reader.ReadValueFromDouble(); + case QuantityValueDeserializationFormat.RoundTripping: + return reader.ReadValueRoundTripping(); + case QuantityValueDeserializationFormat.Custom: + default: + reader.Read(); + return serializer.Deserialize(reader); + } + } + + public static QuantityValue ReadExactNumber(this JsonReader reader) + { + var valueString = reader.ReadAsString(); + if (valueString == null) + { + throw new JsonSerializationException("Error converting value {null} to type 'QuantityValue'"); + } + + return QuantityValue.Parse(valueString, NumberStyles.Float, CultureInfo.InvariantCulture); + } + + public static QuantityValue ReadValueFromDouble(this JsonReader reader) + { + var doubleValue = reader.ReadAsDouble(); + if (!doubleValue.HasValue) + { + throw new JsonSerializationException("Error converting value {null} to type 'QuantityValue'"); + } + + return QuantityValue.FromDoubleRounded(doubleValue.Value); + } + + public static QuantityValue ReadValueRoundTripping(this JsonReader reader) + { + var valueString = reader.ReadAsString(); + if (valueString == null) + { + throw new JsonSerializationException("Error converting value {null} to type 'QuantityValue'"); + } + +#if NET + ReadOnlySpan valueSpan = valueString.AsSpan(); + return TryParseFraction(valueSpan, out QuantityValue quantityValue) + ? quantityValue + : QuantityValue.Parse(valueSpan, NumberStyles.Float, CultureInfo.InvariantCulture); +#else + return TryParseFraction(valueString, out QuantityValue quantityValue) + ? quantityValue + : QuantityValue.Parse(valueString, NumberStyles.Float, CultureInfo.InvariantCulture); +#endif + +#if NET + static bool TryParseFraction(ReadOnlySpan value, out QuantityValue quantityValue) + { + if (value.TrySplit('/', out ReadOnlySpan numeratorSpan, out ReadOnlySpan denominatorSpan)) + { + if (BigInteger.TryParse(numeratorSpan, out BigInteger numerator) && BigInteger.TryParse(denominatorSpan, out BigInteger denominator)) + { + quantityValue = QuantityValue.FromTerms(numerator, denominator); + return true; + } + } + + quantityValue = default; + return false; + } +#else + static bool TryParseFraction(string valueToken, out QuantityValue quantityValue) + { + var ranges = valueToken.Split('/'); + if (ranges.Length == 2) + { + if (BigInteger.TryParse(ranges[0], out BigInteger numerator) && BigInteger.TryParse(ranges[1], out BigInteger denominator)) + { + quantityValue = QuantityValue.FromTerms(numerator, denominator); + return true; + } + } + + quantityValue = default; + return false; + } +#endif + } +} diff --git a/UnitsNet.Serialization.JsonNet/QuantityValueFormatOptions.cs b/UnitsNet.Serialization.JsonNet/QuantityValueFormatOptions.cs new file mode 100644 index 0000000000..422c621926 --- /dev/null +++ b/UnitsNet.Serialization.JsonNet/QuantityValueFormatOptions.cs @@ -0,0 +1,101 @@ +// 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. + +namespace UnitsNet.Serialization.JsonNet; + +/// +/// Represents options for formatting quantity values during serialization and deserialization. +/// +public record struct QuantityValueFormatOptions( + QuantityValueSerializationFormat SerializationFormat = QuantityValueSerializationFormat.DecimalPrecision, + QuantityValueDeserializationFormat DeserializationFormat = QuantityValueDeserializationFormat.ExactNumber); + +/// +/// Specifies the format used for serializing to JSON. +/// +public enum QuantityValueSerializationFormat +{ + /// + /// Represents the serialization format where the quantity value is serialized as a number with decimal precision. + /// + /// + /// This number is represented with up to 29 significant digits. Numbers such as "1/3" would be represented as + /// "0.3333333333333333333333333333". + /// + DecimalPrecision, + + /// + /// Represents the serialization format where the quantity value is serialized as a number with double precision. + /// + /// + /// This number is represented with up to 17 significant digits. Numbers such as "1/3" would be represented as + /// "0.3333333333333333". + /// + DoublePrecision, + + /// + /// Represents a serialization format that ensures the exact value of a quantity is preserved during serialization and + /// deserialization. + /// This format is particularly useful for scenarios where precision and round-trip accuracy are critical. + /// + /// + /// This format dynamically switches between decimal and fractional notation + /// depending on the value being serialized. This ensures that the serialized representation is both precise and + /// compact. + /// For example: + /// - A value such as 1.23456789 will be serialized in decimal notation, including all significant digits. + /// - A value such as 1/3 will be serialized as a fraction (e.g., "1/3"). + /// This format is ideal for scenarios where the exact representation of a value is required for round-trip + /// serialization and deserialization. + /// + RoundTripping, + + /// + /// Relies on the presence of a custom converter for the . + /// + /// + /// When this option is selected JsonConvert is used for the serialization. + /// + Custom +} + +/// +/// Specifies the format used for deserializing from JSON. +/// +public enum QuantityValueDeserializationFormat +{ + /// + /// Deserializes the quantity value as exact number in decimal notation. + /// + ExactNumber, + + /// + /// Deserializes the quantity value as a double precision number, which is then rounded to 15 significant digits. + /// + RoundedDouble, + + /// + /// Represents a serialization format that ensures the exact value of a quantity is preserved during serialization and + /// deserialization. + /// This format is particularly useful for scenarios where precision and round-trip accuracy are critical. + /// + /// + /// This format dynamically switches between decimal and fractional notation + /// depending on the value being serialized. This ensures that the serialized representation is both precise and + /// compact. + /// For example: + /// - A value such as 1.23456789 will be serialized in decimal notation, including all significant digits. + /// - A value such as 1/3 will be serialized as a fraction (e.g., "1/3"). + /// This format is ideal for scenarios where the exact representation of a value is required for round-trip + /// serialization and deserialization. + /// + RoundTripping, + + /// + /// Relies on the presence of a custom converter for the . + /// + /// + /// When this option is selected JsonConvert is used for the deserialization. + /// + Custom +} diff --git a/UnitsNet.Serialization.JsonNet/StringExtensions.cs b/UnitsNet.Serialization.JsonNet/StringExtensions.cs index 0c99180464..d2e535fb7f 100644 --- a/UnitsNet.Serialization.JsonNet/StringExtensions.cs +++ b/UnitsNet.Serialization.JsonNet/StringExtensions.cs @@ -2,6 +2,9 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System.Diagnostics.CodeAnalysis; +#if NET +using System; +#endif namespace UnitsNet.Serialization.JsonNet { @@ -21,5 +24,23 @@ internal static class StringExtensions ? value.Substring(0, maxLength - truncationSuffix.Length) + truncationSuffix : value; } + +#if NET + public static bool TrySplit(this ReadOnlySpan span, char separator, out ReadOnlySpan firstSpan, out ReadOnlySpan secondSpan) + { + var separatorIndex = span.IndexOf(separator); + + if (separatorIndex < 0) + { + firstSpan = span; + secondSpan = ReadOnlySpan.Empty; + return false; + } + + firstSpan = span.Slice(0, separatorIndex); + secondSpan = span.Slice(separatorIndex + 1); + return true; + } +#endif } } diff --git a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj index c1ba0ba426..44671a960d 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj +++ b/UnitsNet.Serialization.JsonNet/UnitsNet.Serialization.JsonNet.csproj @@ -1,8 +1,8 @@ - + UnitsNet.Serialization.JsonNet - 6.0.0-pre007 + 6.0.0-pre018 Andreas Gullberg Larsen Units.NET Serialization with Json.NET A helper library for serializing and deserializing types in Units.NET using Json.NET. diff --git a/UnitsNet.Serialization.JsonNet/UnitsNetBaseJsonConverter.cs b/UnitsNet.Serialization.JsonNet/UnitsNetBaseJsonConverter.cs index 73f4cce110..c6f2a2952f 100644 --- a/UnitsNet.Serialization.JsonNet/UnitsNetBaseJsonConverter.cs +++ b/UnitsNet.Serialization.JsonNet/UnitsNetBaseJsonConverter.cs @@ -25,7 +25,7 @@ public abstract class UnitsNetBaseJsonConverter : NullableQuantityConverter /// Register custom types so that the converter can instantiate these quantities. - /// Instead of calling , the will be used to instantiate the object. + /// Instead of calling , the will be used to instantiate the object. /// It is therefore assumed that the constructor of is specified with new T(double value, typeof() unit). /// Registering the same multiple times, it will overwrite the one registered. /// @@ -96,10 +96,23 @@ protected IQuantity ConvertValueUnit(ValueUnit valueUnit) if (registeredQuantity is not null) { - return (IQuantity)Activator.CreateInstance(registeredQuantity, valueUnit.Value, unit)!; + var instance = Activator.CreateInstance(registeredQuantity, (QuantityValue)valueUnit.Value, unit); + if (instance is IQuantity quantityCreated) + { + return quantityCreated; + } + + if (instance is not null) + { + throw new InvalidOperationException( + $"The instance created for '{registeredQuantity.Name}' is not a valid quantity: '{instance.GetType()}'."); + } + + throw new InvalidOperationException( + $"Cannot create instance of type {registeredQuantity.Name} from value {valueUnit.Value} and unit {valueUnit.Unit}."); } - return Quantity.From(valueUnit.Value, unit); + return Quantity.From(QuantityValue.FromDoubleRounded(valueUnit.Value), unit); } private (Type? Quantity, Type? Unit) GetRegisteredType(string unit) diff --git a/UnitsNet.Serialization.JsonNet/Value/QuantityValueFractionalNotationConverter.cs b/UnitsNet.Serialization.JsonNet/Value/QuantityValueFractionalNotationConverter.cs new file mode 100644 index 0000000000..3376106aca --- /dev/null +++ b/UnitsNet.Serialization.JsonNet/Value/QuantityValueFractionalNotationConverter.cs @@ -0,0 +1,157 @@ +// 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 System.Numerics; +using Newtonsoft.Json; + +namespace UnitsNet.Serialization.JsonNet.Value; + +/// +/// A custom JSON converter for serializing and deserializing objects. +/// +/// +/// This converter handles the serialization of as a fraction, +/// represented by its numerator and denominator, to ensure precise representation of values. +/// +public class QuantityValueFractionalNotationConverter : JsonConverter +{ + private const string NumeratorPropertyName = "N"; + private const string DenominatorPropertyName = "D"; + private readonly bool _reduceTerms; + + /// + /// Gets the default instance of the . + /// + /// + /// This property provides a pre-configured, shared instance of the converter + /// with default settings, simplifying the serialization and deserialization + /// of objects in JSON format. + /// + public static QuantityValueFractionalNotationConverter Default { get; } = new(); + + /// + /// Gets an instance of configured to reduce terms + /// during serialization and deserialization. + /// + /// + /// This property provides a pre-configured converter that simplifies fractional representations + /// by reducing the numerator and denominator to their smallest terms. + /// + public static QuantityValueFractionalNotationConverter Reducing { get; } = new(true); + + /// + /// Initializes a new instance of the class + /// with default settings. + /// + /// + /// This constructor sets up the converter to handle the serialization and deserialization + /// of objects in JSON format, using default behavior. + /// + public QuantityValueFractionalNotationConverter() + : this(false) + { + } + + /// + /// Initializes a new instance of the class + /// with the default configuration. + /// + /// + /// This constructor sets up the converter with default settings, where terms are not reduced + /// during serialization and deserialization. + /// + public QuantityValueFractionalNotationConverter(bool reduceTerms) + { + _reduceTerms = reduceTerms; + } + + /// + public override void WriteJson(JsonWriter writer, QuantityValue value, JsonSerializer serializer) + { + (BigInteger numerator, BigInteger denominator) = _reduceTerms ? QuantityValue.Reduce(value) : value; + + writer.WriteStartObject(); + + if((serializer.DefaultValueHandling & DefaultValueHandling.Ignore) != 0) + { + // Write only if the property is non-default. + if (!numerator.IsZero) + { + writer.WritePropertyName(NumeratorPropertyName); + serializer.Serialize(writer, numerator); + } + + if (!denominator.IsOne) + { + writer.WritePropertyName(DenominatorPropertyName); + serializer.Serialize(writer, denominator); + } + } + else + { + writer.WritePropertyName(NumeratorPropertyName); + serializer.Serialize(writer, numerator); + writer.WritePropertyName(DenominatorPropertyName); + serializer.Serialize(writer, denominator); + } + + writer.WriteEndObject(); + } + + /// + public override QuantityValue ReadJson(JsonReader reader, Type objectType, QuantityValue existingValue, bool hasExistingValue, + JsonSerializer serializer) + { + BigInteger? numerator = null; + BigInteger? denominator = null; + // Ensure the reader is at the start of an object + if (reader.TokenType != JsonToken.StartObject) + { + throw new JsonSerializationException("Expected StartObject token."); + } + + // Read through the JSON object + while (reader.Read()) + { + if (reader.TokenType == JsonToken.EndObject) + { + break; // End of the object + } + + if (reader.TokenType == JsonToken.PropertyName) + { + var propertyName = (string)reader.Value!; + reader.Read(); // Move to the value + if (string.Equals(propertyName, NumeratorPropertyName, StringComparison.OrdinalIgnoreCase)) + { + numerator = serializer.Deserialize(reader); + } + else if (string.Equals(propertyName, DenominatorPropertyName, StringComparison.OrdinalIgnoreCase)) + { + denominator = serializer.Deserialize(reader); + } + else if (serializer.MissingMemberHandling == MissingMemberHandling.Ignore) + { + reader.Skip(); + } + else + { + throw new JsonException($"'{propertyName}' was no found in the list of members of '{objectType}'."); + } + } + } + + if (numerator.HasValue && denominator.HasValue) + { + return QuantityValue.FromTerms(numerator.Value, denominator.Value); + } + + if (numerator.HasValue) + { + return numerator.Value; + } + + return denominator.HasValue ? QuantityValue.FromTerms(BigInteger.Zero, denominator.Value) : QuantityValue.Zero; + } +} diff --git a/UnitsNet.Serialization.SystemTextJson.Tests/AbbreviatedInterfaceQuantityConverterWithValueConverterTest.cs b/UnitsNet.Serialization.SystemTextJson.Tests/AbbreviatedInterfaceQuantityConverterWithValueConverterTest.cs new file mode 100644 index 0000000000..abe65b66f6 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson.Tests/AbbreviatedInterfaceQuantityConverterWithValueConverterTest.cs @@ -0,0 +1,269 @@ +// 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.Text.Json; +using System.Text.Json.Serialization; +using JetBrains.Annotations; +using UnitsNet.Serialization.SystemTextJson.Value; +using UnitsNet.Units; + +namespace UnitsNet.Serialization.SystemTextJson.Tests; + +[TestSubject(typeof(AbbreviatedInterfaceQuantityWithValueConverter))] +public class AbbreviatedInterfaceQuantityConverterWithValueConverterTest +{ + [Fact] + public void Constructor_WithNullAbbreviations_ThrowsArgumentNullException() + { + Assert.Throws(() => new AbbreviatedInterfaceQuantityWithValueConverter(null!)); + Assert.Throws(() => new AbbreviatedInterfaceQuantityWithValueConverter(QuantityValueMixedNotationConverter.Default, null!)); + } + + [Theory] + [InlineData("""{"Value":10,"Unit":"m","Type":"Length"}""", typeof(Length), 10, LengthUnit.Meter)] + [InlineData("""{"Value":5,"Unit":"g","Type":"Mass"}""", typeof(Mass), 5, MassUnit.Gram)] + [InlineData("""{"Value":5,"Type":"Mass"}""", typeof(Mass), 5, MassUnit.Kilogram)] + [InlineData("""{"Value":5,"Unit":"kg"}""", typeof(Mass), 5, MassUnit.Kilogram)] + [InlineData("""{"Value":0,"Unit":"s","Type":"Duration"}""", typeof(Duration), 0, DurationUnit.Second)] + public void Deserializing_WithDecimalNotation_ReturnsCorrectQuantity(string json, Type expectedType, decimal expectedValue, Enum expectedUnit) + { + // Arrange + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithValueConverter(QuantityValueMixedNotationConverter.Default)); + + // Act + IQuantity result = JsonSerializer.Deserialize(json, options)!; + + // Assert + Assert.IsType(expectedType, result); + Assert.Equal(expectedValue, result.Value); + Assert.Equal(expectedUnit, result.Unit); + } + + [Theory] + [InlineData("""{"value":10,"unit":"m","type":"Length"}""", typeof(Length), 10, LengthUnit.Meter)] + [InlineData("""{"value":5,"unit":"g","type":"Mass"}""", typeof(Mass), 5, MassUnit.Gram)] + [InlineData("""{"value":0,"unit":"s","type":"Duration"}""", typeof(Duration), 0, DurationUnit.Second)] + public void Deserializing_WithDecimalNotation_And_CamelCasePropertyNamingPolicy_ReturnsCorrectQuantity(string json, Type expectedType, decimal expectedValue, Enum expectedUnit) + { + // Arrange + var options = new JsonSerializerOptions {PropertyNamingPolicy = JsonNamingPolicy.CamelCase}; + options.Converters.Add(new AbbreviatedInterfaceQuantityWithValueConverter(QuantityValueMixedNotationConverter.Default)); + + // Act + IQuantity result = JsonSerializer.Deserialize(json, options)!; + + // Assert + Assert.IsType(expectedType, result); + Assert.Equal(expectedValue, result.Value); + Assert.Equal(expectedUnit, result.Unit); + } + + + [Theory] + [InlineData("""{"Value":10,"Unit":"m","Type":"Length"}""", typeof(Length), 10, LengthUnit.Meter)] + [InlineData("""{"value":5,"unit":"g","type":"Mass"}""", typeof(Mass), 5, MassUnit.Gram)] + [InlineData("""{"VALUE":0,"uniT":"s","tYPe":"Duration"}""", typeof(Duration), 0, DurationUnit.Second)] + public void Deserializing_WithDecimalNotation_IgnoringCase_ReturnsCorrectQuantity(string json, Type expectedType, decimal expectedValue, Enum expectedUnit) + { + // Arrange + var options = new JsonSerializerOptions {PropertyNameCaseInsensitive = true}; + options.Converters.Add(new AbbreviatedInterfaceQuantityWithValueConverter(QuantityValueMixedNotationConverter.Default)); + + // Act + IQuantity result = JsonSerializer.Deserialize(json, options)!; + + // Assert + Assert.IsType(expectedType, result); + Assert.Equal(expectedValue, result.Value); + Assert.Equal(expectedUnit, result.Unit); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Deserializing_WithDecimalNotation_WithExtraProperties(bool ignoreCasing) + { + // Arrange + const string json = """{"UnknownProperty":"Something", "Value":5,"Unit":"g","Type":"Mass"}"""; + var expectedQuantity = Mass.FromGrams(5); + var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = ignoreCasing }; + options.Converters.Add(new AbbreviatedInterfaceQuantityWithValueConverter(QuantityValueMixedNotationConverter.Default)); + + // Act + IQuantity result = JsonSerializer.Deserialize(json, options)!; + + // Assert + Assert.Equal(expectedQuantity, result); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Deserialize_WithAdditionalProperties_WhenUnmappedMemberHandlingIsDisallowed_ThrowsJsonException(bool ignoreCasing) + { + // Arrange + const string json = """{"UnknownProperty":"Something", "Value":5,"Unit":"g","Type":"Mass"}"""; + var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = ignoreCasing, UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow}; + options.Converters.Add(new AbbreviatedInterfaceQuantityWithValueConverter(QuantityValueMixedNotationConverter.Default)); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_WithoutUnitAndType_ThrowsJsonException() + { + // Arrange + const string json = """{"Value":5}"""; + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithValueConverter(QuantityValueMixedNotationConverter.Default)); + + // Act + var exception = Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + + // Assert + Assert.Equal("Both the quantity name and unit abbreviation are missing from the JSON.", exception.Message); + } + + [Fact] + public void Deserializing_WithAmbiguousUnitAndNotType_ThrowsAmbiguousUnitParseException() + { + // Arrange + const string json = """{"Value":10,"Unit":"m"}""";; + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithValueConverter(QuantityValueMixedNotationConverter.Default)); + + // Act + var exception = Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + + // Assert + Assert.Equal("""Cannot parse "m" since it matches multiple units: Meter ("m"), Minute ("m").""", exception.Message); + } + + [Fact] + public void Deserializing_WithNonAmbiguousUnitAndNoType_ReturnsTheExpectedQuantity() + { + // Arrange + const string json = """{"Value":10,"Unit":"m"}""";; + var expected = Length.FromMeters(10); + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithValueConverter(QuantityValueMixedNotationConverter.Default, new UnitParser([Length.Info]))); + + // Act + IQuantity result = JsonSerializer.Deserialize(json, options)!; + + // Assert + Assert.Equal(expected, result); + } + + [Theory] + [InlineData(10, "Meter", "Length", """{"Value":10,"Unit":"m","Type":"Length"}""")] + [InlineData(5, "Kilogram", "Mass", """{"Value":5,"Unit":"kg","Type":"Mass"}""")] + [InlineData(0, "Second", "Duration", """{"Value":0,"Unit":"s","Type":"Duration"}""")] + public void Serializing_WithDecimalNotation_ReturnsTheExpectedJson(double value, string unit, string type, string expectedJson) + { + // Arrange + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithValueConverter(QuantityValueMixedNotationConverter.Default)); + + IQuantity quantity = Quantity.From(value, type, unit); + + // Act + var actualJson = JsonSerializer.Serialize(quantity, options); + + // Assert + Assert.Equal(expectedJson, actualJson); + } + + [Fact] + public void Deserializing_WithUnknownQuantity_ThrowsQuantityNotFoundException() + { + // Arrange + const string json = """{"Value":10,"Unit":"m","Type":"Length"}""";; + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithValueConverter(QuantityValueMixedNotationConverter.Default, new UnitParser([Mass.Info]))); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_WithUnknownUnit_ThrowsUnitNotFoundException() + { + // Arrange + const string json = """{"Value":10,"Unit":"unknown","Type":"Length"}""";; + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithValueConverter(QuantityValueMixedNotationConverter.Default)); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Theory] + [InlineData(10, "Meter", "Length", """{"value":10,"unit":"m","type":"Length"}""")] + [InlineData(5, "Kilogram", "Mass", """{"value":5,"unit":"kg","type":"Mass"}""")] + [InlineData(0, "Second", "Duration", """{"value":0,"unit":"s","type":"Duration"}""")] + public void Serializing_WithDecimalNotation_And_CamelCasePropertyNamingPolicy_ReturnsTheExpectedJson(double value, string unit, string type, string expectedJson) + { + // Arrange + var options = new JsonSerializerOptions {PropertyNamingPolicy = JsonNamingPolicy.CamelCase}; + options.Converters.Add(new AbbreviatedInterfaceQuantityWithValueConverter(QuantityValueMixedNotationConverter.Default)); + + IQuantity quantity = Quantity.From(value, type, unit); + + // Act + var actualJson = JsonSerializer.Serialize(quantity, options); + + // Assert + Assert.Equal(expectedJson, actualJson); + } + + [Theory] + [InlineData(10, "Centimeter", "Length", """{"Value":10,"Unit":"cm","Type":"Length"}""")] + [InlineData(5, "Kilogram", "Mass", """{"Value":5,"Type":"Mass"}""")] + [InlineData(0, "Second", "Duration", """{"Type":"Duration"}""")] + public void Serializing_WithDecimalNotation_IgnoringDefaultValues_ReturnsTheExpectedJson(double value, string unit, string quantityName, string expectedJson) + { + // Arrange + var options = new JsonSerializerOptions {DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault}; + options.Converters.Add(new AbbreviatedInterfaceQuantityWithValueConverter(QuantityValueMixedNotationConverter.Default)); + + IQuantity quantity = Quantity.From(value, quantityName, unit); + + // Act + var actualJson = JsonSerializer.Serialize(quantity, options); + + // Assert + Assert.Equal(expectedJson, actualJson); + } + + [Fact] + public void Serializing_NullQuantity_WritesNull() + { + // Arrange + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithValueConverter(QuantityValueMixedNotationConverter.Default)); + + IQuantity quantity = null!; + + // Act + var actualJson = JsonSerializer.Serialize(quantity, options); + + // Assert + Assert.Equal("null", actualJson); + } + + [Fact] + public void Serializing_UnknownQuantity_ThrowsUnitNotFoundException() + { + // Arrange + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithValueConverter(QuantityValueMixedNotationConverter.Default, new UnitParser([Mass.Info]))); + + IQuantity quantity = Length.Zero; + + // Assert + Assert.Throws(() => JsonSerializer.Serialize(quantity, options)); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson.Tests/AbbreviatedInterfaceQuantityWithAvailableValueConverterTest.cs b/UnitsNet.Serialization.SystemTextJson.Tests/AbbreviatedInterfaceQuantityWithAvailableValueConverterTest.cs new file mode 100644 index 0000000000..08e7832a0b --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson.Tests/AbbreviatedInterfaceQuantityWithAvailableValueConverterTest.cs @@ -0,0 +1,311 @@ +// 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.Text.Json; +using System.Text.Json.Serialization; +using JetBrains.Annotations; +using UnitsNet.Serialization.SystemTextJson.Value; +using UnitsNet.Units; + +namespace UnitsNet.Serialization.SystemTextJson.Tests; + +[TestSubject(typeof(AbbreviatedInterfaceQuantityWithAvailableValueConverter))] +public class AbbreviatedInterfaceQuantityWithAvailableValueConverterTest +{ + [Fact] + public void Constructor_WithNullAbbreviations_ThrowsArgumentNullException() + { + Assert.Throws(() => new AbbreviatedInterfaceQuantityWithAvailableValueConverter(null!)); + } + + [Theory] + [InlineData("""{"Value":10,"Unit":"m","Type":"Length"}""", typeof(Length), 10, LengthUnit.Meter)] + [InlineData("""{"Value":5,"Unit":"g","Type":"Mass"}""", typeof(Mass), 5, MassUnit.Gram)] + [InlineData("""{"Value":5,"Type":"Mass"}""", typeof(Mass), 5, MassUnit.Kilogram)] + [InlineData("""{"Value":5,"Unit":"kg"}""", typeof(Mass), 5, MassUnit.Kilogram)] + [InlineData("""{"Value":0,"Unit":"s","Type":"Duration"}""", typeof(Duration), 0, DurationUnit.Second)] + public void Deserializing_WithDecimalNotation_ReturnsCorrectQuantity(string json, Type expectedType, decimal expectedValue, Enum expectedUnit) + { + // Arrange + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter()); + + // Act + IQuantity result = JsonSerializer.Deserialize(json, options)!; + + // Assert + Assert.IsType(expectedType, result); + Assert.Equal(expectedValue, result.Value); + Assert.Equal(expectedUnit, result.Unit); + } + + [Theory] + [InlineData("""{"value":10,"unit":"m","type":"Length"}""", typeof(Length), 10, LengthUnit.Meter)] + [InlineData("""{"value":5,"unit":"g","type":"Mass"}""", typeof(Mass), 5, MassUnit.Gram)] + [InlineData("""{"value":0,"unit":"s","type":"Duration"}""", typeof(Duration), 0, DurationUnit.Second)] + public void Deserializing_WithDecimalNotation_And_CamelCasePropertyNamingPolicy_ReturnsCorrectQuantity(string json, Type expectedType, decimal expectedValue, Enum expectedUnit) + { + // Arrange + var options = new JsonSerializerOptions {PropertyNamingPolicy = JsonNamingPolicy.CamelCase}; + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter()); + + // Act + IQuantity result = JsonSerializer.Deserialize(json, options)!; + + // Assert + Assert.IsType(expectedType, result); + Assert.Equal(expectedValue, result.Value); + Assert.Equal(expectedUnit, result.Unit); + } + + + [Theory] + [InlineData("""{"Value":10,"Unit":"m","Type":"Length"}""", typeof(Length), 10, LengthUnit.Meter)] + [InlineData("""{"value":5,"unit":"g","type":"Mass"}""", typeof(Mass), 5, MassUnit.Gram)] + [InlineData("""{"VALUE":0,"uniT":"s","tYPe":"Duration"}""", typeof(Duration), 0, DurationUnit.Second)] + public void Deserializing_WithDecimalNotation_IgnoringCase_ReturnsCorrectQuantity(string json, Type expectedType, decimal expectedValue, Enum expectedUnit) + { + // Arrange + var options = new JsonSerializerOptions {PropertyNameCaseInsensitive = true}; + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter()); + + // Act + IQuantity result = JsonSerializer.Deserialize(json, options)!; + + // Assert + Assert.IsType(expectedType, result); + Assert.Equal(expectedValue, result.Value); + Assert.Equal(expectedUnit, result.Unit); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Deserializing_WithDecimalNotation_WithExtraProperties(bool ignoreCasing) + { + // Arrange + const string json = """{"UnknownProperty":"Something", "Value":5,"Unit":"g","Type":"Mass"}"""; + var expectedQuantity = Mass.FromGrams(5); + var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = ignoreCasing }; + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter()); + + // Act + IQuantity result = JsonSerializer.Deserialize(json, options)!; + + // Assert + Assert.Equal(expectedQuantity, result); + } + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Deserialize_WithAdditionalProperties_WhenUnmappedMemberHandlingIsDisallowed_ThrowsJsonException(bool ignoreCasing) + { + // Arrange + const string json = """{"UnknownProperty":"Something", "Value":5,"Unit":"g","Type":"Mass"}"""; + var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = ignoreCasing, UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow}; + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter()); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_WithoutUnitAndType_ThrowsJsonException() + { + // Arrange + const string json = """{"Value":5}"""; + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter()); + + // Act + var exception = Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + + // Assert + Assert.Equal("Both the quantity name and unit abbreviation are missing from the JSON.", exception.Message); + } + + [Fact] + public void Deserializing_WithAmbiguousUnitAndNotType_ThrowsAmbiguousUnitParseException() + { + // Arrange + const string json = """{"Value":10,"Unit":"m"}""";; + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter()); + + // Act + var exception = Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + + // Assert + Assert.Equal("""Cannot parse "m" since it matches multiple units: Meter ("m"), Minute ("m").""", exception.Message); + } + + [Fact] + public void Deserializing_WithNonAmbiguousUnitAndNoType_ReturnsTheExpectedQuantity() + { + // Arrange + const string json = """{"Value":10,"Unit":"m"}""";; + var expected = Length.FromMeters(10); + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter(new UnitParser([Length.Info]))); + + // Act + IQuantity result = JsonSerializer.Deserialize(json, options)!; + + // Assert + Assert.Equal(expected, result); + } + + [Theory] + [InlineData(10, "Meter", "Length", """{"Value":10,"Unit":"m","Type":"Length"}""")] + [InlineData(5, "Kilogram", "Mass", """{"Value":5,"Unit":"kg","Type":"Mass"}""")] + [InlineData(0, "Second", "Duration", """{"Value":0,"Unit":"s","Type":"Duration"}""")] + public void Serializing_WithDecimalNotation_ReturnsTheExpectedJson(double value, string unit, string type, string expectedJson) + { + // Arrange + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter()); + + IQuantity quantity = Quantity.From(value, type, unit); + + // Act + var actualJson = JsonSerializer.Serialize(quantity, options); + + // Assert + Assert.Equal(expectedJson, actualJson); + } + + [Fact] + public void Deserializing_WithUnknownQuantity_ThrowsQuantityNotFoundException() + { + // Arrange + const string json = """{"Value":10,"Unit":"m","Type":"Length"}""";; + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter(new UnitParser([Mass.Info]))); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_WithUnknownUnit_ThrowsUnitNotFoundException() + { + // Arrange + const string json = """{"Value":10,"Unit":"unknown","Type":"Length"}""";; + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter()); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_WithoutQuantityValueConverter_ThrowsJsonException() + { + // Arrange + const string json = """{"Value":10,"Unit":"m","Type":"Length"}""";; + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter()); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Theory] + [InlineData(10, "Meter", "Length", """{"value":10,"unit":"m","type":"Length"}""")] + [InlineData(5, "Kilogram", "Mass", """{"value":5,"unit":"kg","type":"Mass"}""")] + [InlineData(0, "Second", "Duration", """{"value":0,"unit":"s","type":"Duration"}""")] + public void Serializing_WithDecimalNotation_And_CamelCasePropertyNamingPolicy_ReturnsTheExpectedJson(double value, string unit, string type, string expectedJson) + { + // Arrange + var options = new JsonSerializerOptions {PropertyNamingPolicy = JsonNamingPolicy.CamelCase}; + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter()); + + IQuantity quantity = Quantity.From(value, type, unit); + + // Act + var actualJson = JsonSerializer.Serialize(quantity, options); + + // Assert + Assert.Equal(expectedJson, actualJson); + } + + [Theory] + [InlineData(10, "Centimeter", "Length", """{"Value":10,"Unit":"cm","Type":"Length"}""")] + [InlineData(5, "Kilogram", "Mass", """{"Value":5,"Type":"Mass"}""")] + [InlineData(0, "Second", "Duration", """{"Type":"Duration"}""")] + public void Serializing_WithDecimalNotation_IgnoringDefaultValues_ReturnsTheExpectedJson(double value, string unit, string quantityName, string expectedJson) + { + // Arrange + var options = new JsonSerializerOptions {DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault}; + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter()); + + IQuantity quantity = Quantity.From(value, quantityName, unit); + + // Act + var actualJson = JsonSerializer.Serialize(quantity, options); + + // Assert + Assert.Equal(expectedJson, actualJson); + } + + [Fact] + public void Serializing_NullQuantity_WritesNull() + { + // Arrange + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter()); + + IQuantity quantity = null!; + + // Act + var actualJson = JsonSerializer.Serialize(quantity, options); + + // Assert + Assert.Equal("null", actualJson); + } + + [Fact] + public void Serializing_WithoutQuantityValueConverter_LeavesTheValueObjectEmpty() + { + // Arrange + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter()); + + IQuantity quantity = new Length(42, LengthUnit.Meter); + const string expectedJson = """{"Value":{},"Unit":"m","Type":"Length"}"""; + + // Act + var result = JsonSerializer.Serialize(quantity, options); + + // Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Serializing_UnknownQuantity_ThrowsUnitNotFoundException() + { + // Arrange + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter(new UnitParser([Mass.Info]))); + + IQuantity quantity = Length.Zero; + + // Assert + Assert.Throws(() => JsonSerializer.Serialize(quantity, options)); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson.Tests/AbbreviatedQuantityConverterTests.cs b/UnitsNet.Serialization.SystemTextJson.Tests/AbbreviatedQuantityConverterTests.cs new file mode 100644 index 0000000000..c822e29f2e --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson.Tests/AbbreviatedQuantityConverterTests.cs @@ -0,0 +1,63 @@ +// 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.Text.Json; +using JetBrains.Annotations; +using UnitsNet.Serialization.SystemTextJson.Value; +using UnitsNet.Units; + +namespace UnitsNet.Serialization.SystemTextJson.Tests; + +[TestSubject(typeof(AbbreviatedQuantityConverter))] +public class AbbreviatedQuantityConverterTests +{ + [Fact] + public void Serializing_WithoutAConverter_UsesDefaultFractionalNotationConverter() + { + // Arrange + var json = """{"Value":{"N":42,"D":10},"Unit":"g"}"""; + var expected = new Mass(4.2m, MassUnit.Gram); + + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedQuantityConverter()); + + // Act + var actualJson = JsonSerializer.Serialize(expected, options); + Mass result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(json, actualJson); + Assert.Equal(expected, result); + } + + [Fact] + public void Serializing_WithDecimalNotationConverter() + { + // Arrange + var json = """{"Value":4.2,"Unit":"g"}"""; + var expected = new Mass(4.2m, MassUnit.Gram); + + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedQuantityConverter(new QuantityValueDecimalNotationConverter())); + + // Act + var actualJson = JsonSerializer.Serialize(expected, options); + Mass result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(json, actualJson); + Assert.Equal(expected, result); + } + + [Fact] + public void CreateConverter_InvalidType_ReturnsNull() + { + // Arrange + var converter = new AbbreviatedQuantityConverter(); + var options = new JsonSerializerOptions(); + Type typeToConvert = typeof(string); + + // Act & Assert + Assert.Null(converter.CreateConverter(typeToConvert, options)); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson.Tests/AbbreviatedQuantityGenericConverterTests.cs b/UnitsNet.Serialization.SystemTextJson.Tests/AbbreviatedQuantityGenericConverterTests.cs new file mode 100644 index 0000000000..92ba0a7b95 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson.Tests/AbbreviatedQuantityGenericConverterTests.cs @@ -0,0 +1,51 @@ +// 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.Text.Json; +using JetBrains.Annotations; +using UnitsNet.Serialization.SystemTextJson.Value; +using UnitsNet.Units; + +namespace UnitsNet.Serialization.SystemTextJson.Tests; + +[TestSubject(typeof(AbbreviatedQuantityConverter<,>))] +public class AbbreviatedQuantityGenericConverterTests +{ + [Fact] + public void Serializing_WithoutAConverter_UsesDefaultFractionalNotationConverter() + { + // Arrange + var json = """{"Value":{"N":42,"D":10},"Unit":"g"}"""; + var expected = new Mass(4.2m, MassUnit.Gram); + + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedQuantityConverter()); + + // Act + var actualJson = JsonSerializer.Serialize(expected, options); + Mass result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(json, actualJson); + Assert.Equal(expected, result); + } + + [Fact] + public void Serializing_WithDecimalNotationConverter() + { + // Arrange + var json = """{"Value":4.2,"Unit":"g"}"""; + var expected = new Mass(4.2m, MassUnit.Gram); + + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedQuantityConverter(Mass.Info, new QuantityValueDecimalNotationConverter())); + + // Act + var actualJson = JsonSerializer.Serialize(expected, options); + Mass result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(json, actualJson); + Assert.Equal(expected, result); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson.Tests/JsonQuantityConverterFactoryTest.cs b/UnitsNet.Serialization.SystemTextJson.Tests/JsonQuantityConverterFactoryTest.cs new file mode 100644 index 0000000000..5f92db1d4c --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson.Tests/JsonQuantityConverterFactoryTest.cs @@ -0,0 +1,58 @@ +// 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.Text.Json; +using System.Text.Json.Serialization; +using JetBrains.Annotations; +using UnitsNet.Units; + +namespace UnitsNet.Serialization.SystemTextJson.Tests; + +[TestSubject(typeof(JsonQuantityConverter))] +public class JsonQuantityConverterFactoryTest +{ + [Theory] + [InlineData(typeof(int), false)] + [InlineData(typeof(double), false)] + [InlineData(typeof(string), false)] + [InlineData(typeof(Length), true)] + public void CanConvert_ReturnsExpectedResult(Type typeToConvert, bool expectedResult) + { + // Arrange + var converter = new JsonQuantityConverter(); + + // Act + var result = converter.CanConvert(typeToConvert); + + // Assert + Assert.Equal(expectedResult, result); + } + + [Fact] + public void CreateConverter_ValidType_ReturnsExpectedConverter() + { + // Arrange + var converter = new JsonQuantityConverter(); + var options = new JsonSerializerOptions(); + Type typeToConvert = typeof(Length); + + // Act + JsonConverter? result = converter.CreateConverter(typeToConvert, options); + + // Assert + Assert.NotNull(result); + Assert.IsType>(result); + } + + [Fact] + public void CreateConverter_InvalidType_ReturnsNull() + { + // Arrange + var converter = new JsonQuantityConverter(); + var options = new JsonSerializerOptions(); + Type typeToConvert = typeof(string); + + // Act & Assert + Assert.Null(converter.CreateConverter(typeToConvert, options)); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson.Tests/JsonQuantityConverterTest.cs b/UnitsNet.Serialization.SystemTextJson.Tests/JsonQuantityConverterTest.cs new file mode 100644 index 0000000000..405288fa29 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson.Tests/JsonQuantityConverterTest.cs @@ -0,0 +1,273 @@ +// 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.Text.Json; +using System.Text.Json.Serialization; +using JetBrains.Annotations; +using UnitsNet.Serialization.SystemTextJson.Unit; +using UnitsNet.Serialization.SystemTextJson.Value; +using UnitsNet.Units; + +namespace UnitsNet.Serialization.SystemTextJson.Tests; +public sealed class TestObject +{ + public Mass? NullableMass { get; set; } + public Mass NonNullableMass { get; set; } +} + +[TestSubject(typeof(JsonQuantityConverter<,>))] +public class JsonQuantityConverterTest +{ + [Fact] + public void Serializing_WithDecimalNotationAndAbbreviatedUnit() + { + // Arrange + var json = """{"Value":4.2,"Unit":"g"}"""; + var expected = new Mass(4.2m, MassUnit.Gram); + + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedUnitConverter()); + options.Converters.Add(new JsonQuantityConverter()); + + // Act + var actualJson = JsonSerializer.Serialize(expected, options); + Mass result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(json, actualJson); + Assert.Equal(expected, result); + } + + [Fact] + public void Serializing_WithDecimalNotationAndAbbreviatedUnit_WithCamelCase() + { + // Arrange + var json = """{"value":4.2,"unit":"g"}"""; + var expected = new Mass(4.2m, MassUnit.Gram); + + var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedUnitConverter()); + options.Converters.Add(new JsonQuantityConverter(Mass.Info)); + + // Act + var actualJson = JsonSerializer.Serialize(expected, options); + Mass result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(json, actualJson); + Assert.Equal(expected, result); + } + + [Fact] + public void Serializing_OneKilogram_WithGenericQuantityConverter_IgnoringDefaultValues() + { + // Arrange + var json = """{"Value":{"N":1}}"""; + var expected = new Mass(QuantityValue.One, MassUnit.Kilogram); + var options = new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault }; + options.Converters.Add(QuantityValueFractionalNotationConverter.Default); + options.Converters.Add(new JsonQuantityConverter(Mass.Info)); + + // Act + var actualJson = JsonSerializer.Serialize(expected, options); + Mass result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(json, actualJson); + Assert.Equal(expected, result); + } + + [Fact] + public void Serializing_ZeroGrams_WithGenericQuantityConverter_IgnoringDefaultValues() + { + // Arrange + var json = """{"Unit":6}"""; + var expected = new Mass(QuantityValue.Zero, MassUnit.Gram); + var options = new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault }; + options.Converters.Add(new JsonQuantityConverter(Mass.Info)); + + // Act + var actualJson = JsonSerializer.Serialize(expected, options); + Mass result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(json, actualJson); + Assert.Equal(expected, result); + } + + [Fact] + public void Serializing_ZeroMass_WithGenericQuantityConverter_IgnoringDefaultValues() + { + // Arrange + var json = "{}"; + Mass expected = Mass.Zero; + var options = new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault }; + options.Converters.Add(new JsonQuantityConverter(Mass.Info)); + + // Act + var actualJson = JsonSerializer.Serialize(expected, options); + Mass result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(json, actualJson); + Assert.Equal(expected, result); + } + + [Fact] + public void Serializing_MassAsNullable() + { + // Arrange + var testObject = new TestObject { NullableMass = Mass.FromGrams(5), NonNullableMass = Mass.FromMilligrams(10) }; + var expectedJson = """{"NullableMass":{"Value":5,"Unit":"g"},"NonNullableMass":{"Value":10,"Unit":"mg"}}"""; + + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedUnitConverter()); + options.Converters.Add(new JsonQuantityConverter(Mass.Info)); + + // Act + var json = JsonSerializer.Serialize(testObject, options); + + // Assert + Assert.Equal(expectedJson, json); + } + + [Fact] + public void Serializing_NullMass_AsNullable() + { + // Arrange + var testObject = new TestObject { NonNullableMass = Mass.FromMilligrams(10) }; + var expectedJson = """{"NullableMass":null,"NonNullableMass":{"Value":10,"Unit":"mg"}}"""; + + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedUnitConverter()); + options.Converters.Add(new JsonQuantityConverter(Mass.Info)); + + // Act + var json = JsonSerializer.Serialize(testObject, options); + + // Assert + Assert.Equal(expectedJson, json); + } + + [Fact] + public void Serializing_NullMass_AsNullable_IgnoringNullValues() + { + // Arrange + var testObject = new TestObject(); + var expectedJson = """{"NonNullableMass":{"Value":0,"Unit":"kg"}}"""; + + var options = new JsonSerializerOptions{DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull}; + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedUnitConverter()); + options.Converters.Add(new JsonQuantityConverter(Mass.Info)); + + // Act + var json = JsonSerializer.Serialize(testObject, options); + + // Assert + Assert.Equal(expectedJson, json); + } + + [Fact] + public void Serializing_NullMass_AsNullable_IgnoringNullAndDefaultValues() + { + // Arrange + var testObject = new TestObject(); + var expectedJson = "{}"; + + var options = new JsonSerializerOptions{DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault}; + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedUnitConverter()); + options.Converters.Add(new JsonQuantityConverter(Mass.Info)); + + // Act + var json = JsonSerializer.Serialize(testObject, options); + + // Assert + Assert.Equal(expectedJson, json); + } + + [Fact] + public void Deserializing_WithDecimalNotationAndAbbreviatedUnit_IgnoringCase() + { + // Arrange + var json = """{"VALUE":4.2,"uNit":"G"}"""; + var expected = new Mass(4.2m, MassUnit.Gram); + + var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true}; + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedUnitConverter()); + options.Converters.Add(new JsonQuantityConverter(Mass.Info)); + + // Act + Mass result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Deserializing_WithDecimalNotationAndAbbreviatedUnit_WithExtraProperties(bool caseInsensitive) + { + // Arrange + var json = """{"Value":4.2,"Unit":"g", "Something":"else"}"""; + var expected = new Mass(4.2m, MassUnit.Gram); + + var options = new JsonSerializerOptions {PropertyNameCaseInsensitive = caseInsensitive}; + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedUnitConverter()); + options.Converters.Add(new JsonQuantityConverter(Mass.Info)); + + // Act + Mass result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Deserialize_WithAdditionalProperties_WhenUnmappedMemberHandlingIsDisallowed_ThrowsJsonException(bool caseInsensitive) + { + // Arrange + var invalidJson = """{"Value":4.2,"Unit":"g", "Something":"else"}"""; + var options = new JsonSerializerOptions { UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, PropertyNameCaseInsensitive = caseInsensitive }; + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedUnitConverter()); + options.Converters.Add(new JsonQuantityConverter(Mass.Info)); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(invalidJson, options)); + } + + [Fact] + public void Constructor_DefaultQuantityInfo_Success() + { + var converter = new JsonQuantityConverter(Length.Info); + Assert.NotNull(converter); + } + + [Fact] + public void Constructor_CustomQuantityInfo_Success() + { + QuantityInfo quantityInfo = Length.Info; + var converter = new JsonQuantityConverter(quantityInfo); + Assert.NotNull(converter); + } + + [Fact] + public void Read_InvalidJson_ThrowsJsonException() + { + var options = new JsonSerializerOptions { Converters = { new JsonQuantityConverter(Length.Info) } }; +#pragma warning disable JSON001 + Assert.Throws(() => JsonSerializer.Deserialize("InvalidJson", options)); +#pragma warning restore JSON001 + } +} diff --git a/UnitsNet.Serialization.SystemTextJson.Tests/QuantityConverterOptionsTest.cs b/UnitsNet.Serialization.SystemTextJson.Tests/QuantityConverterOptionsTest.cs new file mode 100644 index 0000000000..7343495988 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson.Tests/QuantityConverterOptionsTest.cs @@ -0,0 +1,158 @@ +// 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.Text.Json; +using System.Text.Json.Serialization; +using UnitsNet.Serialization.SystemTextJson.Unit; +using UnitsNet.Serialization.SystemTextJson.Value; +using UnitsNet.Units; + +namespace UnitsNet.Serialization.SystemTextJson.Tests; + +public class QuantityConverterOptionsTest +{ + [Fact] + public void Serializing_WithDecimalNotationConverterAndUnitTypeAndNameConverter_ReturnsExpectedMass() + { + // Arrange + var json = """{"Value":4.2,"Unit":"MassUnit.Gram"}"""; + var expected = new Mass(4.2m, MassUnit.Gram); + + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new UnitTypeAndNameConverter()); + options.Converters.Add(new JsonQuantityConverter()); + + // Act + var actualJson = JsonSerializer.Serialize(expected, options); + Mass result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(json, actualJson); + Assert.Equal(expected, result); + } + + [Fact] + public void Serializing_WithFractionalNotationConverterAndStringEnumConverter() + { + // Arrange + var json = """{"Value":{"N":42,"D":10},"Unit":"Gram"}"""; + var expected = new Mass(4.2m, MassUnit.Gram); + + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueFractionalNotationConverter(false)); + options.Converters.Add(new JsonStringEnumConverter()); + options.Converters.Add(new JsonQuantityConverter()); + + // Act + var actualJson = JsonSerializer.Serialize(expected, options); + Mass result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(json, actualJson); + Assert.Equal(expected, result); + } + + [Fact] + public void Serializing_OneKilogram_WithJsonQuantityConverter_IgnoringDefaultValues() + { + // Arrange + var json = """{"Value":{"N":1}}"""; + var expected = new Mass(QuantityValue.One, MassUnit.Kilogram); + var options = new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault }; + options.Converters.Add(QuantityValueFractionalNotationConverter.Default); + options.Converters.Add(new JsonQuantityConverter()); + + // Act + var actualJson = JsonSerializer.Serialize(expected, options); + Mass result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(json, actualJson); + Assert.Equal(expected, result); + } + + [Fact] + public void Serializing_ArrayOfMasses_WithJsonQuantityConverter_IgnoringDefaultValues() + { + // Arrange + var json = """[{"Value":{"N":42,"D":10},"Unit":6},{"Value":{"N":1}},{}]"""; + Mass[] masses = [new(4.2m, MassUnit.Gram), new(1, MassUnit.Kilogram), Mass.Zero]; + var options = new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault }; + options.Converters.Add(QuantityValueFractionalNotationConverter.Default); + options.Converters.Add(new JsonQuantityConverter()); + + // Act + var actualJson = JsonSerializer.Serialize(masses, options); + Mass[] result = JsonSerializer.Deserialize(json, options)!; + + // Assert + Assert.Equal(json, actualJson); + Assert.Equal(masses, result); + } + + + [Fact] + public void Serializing_WithFractionalNotationAndAbbreviation() + { + // Arrange + var json = """{"Value":{"N":42,"D":10},"Unit":"g"}"""; + var expected = new Mass(4.2m, MassUnit.Gram); + + var options = new JsonSerializerOptions(); + options.Converters.Add(QuantityValueFractionalNotationConverter.Default); + options.Converters.Add(new AbbreviatedUnitConverter()); + options.Converters.Add(new JsonQuantityConverter()); + + // Act + var actualJson = JsonSerializer.Serialize(expected, options); + Mass result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(json, actualJson); + Assert.Equal(expected, result); + } + + [Fact] + public void Serializing_ArrayOfMasses_WithJsonQuantityConverter() + { + // Arrange + var json = """[{"Value":{"N":42,"D":10},"Unit":6},{"Value":{"N":1,"D":1},"Unit":8},{"Value":{"N":0,"D":1},"Unit":8}]"""; + Mass[] masses = [new(4.2m, MassUnit.Gram), new(1, MassUnit.Kilogram), Mass.Zero]; + var options = new JsonSerializerOptions(); + options.Converters.Add(QuantityValueFractionalNotationConverter.Default); + options.Converters.Add(new JsonQuantityConverter()); + + // Act + var actualJson = JsonSerializer.Serialize(masses, options); + Mass[] result = JsonSerializer.Deserialize(json, options)!; + + // Assert + Assert.Equal(json, actualJson); + Assert.Equal(masses, result); + } + + [Fact] + public void Serializing_IQuantity_WithDecimalNotationAndAbbreviation() + { + // Arrange + var json = """{"Value":4.2,"Unit":"g","Type":"Mass"}"""; + var expected = new Mass(4.2m, MassUnit.Gram); + IQuantity interfaceQuantity = expected; + + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + options.Converters.Add(new AbbreviatedInterfaceQuantityWithAvailableValueConverter()); + options.Converters.Add(new JsonQuantityConverter()); // this one should not be called when serializing via the IQuantity interface + options.Converters.Add(new UnitTypeAndNameConverter()); // this one should not be called when serializing via the IQuantity interface + + // Act + var actualJson = JsonSerializer.Serialize(interfaceQuantity, options); + IQuantity? result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(json, actualJson); + Assert.Equal(expected, result); + Assert.NotEqual(json, JsonSerializer.Serialize(expected, options)); // this should serialize using the UnitTypeAndNameConverter + } +} diff --git a/UnitsNet.Serialization.SystemTextJson.Tests/Unit/AbbreviatedUnitConverterTests.cs b/UnitsNet.Serialization.SystemTextJson.Tests/Unit/AbbreviatedUnitConverterTests.cs new file mode 100644 index 0000000000..63ee027b2a --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson.Tests/Unit/AbbreviatedUnitConverterTests.cs @@ -0,0 +1,183 @@ +// 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.Globalization; +using System.Text.Json; +using JetBrains.Annotations; +using UnitsNet.Serialization.SystemTextJson.Unit; +using UnitsNet.Units; + +namespace UnitsNet.Serialization.SystemTextJson.Tests.Unit; + +[TestSubject(typeof(AbbreviatedUnitConverter))] +public class AbbreviatedUnitConverterTests +{ + private static JsonSerializerOptions CreateOptions() + { + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedUnitConverter()); + return options; + } + + [Fact] + public void Serialize_ReturnsExpectedAbbreviation() + { + // Arrange + const MassUnit unit = MassUnit.Gram; + const string expectedJson = """ + "g" + """; + JsonSerializerOptions options = CreateOptions(); + + // Act + var json = JsonSerializer.Serialize(unit, options); + + // Assert + Assert.Equal(expectedJson, json); + } + + [Fact] + public void Serialize_WithConverterForType_ReturnsExpectedAbbreviationForTheSpecifiedType() + { + // Arrange + const MassUnit unit = MassUnit.Gram; + const string expectedJson = """ + "g" + """; + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedUnitConverter()); + + // Act + var json = JsonSerializer.Serialize(unit, options); + + // Assert + Assert.Equal(expectedJson, json); + Assert.Equal("1", JsonSerializer.Serialize(VolumeUnit.AcreFoot, options)); + } + + [Fact] + public void Serialize_WithCustomAbbreviations_ReturnsExpectedAbbreviation() + { + // Arrange + const MassUnit unit = MassUnit.Gram; + const string expectedJson = """ + "g (custom)" + """; + var abbreviations = new UnitAbbreviationsCache([Mass.Info]); + abbreviations.MapUnitToDefaultAbbreviation(MassUnit.Gram, "g (custom)"); + + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedUnitConverter(new UnitParser(abbreviations))); + + // Act + var json = JsonSerializer.Serialize(unit, options); + + // Assert + Assert.Equal(expectedJson, json); + Assert.Equal("1", JsonSerializer.Serialize(VolumeUnit.AcreFoot, options)); + } + + [Fact] + public void Serialize_WithCustomCulture_ReturnsExpectedAbbreviation() + { + // Arrange + const MassUnit unit = MassUnit.Gram; + const string expectedJson = """ + "\u0433" + """; // "г" + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedUnitConverter(UnitParser.Default, CultureInfo.GetCultureInfo("ru-RU"))); + + // Act + var json = JsonSerializer.Serialize(unit, options); + + // Assert + Assert.Equal(expectedJson, json); + } + + [Fact] + public void Serialize_AsDictionaryKey_ReturnsTheExpectedResult() + { + // Arrange + var dictionary = new Dictionary + { + {MassUnit.Gram, "grams"}, + {MassUnit.Kilogram, "kilograms"} + }; + const string expectedJson = """{"g":"grams","kg":"kilograms"}"""; + JsonSerializerOptions options = CreateOptions(); + + // Act + var json = JsonSerializer.Serialize(dictionary, options); + + // Assert + Assert.Equal(expectedJson, json); + } + + [Fact] + public void Deserialize_ReturnsExpectedMassUnit() + { + // Arrange + const string json = """ + "g" + """; + const MassUnit expected = MassUnit.Gram; + JsonSerializerOptions options = CreateOptions(); + + // Act + MassUnit result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_WithCustomCulture_ReturnsExpectedMassUnit() + { + // Arrange + var json = """ + "\u0433" + """; // "г" + MassUnit expected = MassUnit.Gram; + var options = new JsonSerializerOptions(); + options.Converters.Add(new AbbreviatedUnitConverter(UnitParser.Default, CultureInfo.GetCultureInfo("ru-RU"))); + + // Act + MassUnit result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_AsDictionaryKey_ReturnsTheExpectedResult() + { + // Arrange + const string json = """{"g":"grams","kg":"kilograms"}"""; + var expectedDictionary = new Dictionary + { + {MassUnit.Gram, "grams"}, + {MassUnit.Kilogram, "kilograms"} + }; + JsonSerializerOptions options = CreateOptions(); + + // Act + Dictionary? dictionary = JsonSerializer.Deserialize>(json, options); + + // Assert + Assert.Equal(expectedDictionary, dictionary); + } + + [Fact] + public void Deserialize_WithInvalidAbbreviation_ThrowsUnitNotFoundException() + { + // Arrange + const string json = """ + "invalid" + """; + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson.Tests/Unit/UnitTypeAndNameConverterTests.cs b/UnitsNet.Serialization.SystemTextJson.Tests/Unit/UnitTypeAndNameConverterTests.cs new file mode 100644 index 0000000000..b4cc98b80e --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson.Tests/Unit/UnitTypeAndNameConverterTests.cs @@ -0,0 +1,266 @@ +// 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.Text.Json; +using JetBrains.Annotations; +using UnitsNet.Serialization.SystemTextJson.Unit; +using UnitsNet.Units; + +namespace UnitsNet.Serialization.SystemTextJson.Tests.Unit; + +[TestSubject(typeof(UnitTypeAndNameConverter<>))] +public class UnitTypeAndNameConverterTests +{ + private static JsonSerializerOptions CreateOptions() + { + var options = new JsonSerializerOptions(); + options.Converters.Add(new UnitTypeAndNameConverter()); + return options; + } + + [Fact] + public void Serialize_ReturnsExpectedTypeAndEnumName() + { + // Arrange + const MassUnit unit = MassUnit.Gram; + const string expectedJson = """ + "MassUnit.Gram" + """; + JsonSerializerOptions options = CreateOptions(); + + // Act + var json = JsonSerializer.Serialize(unit, options); + + // Assert + Assert.Equal(expectedJson, json); + } + + [Fact] + public void Serialize_WithConverterForType_ReturnsExpectedTypeAndEnumNameForTheSpecifiedType() + { + // Arrange + const MassUnit unit = MassUnit.Gram; + const string expectedJson = """ + "MassUnit.Gram" + """; + var options = new JsonSerializerOptions(); + options.Converters.Add(new UnitTypeAndNameConverter(Mass.Info)); + + // Act + var json = JsonSerializer.Serialize(unit, options); + + // Assert + Assert.Equal(expectedJson, json); + Assert.Equal("1", JsonSerializer.Serialize(VolumeUnit.AcreFoot, options)); + } + + [Fact] + public void Serialize_WithCustomQuantities_ReturnsExpectedTypeAndEnumName() + { + // Arrange + const MassUnit unit = MassUnit.Gram; + const string expectedJson = """ + "MassUnit.Gram" + """; + var options = new JsonSerializerOptions(); + options.Converters.Add(new UnitTypeAndNameConverter(new QuantityInfoLookup([Mass.Info]))); + + // Act + var json = JsonSerializer.Serialize(unit, options); + + // Assert + Assert.Equal(expectedJson, json); + Assert.Equal("1", JsonSerializer.Serialize(VolumeUnit.AcreFoot, options)); + } + + [Fact] + public void Serialize_WithCustomMassUnit_ReturnsExpectedTypeAndEnumName() + { + // Arrange + const MassUnit unit = (MassUnit)(-1); + var customMassInfo = Mass.MassInfo.CreateDefault(units => units.Append(new UnitDefinition(unit, "Custom", "Customs", BaseUnits.Undefined))); + const string expectedJson = """ + "MassUnit.Custom" + """; + var options = new JsonSerializerOptions(); + options.Converters.Add(new UnitTypeAndNameConverter(new QuantityInfoLookup([customMassInfo]))); + + // Act + var json = JsonSerializer.Serialize(unit, options); + + // Assert + Assert.Equal(expectedJson, json); + } + + [Fact] + public void Serialize_AsDictionaryKey_ReturnsTheExpectedResult() + { + // Arrange + var dictionary = new Dictionary + { + {MassUnit.Gram, "grams"}, + {MassUnit.Kilogram, "kilograms"} + }; + const string expectedJson = """{"MassUnit.Gram":"grams","MassUnit.Kilogram":"kilograms"}"""; + JsonSerializerOptions options = CreateOptions(); + + // Act + var json = JsonSerializer.Serialize(dictionary, options); + + // Assert + Assert.Equal(expectedJson, json); + } + + [Fact] + public void Deserialize_ReturnsExpectedMassUnit() + { + // Arrange + const string json = """ + "MassUnit.Gram" + """; + const MassUnit expected = MassUnit.Gram; + JsonSerializerOptions options = CreateOptions(); + + // Act + MassUnit result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_WithLowercaseUnit_ThrowsUnitNotFoundException() + { + // Arrange + const string json = """ + "MassUnit.gram" + """; + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserialize_WithLowercaseUnit_AndCaseInsensitiveMatching_ReturnsTheExpectedResult() + { + // Arrange + const string json = """ + "MassUnit.gram" + """; + const MassUnit expected = MassUnit.Gram; + var options = new JsonSerializerOptions(); + options.Converters.Add(new UnitTypeAndNameConverter(true)); + + // Act + MassUnit result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_WithCustomUnit_ReturnsTheExpectedResult() + { + // Arrange + const string json = """ + "MassUnit.Custom" + """; + const MassUnit expected = (MassUnit)(-1); + var customMassInfo = Mass.MassInfo.CreateDefault(units => units.Append(new UnitDefinition(expected, "Custom", "Customs", BaseUnits.Undefined))); + var options = new JsonSerializerOptions(); + options.Converters.Add(new UnitTypeAndNameConverter(new QuantityInfoLookup([customMassInfo]))); + + // Act + MassUnit result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_AsDictionaryKey_ReturnsTheExpectedResult() + { + // Arrange + const string json = """{"MassUnit.Gram":"grams","MassUnit.Kilogram":"kilograms"}"""; + var expectedDictionary = new Dictionary + { + {MassUnit.Gram, "grams"}, + {MassUnit.Kilogram, "kilograms"} + }; + + JsonSerializerOptions options = CreateOptions(); + + // Act + Dictionary? dictionary = JsonSerializer.Deserialize>(json, options); + + // Assert + Assert.Equal(expectedDictionary, dictionary); + } + + [Fact] + public void Deserialize_WithUnitValue_ThrowsUnitNotFoundException() + { + // Arrange + const string json = """ + "MassUnit.1" + """; + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserialize_WithEmptyString_ThrowsJsonException() + { + // Arrange + const string json = """ + "" + """; + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserialize_WithInvalidStringFormat_ThrowsJsonException() + { + // Arrange + const string json = """ + "Gram" + """; + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserialize_WithInvalidUnitName_ThrowsUnitNotFoundException() + { + // Arrange + const string json = """ + "MassUnit.Invalid" + """; + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserialize_WithInvalidUnitName_WhenUsingCaseInsensitiveMatching_ThrowsUnitNotFoundException() + { + // Arrange + const string json = """ + "MassUnit.Invalid" + """; + var options = new JsonSerializerOptions(); + options.Converters.Add(new UnitTypeAndNameConverter(true)); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson.Tests/UnitsNet.Serialization.SystemTextJson.Tests.csproj b/UnitsNet.Serialization.SystemTextJson.Tests/UnitsNet.Serialization.SystemTextJson.Tests.csproj new file mode 100644 index 0000000000..089fe53fc7 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson.Tests/UnitsNet.Serialization.SystemTextJson.Tests.csproj @@ -0,0 +1,31 @@ + + + + net48;net8.0;net9.0 + enable + enable + latest + + false + true + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + diff --git a/UnitsNet.Serialization.SystemTextJson.Tests/Value/BigIntegerConverterTests.cs b/UnitsNet.Serialization.SystemTextJson.Tests/Value/BigIntegerConverterTests.cs new file mode 100644 index 0000000000..066624e6c9 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson.Tests/Value/BigIntegerConverterTests.cs @@ -0,0 +1,215 @@ +using System.Globalization; +using System.Numerics; +using System.Text.Json; +using System.Text.Json.Serialization; +using JetBrains.Annotations; +using UnitsNet.Serialization.SystemTextJson.Value; + +namespace UnitsNet.Serialization.SystemTextJson.Tests.Value; + +[TestSubject(typeof(BigIntegerConverter))] +public class BigIntegerConverterTests +{ + private static JsonSerializerOptions CreateOptions() + { + var options = new JsonSerializerOptions(); + options.Converters.Add(new BigIntegerConverter()); + return options; + } + + [Fact] + public void Serializing_ReturnsBigIntegerAsNumber() + { + // Arrange: A JSON string without any escape sequences. + const string json = "123456789012345678901234567890"; + var value = BigInteger.Parse("123456789012345678901234567890", CultureInfo.InvariantCulture); + JsonSerializerOptions options = CreateOptions(); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serializing_VeryLargeNumbers_ReturnsTheExpectedResult() + { + // Arrange: A JSON string representing the string '10...' with 520 zeros + var json = new string(Enumerable.Repeat('0', 520).Prepend('1').ToArray()); + var value = BigInteger.Pow(10, 520); + JsonSerializerOptions options = CreateOptions(); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serializing_AsString_ReturnsBigIntegerAsNumber() + { + // Arrange: A JSON string without any escape sequences. + const string json = """ + "123456789012345678901234567890" + """; + var value = BigInteger.Parse("123456789012345678901234567890", CultureInfo.InvariantCulture); + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.WriteAsString; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serializing_VeryLargeNumbers_AsString_ReturnsTheExpectedResult() + { + // Arrange: A JSON string representing the string "10..." with 520 zeros + var json = new string(Enumerable.Repeat('0', 520).Prepend('1').Prepend('"').Append('"').ToArray()); + var value = BigInteger.Pow(10, 520); + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.WriteAsString; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Deserializing_NumberString_ReturnsExpectedBigInteger() + { + // Arrange: A JSON string without any escape sequences. + const string json = "123456789012345678901234567890"; + var expected = BigInteger.Parse("123456789012345678901234567890", CultureInfo.InvariantCulture); + + // Act + BigInteger result = JsonSerializer.Deserialize(json, CreateOptions()); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserializing_QuotedNumber_WithDefaultNumberHandling_ThrowsJsonException() + { + // Arrange: A JSON string without any escape sequences. + const string json = """ + "123456789012345678901234567890" + """; + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_QuotedNumber_WithAllowReadingFromString_ReturnsExpectedBigInteger() + { + // Arrange: A JSON string without any escape sequences. + const string json = """ + "123456789012345678901234567890" + """; + var expected = BigInteger.Parse("123456789012345678901234567890", CultureInfo.InvariantCulture); + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowReadingFromString; + + // Act + BigInteger result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserializing_VeryLongNumbers_ReturnsTheExpectedResult() + { + // Arrange: A very long number string ('10...' with 520 zeros) + var json = new string(Enumerable.Repeat('0', 520).Prepend('1').ToArray()); + var expected = BigInteger.Pow(10, 520); + JsonSerializerOptions options = CreateOptions(); + + // Act + BigInteger result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_EscapedString_WithAllowReadingFromString_ReturnsExpectedBigInteger() + { + // Arrange: A JSON string with Unicode escape sequences. + // The JSON literal "12345\u0034\u0035" should be interpreted as "1234545". + var json = """ + "12345\u0034\u0035" + """; + var expected = BigInteger.Parse("1234545", CultureInfo.InvariantCulture); + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowReadingFromString; + + // Act + BigInteger result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserializing_InvalidNumberString_ThrowsFormatException() + { + // Arrange: A JSON string without any escape sequences. +#pragma warning disable JSON001 + const string json = """ + "12345678901234567890123456789invalid0" + """; +#pragma warning restore JSON001 + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowReadingFromString; + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_EmptyString_ThrowsJsonException() + { + // Arrange: A JSON string without any escape sequences. + const string json = """ + "" + """; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowReadingFromString; + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_EmptyObjectString_ThrowsJsonException() + { + // Arrange: A JSON string without any escape sequences. + const string json = "{}"; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowReadingFromString; + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_NullObject_ThrowsJsonException() + { + // Arrange: A JSON string without any escape sequences. + const string json = "null"; + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson.Tests/Value/QuantityValueDecimalConverterTests.cs b/UnitsNet.Serialization.SystemTextJson.Tests/Value/QuantityValueDecimalConverterTests.cs new file mode 100644 index 0000000000..a81f7a1fb2 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson.Tests/Value/QuantityValueDecimalConverterTests.cs @@ -0,0 +1,248 @@ +// 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.Text.Json; +using System.Text.Json.Serialization; +using JetBrains.Annotations; +using UnitsNet.Serialization.SystemTextJson.Value; + +namespace UnitsNet.Serialization.SystemTextJson.Tests.Value; + +[TestSubject(typeof(QuantityValueDecimalConverter))] +public class QuantityValueDecimalConverterTests +{ + private static JsonSerializerOptions CreateOptions() + { + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalConverter()); + return options; + } + + [Fact] + public void Serialize_ReturnsTheValueInDecimalNotation() + { + // Arrange + var json = "4.2"; + QuantityValue value = 4.2m; + JsonSerializerOptions options = CreateOptions(); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_WithJsonNumberHandling_WriteAsString_ReturnsTheValueInDecimalNotation() + { + // Arrange + var json = "\"4.2\""; + QuantityValue value = 4.2m; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.WriteAsString; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_WithDefaultSettings_ReturnsTheValueFormattedAsG29() + { + // Arrange + var json = "0.3333333333333333333333333333"; + var value = QuantityValue.FromTerms(1, 3); + JsonSerializerOptions options = CreateOptions(); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_WithNumbersBeyondTheDecimalRange_ThrowsOverflowException() + { + // Arrange + var value = QuantityValue.FromPowerOfTen(1, 40); + JsonSerializerOptions options = CreateOptions(); + + Assert.Throws(() => JsonSerializer.Serialize(value, options)); + } + + [Fact] + public void Serializing_NaN_or_Infinity_WithStrictNumberHandling_ThrowsJsonException() + { + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.Strict; + + // Assert + Assert.Throws(() => JsonSerializer.Serialize(QuantityValue.NaN, options)); + Assert.Throws(() => JsonSerializer.Serialize(QuantityValue.PositiveInfinity, options)); + Assert.Throws(() => JsonSerializer.Serialize(QuantityValue.NegativeInfinity, options)); + } + + [Fact] + public void Serializing_NaN_WithAllowNamedFloatingPointLiterals_ReturnsTheExpectedResult() + { + // Arrange + var expectedJson = "\"NaN\""; + var value = QuantityValue.NaN; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Serializing_PositiveInfinity_WithAllowNamedFloatingPointLiterals_ReturnsTheExpectedResult() + { + // Arrange + var expectedJson = "\"Infinity\""; + var value = QuantityValue.PositiveInfinity; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Deserialize_ValidNumberString_ReturnsTheExpectedValue() + { + // Arrange + var json = "4.2"; + QuantityValue expected = 4.2m; + JsonSerializerOptions options = CreateOptions(); + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_NumberStringInScientificNotation_ReturnsTheExpectedValue() + { + // Arrange + var json = "3.3333333E-06"; + QuantityValue expected = 3.3333333E-06; // ~ 1/300_000 + JsonSerializerOptions options = CreateOptions(); + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_QuotedNumber_With_AllowReadingFromString_ReturnsTheExpectedValue() + { + // Arrange + var json = "\"4.2\""; + QuantityValue expected = 4.2m; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_PositiveInfinity_With_AllowNamedFloatingPointLiterals_ReturnsTheExpectedValue() + { + // Arrange + var json = "\"Infinity\""; + QuantityValue expected = QuantityValue.PositiveInfinity; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_NegativeInfinity_With_AllowNamedFloatingPointLiterals_ReturnsTheExpectedValue() + { + // Arrange + var json = "\"-Infinity\""; + QuantityValue expected = QuantityValue.NegativeInfinity; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_NaN_With_AllowNamedFloatingPointLiterals_ReturnsTheExpectedValue() + { + // Arrange + var json = "\"NaN\""; + QuantityValue expected = QuantityValue.NaN; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserializing_NaN_Without_AllowNamedFloatingPointLiterals_FormatException() + { + // Arrange + var json = "\"NaN\""; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowReadingFromString; + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_WithInvalidString_ThrowsFormatException() + { + // Arrange + var json = "\"123invalid456\""; + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_WithEmptyObjectString_ThrowsJsonException() + { + // Arrange + var json = "{}"; + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson.Tests/Value/QuantityValueDecimalNotationConverterTests.cs b/UnitsNet.Serialization.SystemTextJson.Tests/Value/QuantityValueDecimalNotationConverterTests.cs new file mode 100644 index 0000000000..9aab9b92c6 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson.Tests/Value/QuantityValueDecimalNotationConverterTests.cs @@ -0,0 +1,275 @@ +// 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.Text.Json; +using System.Text.Json.Serialization; +using JetBrains.Annotations; +using UnitsNet.Serialization.SystemTextJson.Value; + +namespace UnitsNet.Serialization.SystemTextJson.Tests.Value; + +[TestSubject(typeof(QuantityValueDecimalNotationConverter))] +public class QuantityValueDecimalNotationConverterTests +{ + private static JsonSerializerOptions CreateOptions() + { + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalNotationConverter()); + return options; + } + + [Fact] + public void Creating_WithNegativePrecision_ThrowsArgumentOutOfRangeException() + { + Assert.Throws(() => new QuantityValueDecimalNotationConverter(-1)); + } + + [Fact] + public void Serialize_ReturnsTheValueInDecimalNotation() + { + // Arrange + var json = "4.2"; + QuantityValue value = 4.2m; + JsonSerializerOptions options = CreateOptions(); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_WithJsonNumberHandling_WriteAsString_ReturnsTheValueInDecimalNotation() + { + // Arrange + var json = "\"4.2\""; + QuantityValue value = 4.2m; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.WriteAsString; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_WithDefaultSettings_ReturnsTheValueFormattedAsG17() + { + // Arrange + var json = "0.33333333333333333"; + var value = QuantityValue.FromTerms(1, 3); + JsonSerializerOptions options = CreateOptions(); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_WithMaxNumberOfSignificantDigits_ReturnsTheValueWithTheSpecifiedPrecision() + { + // Arrange + var json = "3.3333333E-06"; + var value = QuantityValue.FromTerms(1, 300_000); + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalNotationConverter(8)); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_WithExtremeNumberOfSignificantDigits_ReturnsTheExpectedResult() + { + // Arrange + var json = "0." + new string(Enumerable.Repeat('3', 260).ToArray()); + var value = QuantityValue.FromTerms(1, 3); + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDecimalNotationConverter(260)); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serializing_NaN_or_Infinity_WithStrictNumberHandling_ThrowsJsonException() + { + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.Strict; + + // Assert + Assert.Throws(() => JsonSerializer.Serialize(QuantityValue.NaN, options)); + Assert.Throws(() => JsonSerializer.Serialize(QuantityValue.PositiveInfinity, options)); + Assert.Throws(() => JsonSerializer.Serialize(QuantityValue.NegativeInfinity, options)); + } + + [Fact] + public void Serializing_NaN_WithAllowNamedFloatingPointLiterals_ReturnsTheExpectedResult() + { + // Arrange + var expectedJson = "\"NaN\""; + var value = QuantityValue.NaN; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Serializing_PositiveInfinity_WithAllowNamedFloatingPointLiterals_ReturnsTheExpectedResult() + { + // Arrange + var expectedJson = "\"Infinity\""; + var value = QuantityValue.PositiveInfinity; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Deserialize_ValidNumberString_ReturnsTheExpectedValue() + { + // Arrange + var json = "4.2"; + QuantityValue expected = 4.2m; + JsonSerializerOptions options = CreateOptions(); + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_NumberStringInScientificNotation_ReturnsTheExpectedValue() + { + // Arrange + var json = "3.3333333E-06"; + QuantityValue expected = 3.3333333E-06; // ~ 1/300_000 + JsonSerializerOptions options = CreateOptions(); + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_QuotedNumber_With_AllowReadingFromString_ReturnsTheExpectedValue() + { + // Arrange + var json = "\"4.2\""; + QuantityValue expected = 4.2m; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_PositiveInfinity_With_AllowNamedFloatingPointLiterals_ReturnsTheExpectedValue() + { + // Arrange + var json = "\"Infinity\""; + QuantityValue expected = QuantityValue.PositiveInfinity; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_NegativeInfinity_With_AllowNamedFloatingPointLiterals_ReturnsTheExpectedValue() + { + // Arrange + var json = "\"-Infinity\""; + QuantityValue expected = QuantityValue.NegativeInfinity; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_NaN_With_AllowNamedFloatingPointLiterals_ReturnsTheExpectedValue() + { + // Arrange + var json = "\"NaN\""; + QuantityValue expected = QuantityValue.NaN; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserializing_NaN_Without_AllowNamedFloatingPointLiterals_ThrowsJsonException() + { + // Arrange + var json = "\"NaN\""; + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_WithInvalidString_ThrowsJsonException() + { + // Arrange + var json = "\"123invalid456\""; + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_WithEmptyObjectString_ThrowsJsonException() + { + // Arrange + var json = "{}"; + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson.Tests/Value/QuantityValueDoubleConverterTests.cs b/UnitsNet.Serialization.SystemTextJson.Tests/Value/QuantityValueDoubleConverterTests.cs new file mode 100644 index 0000000000..d22a3a025a --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson.Tests/Value/QuantityValueDoubleConverterTests.cs @@ -0,0 +1,259 @@ +// 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.Text.Json; +using System.Text.Json.Serialization; +using JetBrains.Annotations; +using UnitsNet.Serialization.SystemTextJson.Value; + +namespace UnitsNet.Serialization.SystemTextJson.Tests.Value; + +[TestSubject(typeof(QuantityValueDoubleConverter))] +public class QuantityValueDoubleConverterTests +{ + private static JsonSerializerOptions CreateOptions() + { + var options = new JsonSerializerOptions(); + options.Converters.Add(new QuantityValueDoubleConverter()); + return options; + } + + [Fact] + public void Constructor_GivenAnInvalidNumberOfSignificantDigits_ThrowsArgumentException() + { + Assert.Throws(() => new QuantityValueDoubleConverter(0)); + Assert.Throws(() => new QuantityValueDoubleConverter(18)); + } + + [Fact] + public void Serialize_ReturnsTheValueInDecimalNotation() + { + // Arrange + #if NET + var json = "4.2"; + #else + var json = "4.2000000000000002"; + #endif + QuantityValue value = 4.2m; + JsonSerializerOptions options = CreateOptions(); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + Assert.Equal(json, JsonSerializer.Serialize(4.2, options)); // same as serializing the double + } + + [Fact] + public void Serialize_WithJsonNumberHandling_WriteAsString_ReturnsTheValueInDecimalNotation() + { + // Arrange + var json = "\"4.2\""; + QuantityValue value = 4.2m; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.WriteAsString; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); +#if NET + Assert.Equal(json, JsonSerializer.Serialize(4.2, options)); // same as serializing the double + #else + Assert.Equal("\"4.2000000000000002\"", JsonSerializer.Serialize(4.2, options)); // not sure why this is different... +#endif + } + + [Fact] + public void Serialize_WithDefaultSettings_ReturnsTheValueFormattedAsG17() + { + // Arrange +#if NET + var json = "0.3333333333333333"; +#else + var json = "0.33333333333333331"; +#endif + var value = QuantityValue.FromTerms(1, 3); + JsonSerializerOptions options = CreateOptions(); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + Assert.Equal(json, JsonSerializer.Serialize(1 / 3.0, options)); // same as serializing the double + } + + [Fact] + public void Serializing_NaN_or_Infinity_WithStrictNumberHandling_ThrowsJsonException() + { + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.Strict; + + // Assert + Assert.Throws(() => JsonSerializer.Serialize(QuantityValue.NaN, options)); + Assert.Throws(() => JsonSerializer.Serialize(QuantityValue.PositiveInfinity, options)); + Assert.Throws(() => JsonSerializer.Serialize(QuantityValue.NegativeInfinity, options)); + } + + [Fact] + public void Serializing_NaN_WithAllowNamedFloatingPointLiterals_ReturnsTheExpectedResult() + { + // Arrange + var expectedJson = "\"NaN\""; + var value = QuantityValue.NaN; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Serializing_PositiveInfinity_WithAllowNamedFloatingPointLiterals_ReturnsTheExpectedResult() + { + // Arrange + var expectedJson = "\"Infinity\""; + var value = QuantityValue.PositiveInfinity; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Deserialize_ValidNumberString_ReturnsTheExpectedValue() + { + // Arrange + var json = "4.2"; + QuantityValue expected = 4.2m; + JsonSerializerOptions options = CreateOptions(); + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_NumberStringInScientificNotation_ReturnsTheExpectedValue() + { + // Arrange + var json = "3.3333333E-06"; + QuantityValue expected = 3.3333333E-06; // ~ 1/300_000 + JsonSerializerOptions options = CreateOptions(); + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_QuotedNumber_With_AllowReadingFromString_ReturnsTheExpectedValue() + { + // Arrange + var json = "\"4.2\""; + QuantityValue expected = 4.2m; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_PositiveInfinity_With_AllowNamedFloatingPointLiterals_ReturnsTheExpectedValue() + { + // Arrange + var json = "\"Infinity\""; + QuantityValue expected = QuantityValue.PositiveInfinity; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_NegativeInfinity_With_AllowNamedFloatingPointLiterals_ReturnsTheExpectedValue() + { + // Arrange + var json = "\"-Infinity\""; + QuantityValue expected = QuantityValue.NegativeInfinity; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_NaN_With_AllowNamedFloatingPointLiterals_ReturnsTheExpectedValue() + { + // Arrange + var json = "\"NaN\""; + QuantityValue expected = QuantityValue.NaN; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserializing_NaN_Without_AllowNamedFloatingPointLiterals_ThrowsJsonException() + { + // Arrange + var json = "\"NaN\""; + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_WithInvalidString_ThrowsJsonException() + { + // Arrange + var json = "\"123invalid456\""; + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_WithEmptyObjectString_ThrowsJsonException() + { + // Arrange + var json = "{}"; + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson.Tests/Value/QuantityValueFractionalNotationConverterTests.cs b/UnitsNet.Serialization.SystemTextJson.Tests/Value/QuantityValueFractionalNotationConverterTests.cs new file mode 100644 index 0000000000..7df7ce7b32 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson.Tests/Value/QuantityValueFractionalNotationConverterTests.cs @@ -0,0 +1,370 @@ +// 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.Text.Json; +using System.Text.Json.Serialization; +using JetBrains.Annotations; +using UnitsNet.Serialization.SystemTextJson.Value; + +namespace UnitsNet.Serialization.SystemTextJson.Tests.Value; + +[TestSubject(typeof(QuantityValueFractionalNotationConverter))] +public class QuantityValueFractionalNotationConverterTests +{ + private static JsonSerializerOptions CreateDefaultOptions() + { + var options = new JsonSerializerOptions(); + options.Converters.Add(QuantityValueFractionalNotationConverter.Default); + return options; + } + + [Fact] + public void Creating_WithNullBigIntegerConverter_ThrowsArgumentOutOfRangeException() + { + Assert.Throws(() => new QuantityValueFractionalNotationConverter(null!)); + } + + [Fact] + public void Serialize_ReturnsTheExpectedResult() + { + // Arrange + const string json = """{"N":42,"D":10}"""; + QuantityValue value = 4.2m; + JsonSerializerOptions options = CreateDefaultOptions(); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_WithReduction_ReturnsTheExpectedResult() + { + // Arrange + const string json = """{"N":21,"D":5}"""; + QuantityValue value = 4.2m; + var options = new JsonSerializerOptions(); + options.Converters.Add(QuantityValueFractionalNotationConverter.Reducing); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_WithLowerCaseProperties_ReturnsTheExpectedResult() + { + // Arrange + const string json = """{"n":42,"d":10}"""; + QuantityValue value = 4.2m; + JsonSerializerOptions options = CreateDefaultOptions(); + options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_Zero_WithDefaultSettings_ReturnsBothTerms() + { + // Arrange + const string json = """{"N":0,"D":1}"""; + var value = QuantityValue.Zero; + JsonSerializerOptions options = CreateDefaultOptions(); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_Zero_IgnoringDefaultValues_ReturnsAnEmptyObject() + { + // Arrange + var json = "{}"; + var value = QuantityValue.Zero; + JsonSerializerOptions options = CreateDefaultOptions(); + options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_IntegerNumber_WithIgnoreCondition_WhenWritingDefault_ReturnsTheNumerator() + { + // Arrange + const string json = """{"N":5}"""; + QuantityValue value = 5; + JsonSerializerOptions options = CreateDefaultOptions(); + options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_DecimalNumber_WithIgnoreCondition_WhenWritingDefault_ReturnsBothTerms() + { + // Arrange + const string json = """{"N":42,"D":10}"""; + QuantityValue value = 4.2m; + JsonSerializerOptions options = CreateDefaultOptions(); + options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Deserialize_ValidJson_ReturnsTheExpectedValue() + { + // Arrange + const string json = """{"N":42,"D":10}"""; + QuantityValue expected = 4.2m; + JsonSerializerOptions options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_ValidJson_WithLowercasePolicy_ReturnsTheExpectedValue() + { + // Arrange + const string json = """{"n":42,"d":10}"""; + QuantityValue expected = 4.2m; + JsonSerializerOptions options = CreateDefaultOptions(); + options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_ValidJson_WithCaseInsensitiveMatching_ReturnsTheExpectedValue() + { + // Arrange + const string json = """{"N":42,"d":10}"""; + QuantityValue expected = 4.2m; + JsonSerializerOptions options = CreateDefaultOptions(); + options.PropertyNameCaseInsensitive = true; + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_ValidJson_WithAdditionalProperties_WithCaseInsensitiveMatching_ReturnsTheExpectedValue() + { + // Arrange + const string json = """{"N":42,"something":2,"d":10}"""; + QuantityValue expected = 4.2m; + JsonSerializerOptions options = CreateDefaultOptions(); + options.PropertyNameCaseInsensitive = true; + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_JsonWithQuotedTerms_WithDefaultNumberHandling_ThrowsJsonException() + { + // Arrange + const string json = """{"N":"42","D":"10"}"""; + JsonSerializerOptions options = CreateDefaultOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserialize_ValidJsonWithQuotedTerms_WithAllowReadingFromString_ReturnsTheExpectedValue() + { + // Arrange + const string json = """{"N":"42","D":"10"}"""; + QuantityValue expected = 4.2m; + JsonSerializerOptions options = CreateDefaultOptions(); + options.NumberHandling = JsonNumberHandling.AllowReadingFromString; + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_WithoutDenominator_ReturnsTheExpectedIntegerValue() + { + // Arrange + const string json = """{"N":42}"""; + QuantityValue expected = 42; + JsonSerializerOptions options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_WithoutNumeratorAndDenominator_ReturnsZero() + { + // Arrange + var json = "{}"; + QuantityValue expected = QuantityValue.Zero; + JsonSerializerOptions options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_WithoutNumeratorAndNonZeroDenominator_ReturnsZero() + { + // Arrange + const string json = """{"D":1}"""; + QuantityValue expected = QuantityValue.Zero; + JsonSerializerOptions options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_WithoutNumeratorAndZeroDenominator_ReturnsNaN() + { + // Arrange + const string json = """{"D":0}"""; + QuantityValue expected = QuantityValue.NaN; + JsonSerializerOptions options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_WithoutPositiveNumeratorAndZeroDenominator_ReturnsPositiveInfinity() + { + // Arrange + const string json = """{"N":1,"D":0}"""; + QuantityValue expected = QuantityValue.PositiveInfinity; + JsonSerializerOptions options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_WithNegativeNumeratorAndZeroDenominator_ReturnsNegativeInfinity() + { + // Arrange + const string json = """{"N":-1,"D":0}"""; + QuantityValue expected = QuantityValue.NegativeInfinity; + JsonSerializerOptions options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_WithAdditionalProperties_ReturnsTheExpectedResult() + { + // Arrange + const string json = """{"N":42,"D":10,"C":1}"""; + QuantityValue expected = 4.2m; + JsonSerializerOptions options = CreateDefaultOptions(); + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public void Deserialize_WithAdditionalProperties_WhenUnmappedMemberHandlingIsDisallowed_ThrowsJsonException(bool caseInsensitive) + { + // Arrange + const string invalidJson = """{"N":42,"D":10,"C":1}"""; + JsonSerializerOptions options = CreateDefaultOptions(); + options.PropertyNameCaseInsensitive = caseInsensitive; + options.UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow; + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(invalidJson, options)); + } + + [Fact] + public void Deserializing_WithInvalidString_ThrowsFormatException() + { + // Arrange + const string invalidJson = """{"N":"4invalid2","D":"10"}"""; + JsonSerializerOptions options = CreateDefaultOptions(); + options.NumberHandling = JsonNumberHandling.AllowReadingFromString; + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(invalidJson, options)); + } + + [Theory] + [InlineData("43")] + [InlineData("""{"N":4""")] + public void Deserializing_WithInvalidJsonString_ThrowsJsonException(string invalidJson) + { + // Arrange + JsonSerializerOptions options = CreateDefaultOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(invalidJson, options)); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson.Tests/Value/QuantityValueMixedNotationConverterTests.cs b/UnitsNet.Serialization.SystemTextJson.Tests/Value/QuantityValueMixedNotationConverterTests.cs new file mode 100644 index 0000000000..7ed05ab964 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson.Tests/Value/QuantityValueMixedNotationConverterTests.cs @@ -0,0 +1,398 @@ +// 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.Numerics; +using System.Text.Json; +using System.Text.Json.Serialization; +using JetBrains.Annotations; +using UnitsNet.Serialization.SystemTextJson.Value; + +namespace UnitsNet.Serialization.SystemTextJson.Tests.Value; + +[TestSubject(typeof(QuantityValueMixedNotationConverter))] +public class QuantityValueMixedNotationConverterTests +{ + private static JsonSerializerOptions CreateOptions() + { + var options = new JsonSerializerOptions(); + options.Converters.Add(QuantityValueMixedNotationConverter.Default); + return options; + } + + [Fact] + public void Serialize_WholeNumber_ReturnsTheExpectedValue() + { + // Arrange + const string json = "42"; + QuantityValue value = 42; + JsonSerializerOptions options = CreateOptions(); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_WholeNumber_WithoutReduction_ReturnsTheExpectedValue() + { + // Arrange + const string json = "42"; + var value = QuantityValue.FromTerms(420, 10); + JsonSerializerOptions options = CreateOptions(); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_WholeNumber_AsString_ReturnsTheExpectedValue() + { + // Arrange + const string json = """ + "42" + """; + QuantityValue value = 42; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.WriteAsString; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_VeryLargeWholeNumber_ReturnsTheExpectedResult() + { + // Arrange: 1e260 (written with all its zeros) + var json = new string(Enumerable.Repeat('0', 512).Prepend('1').ToArray()); + QuantityValue value = BigInteger.Pow(10, 512); + JsonSerializerOptions options = CreateOptions(); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_TerminatingDecimal_ReturnsTheValueInDecimalNotation() + { + // Arrange + const string json = "4.25"; + QuantityValue value = 4.25m; + JsonSerializerOptions options = CreateOptions(); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_TerminatingDecimal_AsString_ReturnsTheExpectedValue() + { + // Arrange + const string json = """ + "42.5" + """; + QuantityValue value = 42.5m; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.WriteAsString; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_NonTerminatingDecimal_ReturnsTheValueFraction() + { + // Arrange + const string json = """ + "1/3" + """; + var value = QuantityValue.FromTerms(1, 3); + JsonSerializerOptions options = CreateOptions(); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Theory] + [InlineData(510)] + [InlineData(511)] + public void Serialize_VeryLargeDecimalNumber_ReturnsTheExpectedResult(int nbZeros) + { + // Arrange: 10000[...]4.2 (written as a decimal, with all its zeros) + var json = $"1{new string(Enumerable.Repeat('0', nbZeros).ToArray())}4.2"; + var value = QuantityValue.FromTerms(42 + BigInteger.Pow(10, nbZeros + 2), 10); + JsonSerializerOptions options = CreateOptions(); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Fact] + public void Serialize_VeryLargeDecimalNumber_AsString_ReturnsTheExpectedResult() + { + // Arrange: 4.2e-255 (written as a quoted decimal, with all its zeros) + var json = $""" + "0.{new string(Enumerable.Repeat('0', 512).ToArray())}42" + """; + var value = QuantityValue.FromPowerOfTen(42, -514); + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.WriteAsString; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + + [Theory] + [InlineData(511)] + [InlineData(512)] + [InlineData(-510)] + public void Serialize_FractionalWithLargeExponent_ReturnsTheExpectedResult(int exponent) + { + // Arrange: (1/3)e256 (written as a fraction, with all its zeros) + var value = QuantityValue.FromPowerOfTen(1, 3, exponent); + var (numerator, denominator) = QuantityValue.Reduce(value); + var json = $""" + "{numerator}/{denominator}" + """; + JsonSerializerOptions options = CreateOptions(); + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(json, result); + } + +// [Theory] +// // [InlineData(250, 250)] +// // [InlineData(40, 250)] +// [InlineData(2, 1)] +// // [InlineData(14, 6)] +// // [InlineData(25, 3)] +// public void Serialize_FractionalWithLargeTerms_ReturnsTheExpectedResult(int numeratorDigits, int denominatorDigits) +// { +// // Arrange: (1/3)e256 (written as a fraction, with all its zeros) +// var value = QuantityValue.FromTerms( +// BigInteger.Parse(new string(Enumerable.Repeat('2', numeratorDigits).ToArray())), +// BigInteger.Parse("1234567" + new string(Enumerable.Repeat('3', denominatorDigits).ToArray()))); +// var (numerator, denominator) = QuantityValue.Reduce(value); +// var json = $""" +// "{numerator}/{denominator}" +// """; +// JsonSerializerOptions options = CreateOptions(); +// +// // Act +// var result = JsonSerializer.Serialize(value, options); +// +// // Assert +// Assert.Equal(json, result); +// } + + [Fact] + public void Serializing_NaN_WithDefaultNumberHandling_ThrowsJsonException() + { + JsonSerializerOptions options = CreateOptions(); + Assert.Throws(() => JsonSerializer.Serialize(QuantityValue.NaN, options)); + } + + [Fact] + public void Serializing_NaN_WithAllowNamedFloatingPointLiterals_ReturnsTheExpectedResult() + { + // Arrange + const string expectedJson = """ + "NaN" + """; + QuantityValue value = QuantityValue.NaN; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Serializing_PositiveInfinity_WithAllowNamedFloatingPointLiterals_ReturnsTheExpectedResult() + { + // Arrange + const string expectedJson = """ + "Infinity" + """; + QuantityValue value = QuantityValue.PositiveInfinity; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Serializing_NegativeInfinity_WithAllowNamedFloatingPointLiterals_ReturnsTheExpectedResult() + { + // Arrange + const string expectedJson = """ + "-Infinity" + """; + QuantityValue value = QuantityValue.NegativeInfinity; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals; + + // Act + var result = JsonSerializer.Serialize(value, options); + + // Assert + Assert.Equal(expectedJson, result); + } + + [Fact] + public void Deserialize_DecimalNumberString_ReturnsTheExpectedValue() + { + // Arrange + const string json = "4.2"; + QuantityValue expected = 4.2m; + JsonSerializerOptions options = CreateOptions(); + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_NumberStringInScientificNotation_ReturnsTheExpectedValue() + { + // Arrange + const string json = "3.3333333E-06"; + QuantityValue expected = 3.3333333E-06; // ~ 1/300_000 + JsonSerializerOptions options = CreateOptions(); + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void Deserialize_FractionString_ReturnsTheExpectedValue() + { + // Arrange + const string json = """ + "1/3" + """; + var expected = QuantityValue.FromTerms(1, 3); + JsonSerializerOptions options = CreateOptions(); + + // Act + QuantityValue result = JsonSerializer.Deserialize(json, options); + + // Assert + Assert.Equal(expected, result); + } + + [Theory] + [InlineData(""" + "12345" + """)] + [InlineData(""" + "12345\u0034\u0035" + """)] + public void Deserializing_QuotedNumber_WithDefaultNumberHandling_ThrowsJsonException(string json) + { + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_WithValidEscapedCharacters_ReturnsTheExpectedResult() + { + // Arrange 1234545 (using the unicode '4') + const string json = """ + "12345\u0034\u0035" + """; + QuantityValue expectedValue = 1234545; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowReadingFromString; + + // Assert + Assert.Equal(expectedValue, JsonSerializer.Deserialize(json, options)); + Assert.Equal(expectedValue, JsonSerializer.Deserialize(json, options)); + } + + [Theory] + [InlineData(""" + "123invalid456" + """)] + [InlineData(""" + "123/invalid456" + """)] + public void Deserializing_WithInvalidString_ThrowsFormatException(string json) + { + // Arrange + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowReadingFromString; + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_WithEmptyString_ThrowsFormatException() + { + // Arrange + const string json = """ + "" + """; + JsonSerializerOptions options = CreateOptions(); + options.NumberHandling = JsonNumberHandling.AllowReadingFromString; + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } + + [Fact] + public void Deserializing_WithEmptyObjectString_ThrowsJsonException() + { + // Arrange + const string json = "{}"; + JsonSerializerOptions options = CreateOptions(); + + // Assert + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + Assert.Throws(() => JsonSerializer.Deserialize(json, options)); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson/AbbreviatedInterfaceQuantityWithAvailableValueConverter.cs b/UnitsNet.Serialization.SystemTextJson/AbbreviatedInterfaceQuantityWithAvailableValueConverter.cs new file mode 100644 index 0000000000..0b4080074d --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson/AbbreviatedInterfaceQuantityWithAvailableValueConverter.cs @@ -0,0 +1,228 @@ +// 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.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; +#if NET +using System.Diagnostics.CodeAnalysis; +#endif + +namespace UnitsNet.Serialization.SystemTextJson; + +/// +/// Provides a custom JSON converter for . +/// This converter handles serialization and deserialization of quantities, +/// ensuring that objects are correctly +/// represented in JSON format. +/// +public abstract class AbbreviatedInterfaceQuantityConverterBase : InterfaceQuantityConverterBase +{ + private readonly CultureInfo _culture = CultureInfo.InvariantCulture; + private readonly UnitParser _unitParser; + + /// + /// Initializes a new instance of the converter using the default . + /// + protected AbbreviatedInterfaceQuantityConverterBase() + : this(UnitParser.Default) + { + } + + /// + /// Initializes a new instance of the converter using the provided . + /// + /// + /// The used for deserializing an abbreviation back into its + /// corresponding unit. + /// + /// + /// Thrown when the parameter is null. + /// + protected AbbreviatedInterfaceQuantityConverterBase(UnitParser unitParser) + { + _unitParser = unitParser ?? throw new ArgumentNullException(nameof(unitParser)); + } + + /// + /// Initializes a new instance of the converter using the provided . + /// + /// + /// The used for deserializing an abbreviation back into its + /// corresponding unit. + /// + /// The primary culture that is used for the unit abbreviations. + /// + /// Thrown when the parameter is null. + /// + protected AbbreviatedInterfaceQuantityConverterBase(UnitParser unitParser, CultureInfo culture) + { + _unitParser = unitParser ?? throw new ArgumentNullException(nameof(unitParser)); + _culture = culture ?? throw new ArgumentNullException(nameof(culture)); + } + + /// + protected override void WriteUnitProperty(Utf8JsonWriter writer, IQuantity quantity, JsonSerializerOptions options) + { + writer.WriteStringValue(_unitParser.Abbreviations.GetDefaultAbbreviation(quantity.UnitKey, _culture)); + } + + /// + protected override string? ReadUnitProperty(ref Utf8JsonReader reader, JsonSerializerOptions options) + { + return reader.GetString(); + } + + /// + protected override IQuantity CreateQuantity(QuantityValue value, string? unitAbbreviation, string? quantityName) + { + UnitInfo unitInfo; + if (quantityName != null && unitAbbreviation != null) + { + unitInfo = _unitParser.GetUnitFromAbbreviation(quantityName, unitAbbreviation, _culture); + } + else if (unitAbbreviation != null) + { + unitInfo = _unitParser.GetUnitFromAbbreviation(unitAbbreviation, _culture); + } + else if (quantityName != null) + { + unitInfo = _unitParser.Quantities.GetQuantityByName(quantityName).BaseUnitInfo; + } + else + { + throw new JsonException("Both the quantity name and unit abbreviation are missing from the JSON."); + } + + return unitInfo.From(value); + } +} + +/// +/// Provides a specialized JSON converter for that utilizes a custom +/// for handling the value property of quantities. +/// This class extends the functionality of by +/// enabling +/// the use of a specific value converter for serialization and deserialization of the quantity's value. +/// +public class AbbreviatedInterfaceQuantityWithValueConverter : AbbreviatedInterfaceQuantityConverterBase +{ + private readonly JsonConverter _valueConverter; + + /// + /// Initializes a new instance of the class + /// with the specified value converter for handling the property of quantities. + /// + /// + /// The to be used for serializing and deserializing the + /// property. + /// + public AbbreviatedInterfaceQuantityWithValueConverter(JsonConverter valueConverter) + : this(valueConverter, UnitParser.Default) + { + } + + /// + /// Initializes a new instance of the + /// class + /// with the specified value converter and unit parser. + /// + /// + /// The used to handle the serialization and + /// deserialization of the value property of quantities. + /// + /// + /// The used to parse and interpret unit abbreviations. + /// + /// + /// Thrown when is null. + /// + public AbbreviatedInterfaceQuantityWithValueConverter(JsonConverter valueConverter, UnitParser unitParser) + : base(unitParser) + { + _valueConverter = valueConverter ?? throw new ArgumentNullException(nameof(valueConverter)); + } + + /// + protected override QuantityValue ReadValueProperty(ref Utf8JsonReader reader, JsonSerializerOptions options) + { + return _valueConverter.Read(ref reader, typeof(QuantityValue), options); + } + + /// + protected override void WriteValueProperty(Utf8JsonWriter writer, IQuantity quantity, JsonSerializerOptions options) + { + _valueConverter.Write(writer, quantity.Value, options); + } +} + +/// +/// Provides a custom JSON converter for . +/// This converter handles serialization and deserialization of quantities, +/// ensuring that objects are correctly +/// represented in JSON format. +/// +#if NET +[RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")] +[RequiresUnreferencedCode( + "If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] +#endif +public class AbbreviatedInterfaceQuantityWithAvailableValueConverter : AbbreviatedInterfaceQuantityConverterBase +{ + /// + public AbbreviatedInterfaceQuantityWithAvailableValueConverter() + { + } + + /// + public AbbreviatedInterfaceQuantityWithAvailableValueConverter(UnitParser unitParser) + : base(unitParser) + { + } + + /// + public AbbreviatedInterfaceQuantityWithAvailableValueConverter(UnitParser unitParser, CultureInfo culture) + : base(unitParser, culture) + { + } + + /// + /// Reads the value property of a JSON object representing a quantity. + /// + /// + /// The used to read the JSON data. + /// + /// + /// The that specify options for deserialization. + /// + /// + /// A representing the value of the quantity read from the JSON data. + /// + /// + /// This method is virtual, allowing derived classes to customize how the value property is read. + /// + /// + /// Thrown if the JSON data is invalid or cannot be deserialized into a . + /// + protected override QuantityValue ReadValueProperty(ref Utf8JsonReader reader, JsonSerializerOptions options) + { + return JsonSerializer.Deserialize(ref reader, options); + } + + /// + /// Writes the "Value" property of the quantity to the JSON output. + /// + /// + /// The used to write the JSON output. + /// + /// + /// The quantity whose "Value" property is being written. + /// + /// + /// The that specify options for JSON serialization. + /// + protected override void WriteValueProperty(Utf8JsonWriter writer, IQuantity quantity, JsonSerializerOptions options) + { + JsonSerializer.Serialize(writer, quantity.Value, options); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson/AbbreviatedQuantityConverter.cs b/UnitsNet.Serialization.SystemTextJson/AbbreviatedQuantityConverter.cs new file mode 100644 index 0000000000..ff2010e1f8 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson/AbbreviatedQuantityConverter.cs @@ -0,0 +1,209 @@ +// 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.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; +using UnitsNet.Serialization.SystemTextJson.Unit; +using UnitsNet.Serialization.SystemTextJson.Value; + +namespace UnitsNet.Serialization.SystemTextJson; + +/// +#if NET +[RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")] +[RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] +#endif +public class AbbreviatedQuantityConverter : JsonQuantityConverter +{ + private readonly CultureInfo _culture; + private readonly UnitParser _unitParser; + private readonly JsonConverter _valueConverter; + + /// + public AbbreviatedQuantityConverter() + : this(QuantityValueFractionalNotationConverter.Default) + { + } + + /// + public AbbreviatedQuantityConverter(JsonConverter valueConverter) + : this(valueConverter, UnitParser.Default) + { + } + + /// + public AbbreviatedQuantityConverter(JsonConverter valueConverter, UnitParser unitParser) + : this(valueConverter, unitParser, CultureInfo.InvariantCulture) + { + } + + /// + public AbbreviatedQuantityConverter(JsonConverter valueConverter, UnitParser unitParser, CultureInfo culture) + : base(unitParser.Quantities) + { + _valueConverter = valueConverter ?? throw new ArgumentNullException(nameof(valueConverter)); + _unitParser = unitParser; + _culture = culture ?? throw new ArgumentNullException(nameof(culture)); + } + + /// + public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + if (!TryGetQuantityInfo(typeToConvert, out QuantityInfo? quantityInfo)) + { + return null; + } + + Type converterType = typeof(AbbreviatedQuantityConverter<,>).MakeGenericType(typeToConvert, quantityInfo.UnitType); + return (JsonConverter?)Activator.CreateInstance(converterType, quantityInfo, _valueConverter, _unitParser, _culture); + } +} + +/// +public class AbbreviatedQuantityConverter : JsonQuantityConverterBase + where TQuantity : IQuantity + where TUnit : struct, Enum +{ + private readonly JsonConverter _unitConverter; + private readonly JsonConverter _valueConverter; + + /// + public AbbreviatedQuantityConverter() + // TODO what should be the default + : this(QuantityValueFractionalNotationConverter.Default) + { + } + +#if NET + /// + /// Initializes a new instance of the class + /// with the specified JSON converter for . + /// + /// + /// The JSON converter used to handle serialization and deserialization of . + /// + /// + /// This constructor allows customization of the conversion logic + /// by providing a specific implementation. + /// + public AbbreviatedQuantityConverter(JsonConverter valueConverter) + // : this((QuantityInfo)UnitsNetSetup.Default.QuantityInfoLookup.GetQuantityInfo(typeof(TQuantity)), valueConverter) + // TODO see if we want to expose the QuantityInfo (a.k.a. the static "Info" property) on the IQuantity interface + : this(TQuantity.From(QuantityValue.Zero, default).QuantityInfo, valueConverter) + { + } +#else + /// + /// Initializes a new instance of the class + /// with a specified JSON converter for . + /// + /// + /// The used to convert instances during serialization and + /// deserialization. + /// + public AbbreviatedQuantityConverter(JsonConverter valueConverter) + : this((QuantityInfo)UnitsNetSetup.Default.Quantities.GetQuantityInfo(typeof(TQuantity)), valueConverter) + { + } +#endif + + /// + /// Initializes a new instance of the class. + /// + /// + /// The containing metadata about the quantity type and its units. + /// + /// + /// The used to convert the quantity value. + /// + /// + /// This constructor allows specifying the quantity information and a custom value converter for serialization and + /// deserialization. + /// + public AbbreviatedQuantityConverter(QuantityInfo quantityInfo, JsonConverter valueConverter) + : this(quantityInfo, valueConverter, UnitParser.Default) + { + } + + /// + /// Initializes a new instance of the class + /// with the specified quantity information, value converter, unit parser, and culture settings. + /// + /// + /// The containing metadata about the quantity type and its units. + /// + /// + /// The used to serialize and deserialize the quantity value. + /// + /// + /// The used to parse unit abbreviations. + /// + public AbbreviatedQuantityConverter(QuantityInfo quantityInfo, JsonConverter valueConverter, UnitParser unitParser) + : this(quantityInfo, valueConverter, unitParser, CultureInfo.InvariantCulture) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// The containing metadata about the quantity type and its units. + /// + /// + /// The used to serialize and deserialize the quantity value. + /// + /// + /// The used to parse unit abbreviations. + /// + /// + /// The used for culture-specific formatting and parsing. + /// + public AbbreviatedQuantityConverter(QuantityInfo quantityInfo, JsonConverter valueConverter, UnitParser unitParser, + CultureInfo culture) + : this(quantityInfo, valueConverter, new AbbreviatedUnitConverter(unitParser, culture)) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The quantity information used for serialization and deserialization. + /// The JSON converter for handling instances. + /// The JSON converter for handling unit types of . + /// + /// Thrown when or is null. + /// + public AbbreviatedQuantityConverter(QuantityInfo quantityInfo, JsonConverter valueConverter, + JsonConverter unitConverter) + : base(quantityInfo) + { + _valueConverter = valueConverter ?? throw new ArgumentNullException(nameof(valueConverter)); + _unitConverter = unitConverter ?? throw new ArgumentNullException(nameof(unitConverter)); + } + + /// + protected override TUnit? ReadUnitProperty(ref Utf8JsonReader reader, JsonSerializerOptions options) + { + return _unitConverter.Read(ref reader, typeof(TUnit), options); + } + + /// + protected override QuantityValue ReadValueProperty(ref Utf8JsonReader reader, JsonSerializerOptions options) + { + return _valueConverter.Read(ref reader, typeof(QuantityValue), options); + } + + /// + protected override void WriteUnitProperty(Utf8JsonWriter writer, TQuantity quantity, JsonSerializerOptions options) + { + _unitConverter.Write(writer, quantity.Unit, options); + } + + /// + protected override void WriteValueProperty(Utf8JsonWriter writer, TQuantity quantity, JsonSerializerOptions options) + { + _valueConverter.Write(writer, quantity.Value, options); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson/InterfaceQuantityConverterBase.cs b/UnitsNet.Serialization.SystemTextJson/InterfaceQuantityConverterBase.cs new file mode 100644 index 0000000000..46516b013d --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson/InterfaceQuantityConverterBase.cs @@ -0,0 +1,216 @@ +// 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.Text.Json; +using System.Text.Json.Serialization; + +namespace UnitsNet.Serialization.SystemTextJson; + +/// +/// Provides a custom JSON converter for . +/// This converter handles serialization and deserialization of quantities, +/// ensuring that objects are correctly +/// represented in JSON format. +/// +public abstract class InterfaceQuantityConverterBase : JsonConverter +{ + /// + public override void Write(Utf8JsonWriter writer, IQuantity quantity, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + JsonEncodedText valueProperty, unitProperty, typeProperty; + if (options.PropertyNamesShouldStartWithLowercase()) + { + valueProperty = JsonQuantityPropertyNames.ValuePropertyName_Lowercase; + unitProperty = JsonQuantityPropertyNames.UnitPropertyName_Lowercase; + typeProperty = JsonQuantityPropertyNames.TypePropertyName_Lowercase; + } + else + { + valueProperty = JsonQuantityPropertyNames.ValuePropertyName; + unitProperty = JsonQuantityPropertyNames.UnitPropertyName; + typeProperty = JsonQuantityPropertyNames.TypePropertyName; + } + + if (options.DefaultIgnoreCondition == JsonIgnoreCondition.WhenWritingDefault) + { + if (!QuantityValue.IsZero(quantity.Value)) + { + // write the Value property + writer.WritePropertyName(valueProperty); + WriteValueProperty(writer, quantity, options); + } + + if (quantity.UnitKey.UnitEnumValue != quantity.QuantityInfo.BaseUnitInfo.UnitKey.UnitEnumValue) + { + // write the Unit property + writer.WritePropertyName(unitProperty); + WriteUnitProperty(writer, quantity, options); + } + } + else + { + // write the Value property + writer.WritePropertyName(valueProperty); + WriteValueProperty(writer, quantity, options); + // write the Unit property + writer.WritePropertyName(unitProperty); + WriteUnitProperty(writer, quantity, options); + } + + // write the Type property (disambiguation based on the quantity name) + writer.WriteString(typeProperty, quantity.QuantityInfo.Name); + + writer.WriteEndObject(); + } + + /// + public override IQuantity Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + QuantityValue value = QuantityValue.Zero; + TJsonUnit? unit = default; + string? quantityName = null; + JsonEncodedText valueProperty, unitProperty, typeProperty; + if (options.PropertyNamesShouldStartWithLowercase()) + { + valueProperty = JsonQuantityPropertyNames.ValuePropertyName_Lowercase; + unitProperty = JsonQuantityPropertyNames.UnitPropertyName_Lowercase; + typeProperty = JsonQuantityPropertyNames.TypePropertyName_Lowercase; + } + else + { + valueProperty = JsonQuantityPropertyNames.ValuePropertyName; + unitProperty = JsonQuantityPropertyNames.UnitPropertyName; + typeProperty = JsonQuantityPropertyNames.TypePropertyName; + } + + if (options.PropertyNameCaseInsensitive) + { + while (reader.ReadNextProperty()) + { + var propertyName = reader.GetString(); + reader.Read(); + if (StringComparer.OrdinalIgnoreCase.Equals(propertyName, valueProperty.Value)) + { + value = ReadValueProperty(ref reader, options); + } + else if (StringComparer.OrdinalIgnoreCase.Equals(propertyName, unitProperty.Value)) + { + unit = ReadUnitProperty(ref reader, options); + } + else if (StringComparer.OrdinalIgnoreCase.Equals(propertyName, typeProperty.Value)) + { + quantityName = reader.GetString(); + } + else if (options.UnmappedMemberHandling == JsonUnmappedMemberHandling.Skip) + { + reader.Skip(); // Skip unknown properties + } + else + { + throw new JsonException($"'{propertyName}' was no found in the list of members of '{typeToConvert}'."); + } + } + } + else + { + while (reader.ReadNextProperty()) + { + if (reader.ValueTextEquals(valueProperty.EncodedUtf8Bytes)) + { + reader.Read(); + value = ReadValueProperty(ref reader, options); + } + else if (reader.ValueTextEquals(unitProperty.EncodedUtf8Bytes)) + { + reader.Read(); + unit = ReadUnitProperty(ref reader, options); + } + else if (reader.ValueTextEquals(typeProperty.EncodedUtf8Bytes)) + { + reader.Read(); + quantityName = reader.GetString(); + } + else if (options.UnmappedMemberHandling == JsonUnmappedMemberHandling.Skip) + { + reader.Skip(); // Skip unknown properties + } + else + { + throw new JsonException($"'{reader.GetString()}' was no found in the list of members of '{typeToConvert}'."); + } + } + } + + return CreateQuantity(value, unit, quantityName); + } + + /// + /// Writes the value property of the quantity to the JSON output. + /// + /// + /// The used to write the JSON output. + /// + /// + /// The quantity whose "Value" property is being written. + /// + /// + /// The that specify options for JSON serialization. + /// + protected abstract void WriteValueProperty(Utf8JsonWriter writer, IQuantity quantity, JsonSerializerOptions options); + + /// + /// Writes the unit property of the quantity to the JSON output. + /// + /// + /// The used to write the JSON output. + /// + /// + /// The quantity whose unit is being written. + /// + /// + /// The that specify options for JSON serialization. + /// + protected abstract void WriteUnitProperty(Utf8JsonWriter writer, IQuantity quantity, JsonSerializerOptions options); + + /// + /// Reads the value property of a JSON object representing a quantity. + /// + /// + /// The used to read the JSON data. + /// + /// + /// The that specify options for deserialization. + /// + /// + /// A representing the value of the quantity read from the JSON data. + /// + protected abstract QuantityValue ReadValueProperty(ref Utf8JsonReader reader, JsonSerializerOptions options); + + /// + /// Reads the "Unit" property of a JSON object representing a quantity. + /// + /// + /// The used to read the JSON data. + /// + /// + /// The that specify options for deserialization. + /// + /// + /// A representing the matching unit of the quantity read from the JSON data. + /// + /// + /// This method is virtual, allowing derived classes to customize how the value property is read. + /// + protected abstract TJsonUnit ReadUnitProperty(ref Utf8JsonReader reader, JsonSerializerOptions options); + + /// + /// Creates an instance of using the specified value, unit, and quantity name. + /// + /// The numerical value of the quantity. + /// The unit associated with the quantity. + /// The name used to identify the type of quantity. + /// An instance of representing the specified value and unit. + protected abstract IQuantity CreateQuantity(QuantityValue value, TJsonUnit? unit, string? quantityName); +} diff --git a/UnitsNet.Serialization.SystemTextJson/InterfaceQuantityWithUnitTypeConverter.cs b/UnitsNet.Serialization.SystemTextJson/InterfaceQuantityWithUnitTypeConverter.cs new file mode 100644 index 0000000000..5174090ea3 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson/InterfaceQuantityWithUnitTypeConverter.cs @@ -0,0 +1,303 @@ +// 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.Text.Json; +using System.Text.Json.Serialization; +#if NET +using System.Collections.Frozen; +using System.Text; +using System.Diagnostics.CodeAnalysis; +#endif + +namespace UnitsNet.Serialization.SystemTextJson; + +/// +/// Provides a custom JSON converter for . +/// This converter handles serialization and deserialization of quantities, +/// ensuring that objects are correctly +/// represented in JSON format. +/// +#if NET +[RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")] +[RequiresUnreferencedCode( + "If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] +#endif +public class InterfaceQuantityWithUnitTypeConverter : JsonConverter +{ + private readonly bool _ignoreCase; +#if NET + private readonly FrozenDictionary _quantities; +#else + private readonly Dictionary _quantities; +#endif + + /// + /// Initializes a new instance of the class with case-sensitive + /// unit matching. + /// + /// + /// This constructor uses the default from + /// to resolve unit names during JSON serialization and deserialization. + /// + public InterfaceQuantityWithUnitTypeConverter() + : this(UnitsNetSetup.Default.Quantities) + { + } + + /// + /// Initializes a new instance of the class + /// with an option to specify case sensitivity. + /// + /// + /// This constructor uses the default from + /// to resolve unit names during JSON serialization and deserialization. + /// + public InterfaceQuantityWithUnitTypeConverter(bool ignoreCase) + : this(UnitsNetSetup.Default.Quantities, ignoreCase) + { + } + + /// + /// Initializes a new instance of the class with the specified + /// and an option to specify case sensitivity. + /// + /// + /// The instance used to resolve quantity and unit information + /// during JSON serialization and deserialization. + /// + /// + /// A boolean value indicating whether the unit name comparison should ignore case during JSON serialization and + /// deserialization. + /// + /// + /// This constructor allows customization of the used for parsing and + /// formatting unit names, enabling advanced scenarios where specific quantity and unit information is required. + /// + public InterfaceQuantityWithUnitTypeConverter(QuantityInfoLookup quantities, bool ignoreCase = false) + { + StringComparer comparer = ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal; +#if NET + _quantities = quantities.Infos.ToFrozenDictionary(info => info.UnitType.Name, comparer); +#else + _quantities = quantities.Infos.ToDictionary(info => info.UnitType.Name, comparer); +#endif + _ignoreCase = ignoreCase; + } + + /// + public override IQuantity Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + QuantityValue value = QuantityValue.Zero; + UnitInfo? unitInfo = null; + JsonEncodedText valueProperty, unitProperty; + if (options.PropertyNamesShouldStartWithLowercase()) + { + valueProperty = JsonQuantityPropertyNames.ValuePropertyName_Lowercase; + unitProperty = JsonQuantityPropertyNames.UnitPropertyName_Lowercase; + } + else + { + valueProperty = JsonQuantityPropertyNames.ValuePropertyName; + unitProperty = JsonQuantityPropertyNames.UnitPropertyName; + } + + if (options.PropertyNameCaseInsensitive) + { + while (reader.ReadNextProperty()) + { + var propertyName = reader.GetString(); + reader.Read(); + if (StringComparer.OrdinalIgnoreCase.Equals(propertyName, valueProperty.Value)) + { + value = ReadValueProperty(ref reader, options); + } + else if (StringComparer.OrdinalIgnoreCase.Equals(propertyName, unitProperty.Value)) + { + unitInfo = ReadUnitInfoProperty(ref reader); + } + else if (options.UnmappedMemberHandling == JsonUnmappedMemberHandling.Skip) + { + reader.Skip(); // Skip unknown properties + } + else + { + throw new JsonException($"'{propertyName}' was no found in the list of members of '{typeToConvert}'."); + } + } + } + else + { + while (reader.ReadNextProperty()) + { + if (reader.ValueTextEquals(valueProperty.EncodedUtf8Bytes)) + { + reader.Read(); + value = ReadValueProperty(ref reader, options); + } + else if (reader.ValueTextEquals(unitProperty.EncodedUtf8Bytes)) + { + reader.Read(); + unitInfo = ReadUnitInfoProperty(ref reader); + } + else if (options.UnmappedMemberHandling == JsonUnmappedMemberHandling.Skip) + { + reader.Skip(); // Skip unknown properties + } + else + { + throw new JsonException($"'{reader.GetString()}' was no found in the list of members of '{typeToConvert}'."); + } + } + } + + if (unitInfo == null) + { + throw new JsonException($"The {unitProperty} property is missing from the JSON"); + } + + return unitInfo.From(value); + } + + /// + /// Reads the value property of a JSON object representing a quantity. + /// + /// + /// The used to read the JSON data. + /// + /// + /// The that specify options for deserialization. + /// + /// + /// A representing the value of the quantity read from the JSON data. + /// + /// + /// This method is virtual, allowing derived classes to customize how the value property is read. + /// + /// + /// Thrown if the JSON data is invalid or cannot be deserialized into a . + /// +#if NET + [RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")] + [RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] +#endif + protected virtual QuantityValue ReadValueProperty(ref Utf8JsonReader reader, JsonSerializerOptions options) + { + return JsonSerializer.Deserialize(ref reader, options); + } + + private UnitInfo ReadUnitInfoProperty(ref Utf8JsonReader reader) + { +#if NET + var charCount = Encoding.UTF8.GetCharCount(reader.ValueSpan); + if (charCount == 0) + { + throw new JsonException("Missing unit"); + } + + Span charBuffer = charCount <= 256 ? stackalloc char[charCount] : new char[charCount]; + Encoding.UTF8.GetChars(reader.ValueSpan, charBuffer); + ReadOnlySpan unitSpan = charBuffer; + if (!unitSpan.TrySplit('.', out ReadOnlySpan unitTypeNameSpan, out ReadOnlySpan unitNameSpan)) + { + throw new JsonException($"Invalid unit format: \"{unitSpan}\""); + } +#else + var unitString = reader.GetString(); // TODO see about using a span here + if (string.IsNullOrEmpty(unitString)) + { + throw new JsonException("Missing unit"); + } + + ReadOnlySpan unitSpan = unitString.AsSpan(); + if (!unitSpan.TrySplit('.', out ReadOnlySpan unitTypeNameSpan, out ReadOnlySpan unitNameSpan)) + { + throw new JsonException($"Invalid unit format: \"{unitString}\""); + } +#endif + + var unitTypeName = unitTypeNameSpan.ToString(); + if (!_quantities.TryGetValue(unitTypeName, out QuantityInfo? quantityInfo)) + { + throw new QuantityNotFoundException($"No quantity in the current configuration contains a unit with the specified type name: '{unitTypeName}'"); + } + + IReadOnlyList unitInfos = quantityInfo.UnitInfos; + var nbUnits = unitInfos.Count; + if (_ignoreCase) + { + for (var i = 0; i < nbUnits; i++) + { + UnitInfo unitInfo = unitInfos[i]; + if (unitNameSpan.Equals(unitInfo.Name.AsSpan(), StringComparison.OrdinalIgnoreCase)) + { + return unitInfo; + } + } + } + else + { + for (var i = 0; i < nbUnits; i++) + { + UnitInfo unitInfo = unitInfos[i]; + if (unitNameSpan.SequenceEqual(unitInfo.Name.AsSpan())) + { + return unitInfo; + } + } + } + + var unitNamePart = unitNameSpan.ToString(); + throw new UnitNotFoundException($"No unit was found for quantity '{quantityInfo.Name}' with the name: '{unitNamePart}'.") + { + Data = { ["quantityName"] = quantityInfo.Name, ["unitName"] = unitNamePart } + }; + } + + /// + /// Writes the "Value" property of the quantity to the JSON output. + /// + /// + /// The used to write the JSON output. + /// + /// + /// The quantity whose "Value" property is being written. + /// + /// + /// The that specify options for JSON serialization. + /// + protected virtual void WriteValueProperty(Utf8JsonWriter writer, IQuantity quantity, JsonSerializerOptions options) + { + JsonSerializer.Serialize(writer, quantity.Value, options); + } + + /// + public override void Write(Utf8JsonWriter writer, IQuantity quantity, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + JsonEncodedText valueProperty, unitProperty; + if (options.PropertyNamesShouldStartWithLowercase()) + { + valueProperty = JsonQuantityPropertyNames.ValuePropertyName_Lowercase; + unitProperty = JsonQuantityPropertyNames.UnitPropertyName_Lowercase; + } + else + { + valueProperty = JsonQuantityPropertyNames.ValuePropertyName; + unitProperty = JsonQuantityPropertyNames.UnitPropertyName; + } + + if (options.DefaultIgnoreCondition != JsonIgnoreCondition.WhenWritingDefault || !QuantityValue.IsZero(quantity.Value)) + { + // write the Value property (with the default converter) + writer.WritePropertyName(valueProperty); + WriteValueProperty(writer, quantity, options); + } + + QuantityInfo quantityInfo = quantity.QuantityInfo; + var unitFormat = $"{quantityInfo.UnitType.Name}.{quantityInfo[quantity.UnitKey].Name}"; + writer.WriteString(unitProperty, unitFormat); + + writer.WriteEndObject(); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson/JsonExtensions.cs b/UnitsNet.Serialization.SystemTextJson/JsonExtensions.cs new file mode 100644 index 0000000000..fbff3ad7f0 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson/JsonExtensions.cs @@ -0,0 +1,197 @@ +// 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.Buffers; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Text; +using System.Text.Json; + +namespace UnitsNet.Serialization.SystemTextJson; + +internal static class JsonExtensions +{ + public static bool ReadNextProperty(this ref Utf8JsonReader reader) + { + reader.Read(); + return reader.TokenType switch + { + JsonTokenType.PropertyName => true, + JsonTokenType.EndObject => false, + _ => throw new JsonException("Expected PropertyName token.") + }; + } + + [SuppressMessage("ReSharper", "ReplaceSliceWithRangeIndexer")] + public static bool TrySplit(this ReadOnlySpan span, char separator, out ReadOnlySpan firstSpan, out ReadOnlySpan secondSpan) + { + var separatorIndex = span.IndexOf(separator); + + if (separatorIndex < 0) + { + firstSpan = span; + secondSpan = ReadOnlySpan.Empty; + return false; + } + + firstSpan = span.Slice(0, separatorIndex); + secondSpan = span.Slice(separatorIndex + 1); + return true; + } + + + public static bool PropertyNamesShouldStartWithLowercase(this JsonSerializerOptions options) + { + JsonNamingPolicy? namingPolicy = options.PropertyNamingPolicy; + return namingPolicy == JsonNamingPolicy.CamelCase || namingPolicy == JsonNamingPolicy.KebabCaseLower || namingPolicy == JsonNamingPolicy.SnakeCaseLower; + } + + public static void WriteStringValues(this Utf8JsonWriter writer, ReadOnlySpan first, char separator, ReadOnlySpan second) + { + var requiredLength = first.Length + second.Length + 1; + Span charBuffer = requiredLength <= 512 ? stackalloc char[requiredLength] : new char[requiredLength]; + CombineSpansWithSeparator(first, separator, second, charBuffer); + writer.WriteStringValue(charBuffer); + } + + public static void WriteValuesAsPropertyName(this Utf8JsonWriter writer, ReadOnlySpan first, char separator, ReadOnlySpan second) + { + var requiredLength = first.Length + second.Length + 1; + Span charBuffer = requiredLength <= 512 ? stackalloc char[requiredLength] : new char[requiredLength]; + CombineSpansWithSeparator(first, separator, second, charBuffer); + writer.WritePropertyName(charBuffer); + } + + // ReSharper disable once ReplaceSliceWithRangeIndexer + private static void CombineSpansWithSeparator(ReadOnlySpan first, char separator, ReadOnlySpan second, Span charBuffer) + { + first.CopyTo(charBuffer); + charBuffer[first.Length] = separator; + second.CopyTo(charBuffer.Slice(first.Length + 1)); + } + +#if NET + public static void WriteValuesAsString(this Utf8JsonWriter writer, TValue first, char separator, TValue second, IFormatProvider? formatProvider = null, int stackAlloc = 512) + where TValue: ISpanFormattable + { + Span charBuffer = stackalloc char[stackAlloc]; + int firstCharsWritten; + while (!first.TryFormat(charBuffer, out firstCharsWritten, ReadOnlySpan.Empty, formatProvider)) + { + charBuffer = new char[charBuffer.Length * 2]; + } + + if (firstCharsWritten == charBuffer.Length) + { + var extendedBuffer = new char[charBuffer.Length * 2]; + charBuffer.CopyTo(extendedBuffer); + charBuffer = extendedBuffer; + } + + charBuffer[firstCharsWritten] = separator; + + int secondCharsWritten; + while (!second.TryFormat(charBuffer[(firstCharsWritten + 1)..], out secondCharsWritten, ReadOnlySpan.Empty, formatProvider)) + { + var extendedBuffer = new char[charBuffer.Length * 2]; + charBuffer.CopyTo(extendedBuffer); + charBuffer = extendedBuffer; + } + + writer.WriteStringValue(charBuffer[..(firstCharsWritten + secondCharsWritten + 1)]); + } + +#endif + + + // private const int StackallocByteThreshold = 512; + // + // internal static int CopyValue(this ref Utf8JsonReader reader, Span destination) + // { + // // Debug.Assert(_tokenType is JsonTokenType.String or JsonTokenType.PropertyName or JsonTokenType.Number); + // // Debug.Assert(_tokenType != JsonTokenType.Number || !ValueIsEscaped, "Numbers can't contain escape characters."); + // + // scoped ReadOnlySpan unescapedSource; + // byte[]? rentedBuffer = null; + // int valueLength; + // + // if (reader.ValueIsEscaped) + // { + // valueLength = reader.HasValueSequence ? checked((int)reader.ValueSequence.Length) : reader.ValueSpan.Length; + // + // Span unescapedBuffer = valueLength <= StackallocByteThreshold ? + // stackalloc byte[StackallocByteThreshold] : + // (rentedBuffer = ArrayPool.Shared.Rent(valueLength)); + // + // bool success = TryCopyEscapedString(ref reader, unescapedBuffer, out int bytesWritten); + // // Debug.Assert(success); + // unescapedSource = unescapedBuffer.Slice(0, bytesWritten); + // } + // else + // { + // if (reader.HasValueSequence) + // { + // ReadOnlySequence valueSequence = reader.ValueSequence; + // valueLength = checked((int)valueSequence.Length); + // + // Span intermediate = valueLength <= StackallocByteThreshold ? + // stackalloc byte[StackallocByteThreshold] : + // (rentedBuffer = ArrayPool.Shared.Rent(valueLength)); + // + // valueSequence.CopyTo(intermediate); + // unescapedSource = intermediate.Slice(0, valueLength); + // } + // else + // { + // unescapedSource = reader.ValueSpan; + // } + // } + // + // int charsWritten = JsonReaderHelper.TranscodeHelper(unescapedSource, destination); + // + // if (rentedBuffer != null) + // { + // new Span(rentedBuffer, 0, unescapedSource.Length).Clear(); + // ArrayPool.Shared.Return(rentedBuffer); + // } + // + // return charsWritten; + // } + // + // private static bool TryCopyEscapedString(this ref Utf8JsonReader reader, Span destination, out int bytesWritten) + // { + // Debug.Assert(_tokenType is JsonTokenType.String or JsonTokenType.PropertyName); + // Debug.Assert(ValueIsEscaped); + // + // byte[]? rentedBuffer = null; + // scoped ReadOnlySpan source; + // + // if (reader.HasValueSequence) + // { + // ReadOnlySequence valueSequence = reader.ValueSequence; + // int sequenceLength = checked((int)valueSequence.Length); + // + // Span intermediate = sequenceLength <= StackallocByteThreshold ? + // stackalloc byte[StackallocByteThreshold] : + // (rentedBuffer = ArrayPool.Shared.Rent(sequenceLength)); + // + // valueSequence.CopyTo(intermediate); + // source = intermediate.Slice(0, sequenceLength); + // } + // else + // { + // source = reader.ValueSpan; + // } + // + // bool success = JsonReaderHelper.TryUnescape(source, destination, out bytesWritten); + // + // if (rentedBuffer != null) + // { + // new Span(rentedBuffer, 0, source.Length).Clear(); + // ArrayPool.Shared.Return(rentedBuffer); + // } + // + // Debug.Assert(bytesWritten < source.Length, "source buffer must contain at least one escape sequence"); + // return success; + // } +} diff --git a/UnitsNet.Serialization.SystemTextJson/JsonQuantityConverter.cs b/UnitsNet.Serialization.SystemTextJson/JsonQuantityConverter.cs new file mode 100644 index 0000000000..48aad0d160 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson/JsonQuantityConverter.cs @@ -0,0 +1,473 @@ +// 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.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace UnitsNet.Serialization.SystemTextJson; + +internal static class JsonQuantityPropertyNames +{ + public static readonly JsonEncodedText ValuePropertyName = JsonEncodedText.Encode("Value"); + public static readonly JsonEncodedText ValuePropertyName_Lowercase = JsonEncodedText.Encode("value"); + + public static readonly JsonEncodedText UnitPropertyName = JsonEncodedText.Encode("Unit"); + public static readonly JsonEncodedText UnitPropertyName_Lowercase = JsonEncodedText.Encode("unit"); + + public static readonly JsonEncodedText TypePropertyName = JsonEncodedText.Encode("Type"); + public static readonly JsonEncodedText TypePropertyName_Lowercase = JsonEncodedText.Encode("type"); +} + +/// +/// Provides a custom JSON converter for quantities implementing . +/// This generic converter handles serialization and deserialization of quantities, +/// ensuring that objects of type are correctly +/// represented in JSON format. +/// +/// +/// The type of the quantity being serialized or deserialized, which must implement +/// . +/// +/// +/// The type of the unit enumeration associated with the quantity, which must be a value type and an enumeration. +/// +/// +/// In order to use this converter directly, you need to make sure that the +/// contains a converter for both the and the +/// of the quantity. +/// +public abstract class JsonQuantityConverterBase : JsonConverter + where TQuantity : IQuantity + where TUnit : struct, Enum +{ + private readonly QuantityInfo _quantityInfo; + + /// + /// Initializes a new instance of the converter using the default of the specified quantity type. + /// + /// + /// This constructor creates a converter that uses the default + /// for the specified quantity type . It is particularly useful when + /// no custom is required for serialization or deserialization. + /// + protected JsonQuantityConverterBase() +#if NET + // TODO see if we want to expose the QuantityInfo (a.k.a. the static "Info" property) on the IQuantity interface + : this(TQuantity.From(QuantityValue.Zero, default).QuantityInfo) +#else + : this((QuantityInfo)UnitsNetSetup.Default.Quantities.GetQuantityInfo(typeof(TQuantity))) +#endif + { + } + + /// + /// Initializes a new instance of the converter with the specified . + /// + /// + /// The instance that provides metadata and configuration + /// for the quantity type and its associated unit type . + /// + protected JsonQuantityConverterBase(QuantityInfo quantityInfo) + { + _quantityInfo = quantityInfo ?? throw new ArgumentNullException(nameof(quantityInfo)); + } + + /// + public override TQuantity Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + QuantityValue value = QuantityValue.Zero; + TUnit? unit = null; + JsonEncodedText valueProperty, unitProperty; + if (options.PropertyNamesShouldStartWithLowercase()) + { + valueProperty = JsonQuantityPropertyNames.ValuePropertyName_Lowercase; + unitProperty = JsonQuantityPropertyNames.UnitPropertyName_Lowercase; + } + else + { + valueProperty = JsonQuantityPropertyNames.ValuePropertyName; + unitProperty = JsonQuantityPropertyNames.UnitPropertyName; + } + + if (options.PropertyNameCaseInsensitive) + { + while (reader.ReadNextProperty()) + { + var propertyName = reader.GetString(); + reader.Read(); + + if (StringComparer.OrdinalIgnoreCase.Equals(propertyName, valueProperty.Value)) + { + value = ReadValueProperty(ref reader, options); + } + else if (StringComparer.OrdinalIgnoreCase.Equals(propertyName, unitProperty.Value)) + { + unit = ReadUnitProperty(ref reader, options); + } + else if (options.UnmappedMemberHandling == JsonUnmappedMemberHandling.Skip) + { + reader.Skip(); // Skip unknown properties + } + else + { + throw new JsonException($"'{propertyName}' was no found in the list of members of '{typeToConvert}'."); + } + } + } + else + { + while (reader.ReadNextProperty()) + { + if (reader.ValueTextEquals(valueProperty.EncodedUtf8Bytes)) + { + reader.Read(); + value = ReadValueProperty(ref reader, options); + } + else if (reader.ValueTextEquals(unitProperty.EncodedUtf8Bytes)) + { + reader.Read(); + unit = ReadUnitProperty(ref reader, options); + } + else if (options.UnmappedMemberHandling == JsonUnmappedMemberHandling.Skip) + { + reader.Skip(); // Skip unknown properties + } + else + { + throw new JsonException($"'{reader.GetString()}' was no found in the list of members of '{typeToConvert}'."); + } + } + } + + // note: we could be using TQuantity.From(value, unit.Value) instead + return unit == null ? _quantityInfo.BaseUnitInfo.From(value) : _quantityInfo.From(value, unit.Value); + } + + /// + public override void Write(Utf8JsonWriter writer, TQuantity quantity, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + JsonEncodedText valueProperty, unitProperty; + if (options.PropertyNamesShouldStartWithLowercase()) + { + valueProperty = JsonQuantityPropertyNames.ValuePropertyName_Lowercase; + unitProperty = JsonQuantityPropertyNames.UnitPropertyName_Lowercase; + } + else + { + valueProperty = JsonQuantityPropertyNames.ValuePropertyName; + unitProperty = JsonQuantityPropertyNames.UnitPropertyName; + } + + if (options.DefaultIgnoreCondition == JsonIgnoreCondition.WhenWritingDefault) + { + if (!QuantityValue.IsZero(quantity.Value)) + { + writer.WritePropertyName(valueProperty); + WriteValueProperty(writer, quantity, options); + } + + if (!EqualityComparer.Default.Equals(quantity.Unit, _quantityInfo.BaseUnitInfo.Value)) + { + writer.WritePropertyName(unitProperty); + WriteUnitProperty(writer, quantity, options); + } + } + else + { + writer.WritePropertyName(valueProperty); + WriteValueProperty(writer, quantity, options); + writer.WritePropertyName(unitProperty); + WriteUnitProperty(writer, quantity, options); + } + + writer.WriteEndObject(); + } + + /// + /// Reads the value property of a JSON object representing a quantity. + /// + /// + /// The used to read the JSON data. + /// + /// + /// The that specify options for deserialization. + /// + /// + /// A representing the value of the quantity read from the JSON data. + /// + /// + /// This method is virtual, allowing derived classes to customize how the value property is read. + /// + /// + /// Thrown if the JSON data is invalid or cannot be deserialized into a . + /// + protected abstract QuantityValue ReadValueProperty(ref Utf8JsonReader reader, JsonSerializerOptions options); + + /// + /// Reads the unit property from the JSON input. + /// + /// + /// The used to read the JSON input. + /// + /// + /// The that specify options for deserialization. + /// + /// + /// The deserialized unit of type , or null if the unit could not be read. + /// + /// + /// Thrown if the JSON input is invalid or does not contain a valid unit property. + /// + protected abstract TUnit? ReadUnitProperty(ref Utf8JsonReader reader, JsonSerializerOptions options); + + /// + /// Writes the "Value" property of the quantity to the JSON output. + /// + /// + /// The used to write the JSON output. + /// + /// + /// The quantity whose "Value" property is being written. + /// + /// + /// The that specify options for JSON serialization. + /// + protected abstract void WriteValueProperty(Utf8JsonWriter writer, TQuantity quantity, JsonSerializerOptions options); + + /// + /// Writes the unit property of the quantity to the JSON output. + /// + /// + /// The used to write the JSON output. + /// + /// + /// The quantity whose unit property is being written. + /// + /// + /// The that specify options for JSON serialization. + /// + /// + /// This method writes the unit property name and its value to the JSON output. + /// The property name is determined by the if specified, + /// otherwise it defaults to the value of UnitPropertyName. + /// + protected abstract void WriteUnitProperty(Utf8JsonWriter writer, TQuantity quantity, JsonSerializerOptions options); +} + +/// +/// Provides a custom JSON converter for quantities implementing . +/// This generic converter handles serialization and deserialization of quantities, +/// ensuring that objects of type are correctly +/// represented in JSON format. +/// +/// +/// The type of the quantity being serialized or deserialized, which must implement +/// . +/// +/// +/// The type of the unit enumeration associated with the quantity, which must be a value type and an enumeration. +/// +/// +/// In order to use this converter directly, you need to make sure that the +/// contains a converter for both the and the +/// of the quantity. +/// +#if NET +[RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")] +[RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] +#endif +public class JsonQuantityConverter : JsonQuantityConverterBase + where TQuantity : IQuantity + where TUnit : struct, Enum +{ + /// + /// Initializes a new instance of the class + /// using the default of the specified quantity type. + /// + /// + /// This constructor creates a converter that uses the default + /// for the specified quantity type . It is particularly useful when + /// no custom is required for serialization or deserialization. + /// + public JsonQuantityConverter() + { + } + + /// + /// Initializes a new instance of the class + /// with the specified . + /// + /// + /// The instance that provides metadata and configuration + /// for the quantity type and its associated unit type . + /// + public JsonQuantityConverter(QuantityInfo quantityInfo) + : base(quantityInfo) + { + } + + /// + /// Reads the value property of a JSON object representing a quantity. + /// + /// + /// The used to read the JSON data. + /// + /// + /// The that specify options for deserialization. + /// + /// + /// A representing the value of the quantity read from the JSON data. + /// + /// + /// This method is virtual, allowing derived classes to customize how the value property is read. + /// + /// + /// Thrown if the JSON data is invalid or cannot be deserialized into a . + /// + protected override QuantityValue ReadValueProperty(ref Utf8JsonReader reader, JsonSerializerOptions options) + { + QuantityValue value = JsonSerializer.Deserialize(ref reader, options); + return value; + } + + /// + /// Reads the unit property from the JSON input. + /// + /// + /// The used to read the JSON input. + /// + /// + /// The that specify options for deserialization. + /// + /// + /// The deserialized unit of type , or null if the unit could not be read. + /// + /// + /// Thrown if the JSON input is invalid or does not contain a valid unit property. + /// + protected override TUnit? ReadUnitProperty(ref Utf8JsonReader reader, JsonSerializerOptions options) + { + TUnit? unit = JsonSerializer.Deserialize(ref reader, options); + return unit; + } + + /// + /// Writes the "Value" property of the quantity to the JSON output. + /// + /// + /// The used to write the JSON output. + /// + /// + /// The quantity whose "Value" property is being written. + /// + /// + /// The that specify options for JSON serialization. + /// + protected override void WriteValueProperty(Utf8JsonWriter writer, TQuantity quantity, JsonSerializerOptions options) + { + JsonSerializer.Serialize(writer, quantity.Value, options); + } + + /// + /// Writes the unit property of the quantity to the JSON output. + /// + /// + /// The used to write the JSON output. + /// + /// + /// The quantity whose unit property is being written. + /// + /// + /// The that specify options for JSON serialization. + /// + /// + /// This method writes the unit property name and its value to the JSON output. + /// The property name is determined by the if specified, + /// otherwise it defaults to the value of UnitPropertyName. + /// + protected override void WriteUnitProperty(Utf8JsonWriter writer, TQuantity quantity, JsonSerializerOptions options) + { + JsonSerializer.Serialize(writer, quantity.Unit, options); + } +} + +/// +/// Provides a factory for creating JSON converters that handle serialization and deserialization +/// of quantities and their associated units. +/// +/// +/// This class leverages the to resolve quantity and unit information +/// during JSON serialization and deserialization. +/// +/// In order to use this converter directly, you need to make sure that the +/// contains a converter for both the and the +/// of the quantity. +/// +/// +#if NET +[RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")] +[RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] +#endif +public class JsonQuantityConverter : JsonConverterFactory +{ + private readonly QuantityInfoLookup _quantities; + + /// + /// Initializes a new instance of the class + /// with an option to specify case sensitivity. + /// + /// + /// This constructor uses the default from + /// to resolve unit names during JSON serialization and deserialization. + /// + public JsonQuantityConverter() + : this(UnitsNetSetup.Default.Quantities) + { + } + + /// + /// Initializes a new instance of the class with the specified + /// and case-sensitivity configuration. + /// + /// + /// The instance used to resolve quantity and unit information + /// during JSON serialization and deserialization. + /// + /// + /// This constructor allows customization of the used for parsing and + /// formatting unit names, enabling advanced scenarios where specific quantity and unit information is required. + /// + public JsonQuantityConverter(QuantityInfoLookup quantities) + { + _quantities = quantities ?? throw new ArgumentNullException(nameof(quantities)); + } + + /// + public override bool CanConvert(Type typeToConvert) + { + return TryGetQuantityInfo(typeToConvert, out _); + } + + /// + public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + if (!TryGetQuantityInfo(typeToConvert, out QuantityInfo? quantityInfo)) + { + return null; + } + + Type converterType = typeof(JsonQuantityConverter<,>).MakeGenericType(typeToConvert, quantityInfo.UnitType); + return (JsonConverter?)Activator.CreateInstance(converterType, quantityInfo); + } + + /// + /// Try to get the for a given quantity type. + /// + protected bool TryGetQuantityInfo(Type typeToConvert, [NotNullWhen(true)] out QuantityInfo? quantityInfo) + { + return _quantities.TryGetQuantityInfo(typeToConvert, out quantityInfo); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson/Unit/AbbreviatedUnitConverter.cs b/UnitsNet.Serialization.SystemTextJson/Unit/AbbreviatedUnitConverter.cs new file mode 100644 index 0000000000..d39e879715 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson/Unit/AbbreviatedUnitConverter.cs @@ -0,0 +1,173 @@ +// 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.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; +#if NET +using System.Diagnostics.CodeAnalysis; +#endif + +namespace UnitsNet.Serialization.SystemTextJson.Unit; + +/// +/// Converter to convert unit-enums to and from abbreviated strings. +/// +/// +/// Reading is case-insensitive, with case-sensitive disambiguation. +/// +#if NET +[RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")] +[RequiresUnreferencedCode( + "If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] +#endif +public class AbbreviatedUnitConverter : JsonConverterFactory +{ + private readonly UnitParser _unitParser; + private readonly CultureInfo _culture = CultureInfo.InvariantCulture; + + /// + /// Initializes a new instance of the class + /// using the default . + /// + /// + /// This constructor sets up the converter to use the default + /// for resolving unit abbreviations during JSON serialization and deserialization. + /// + public AbbreviatedUnitConverter() + : this(UnitParser.Default) + { + } + + /// + /// Initializes a new instance of the class with the specified unit parser. + /// + /// + /// The used for deserializing an abbreviation back into its + /// corresponding unit. + /// + /// + /// This constructor sets up the converter to utilize the provided + /// for managing unit abbreviations and parsing during JSON operations. + /// + public AbbreviatedUnitConverter(UnitParser unitParser) + { + _unitParser = unitParser ?? throw new ArgumentNullException(nameof(unitParser)); + } + + /// + /// Initializes a new instance of the class with the specified unit parser and culture. + /// + /// + /// The used for deserializing an abbreviation back into its + /// corresponding unit. + /// + /// The used for parsing and formatting unit abbreviations. + /// + /// This constructor allows customization of both the unit abbreviations cache and the culture used for parsing and + /// formatting unit abbreviations. + /// + public AbbreviatedUnitConverter(UnitParser unitParser, CultureInfo culture) + { + _unitParser = unitParser ?? throw new ArgumentNullException(nameof(unitParser)); + _culture = culture ?? throw new ArgumentNullException(nameof(culture)); + } + + /// + public sealed override bool CanConvert(Type typeToConvert) + { + return _unitParser.Quantities.TryGetQuantityByUnitType(typeToConvert, out _); + } + + /// + public sealed override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + // QuantityInfo quantityInfo = _unitParser.Quantities.GetQuantityByUnitType(typeToConvert); + Type converterType = typeof(AbbreviatedUnitConverter<>).MakeGenericType(typeToConvert); + return (JsonConverter?)Activator.CreateInstance(converterType, _unitParser, _culture); + } +} + +/// +/// Converter to convert unit-enums to and from abbreviated strings. +/// +/// +/// Reading is case-insensitive, with case-sensitive disambiguation. +/// +public class AbbreviatedUnitConverter : JsonConverter where TUnit : struct, Enum +{ + private readonly UnitParser _unitParser; + private readonly CultureInfo _culture = CultureInfo.InvariantCulture; + + /// + /// Initializes a new instance of the class + /// using the default . + /// + /// + /// This constructor sets up the converter to use the default + /// for resolving unit abbreviations during JSON serialization and deserialization. + /// + public AbbreviatedUnitConverter() + : this(UnitParser.Default) + { + } + + /// + /// Initializes a new instance of the class with the specified unit parser. + /// + /// + /// The used for deserializing an abbreviation back into its + /// corresponding unit. + /// + /// + /// This constructor sets up the converter to utilize the provided + /// for managing unit abbreviations and parsing during JSON operations. + /// + public AbbreviatedUnitConverter(UnitParser unitParser) + { + _unitParser = unitParser ?? throw new ArgumentNullException(nameof(unitParser)); + } + + /// + /// Initializes a new instance of the class with the specified unit parser and culture. + /// + /// + /// The used for deserializing an abbreviation back into its + /// corresponding unit. + /// + /// The used for parsing and formatting unit abbreviations. + /// + /// This constructor allows customization of both the unit abbreviations cache and the culture used for parsing and + /// formatting unit abbreviations. + /// + public AbbreviatedUnitConverter(UnitParser unitParser, CultureInfo culture) + { + _unitParser = unitParser ?? throw new ArgumentNullException(nameof(unitParser)); + _culture = culture ?? throw new ArgumentNullException(nameof(culture)); + } + + /// + public override TUnit Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return _unitParser.Parse(reader.GetString()!, _culture); + } + + /// + public override TUnit ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return Read(ref reader, typeToConvert, options); + } + + /// + public override void Write(Utf8JsonWriter writer, TUnit value, JsonSerializerOptions options) + { + var abbreviation = _unitParser.Abbreviations.GetDefaultAbbreviation(value, _culture); + writer.WriteStringValue(abbreviation); + } + + /// + public override void WriteAsPropertyName(Utf8JsonWriter writer, TUnit value, JsonSerializerOptions options) + { + writer.WritePropertyName(_unitParser.Abbreviations.GetDefaultAbbreviation(value, _culture)); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson/Unit/UnitTypeAndNameConverter.cs b/UnitsNet.Serialization.SystemTextJson/Unit/UnitTypeAndNameConverter.cs new file mode 100644 index 0000000000..e0297d98fb --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson/Unit/UnitTypeAndNameConverter.cs @@ -0,0 +1,203 @@ +// 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.Text.Json; +using System.Text.Json.Serialization; +#if NET +using System.Text; +using System.Diagnostics.CodeAnalysis; +#endif + +namespace UnitsNet.Serialization.SystemTextJson.Unit; + +/// +/// Provides functionality for converting units of a specific type to and from their string representations +/// in JSON serialization and deserialization processes. +/// +/// +/// This converter uses the corresponding to the given unit in the provided +/// . +/// It supports case-sensitive or case-insensitive comparisons based on the specified configuration. +/// +/// +/// +#if NET +[RequiresDynamicCode("The native code for this instantiation might not be available at runtime.")] +[RequiresUnreferencedCode("If some of the generic arguments are annotated (either with DynamicallyAccessedMembersAttribute, or generic constraints), trimming can't validate that the requirements of those annotations are met.")] +#endif +public class UnitTypeAndNameConverter : JsonConverterFactory +{ + private readonly bool _ignoreCase; + private readonly QuantityInfoLookup _quantities; + + /// + /// Initializes a new instance of the class with case-sensitive unit matching. + /// + /// + /// This constructor uses the default from + /// to resolve unit names during JSON serialization and deserialization. + /// + public UnitTypeAndNameConverter() + : this(UnitsNetSetup.Default.Quantities) + { + } + + /// + /// Initializes a new instance of the class + /// with an option to specify case sensitivity. + /// + /// + /// This constructor uses the default from + /// to resolve unit names during JSON serialization and deserialization. + /// + public UnitTypeAndNameConverter(bool ignoreCase) + : this(UnitsNetSetup.Default.Quantities, ignoreCase) + { + } + + /// + /// Initializes a new instance of the class with the specified + /// and an option to specify case sensitivity. + /// + /// + /// The instance used to resolve quantity and unit information + /// during JSON serialization and deserialization. + /// + /// + /// A boolean value indicating whether the unit name comparison should ignore case during JSON serialization and + /// deserialization. + /// + /// + /// This constructor allows customization of the used for parsing and + /// formatting unit names, enabling advanced scenarios where specific quantity and unit information is required. + /// + public UnitTypeAndNameConverter(QuantityInfoLookup quantities, bool ignoreCase = false) + { + _quantities = quantities; + _ignoreCase = ignoreCase; + } + + /// + public sealed override bool CanConvert(Type typeToConvert) + { + return _quantities.TryGetQuantityByUnitType(typeToConvert, out _); + } + + /// + public sealed override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) + { + QuantityInfo quantityInfo = _quantities.GetQuantityByUnitType(typeToConvert); + Type converterType = typeof(UnitTypeAndNameConverter<>).MakeGenericType(typeToConvert); + return (JsonConverter?)Activator.CreateInstance(converterType, quantityInfo, _ignoreCase); + } +} + +/// +/// Provides functionality for converting units of a specific type to and from their string representations +/// in JSON serialization and deserialization processes. +/// +/// +/// The type of the unit being converted, which must be a struct and an enumeration. +/// +/// +/// This converter uses the corresponding to the given unit in the +/// provided . +/// It supports case-sensitive or case-insensitive comparisons based on the specified configuration. +/// +/// +/// +public class UnitTypeAndNameConverter : JsonConverter where TUnit : struct, Enum +{ + private const int StackAllocThreshold = 512; + + private readonly bool _ignoreCase; + private readonly QuantityInfo _quantityInfo; + + /// + /// Initializes a new instance of the class with the specified + /// quantity information and an option to configure case sensitivity for unit name comparisons. + /// + /// + /// The quantity information that provides metadata about the unit type, including unit abbreviations and the base + /// unit. + /// + /// + /// A boolean value indicating whether the unit name comparison should ignore case during JSON serialization and + /// deserialization. + /// + /// + /// Thrown when is null. + /// + public UnitTypeAndNameConverter(QuantityInfo quantityInfo, bool ignoreCase = false) + { + _quantityInfo = quantityInfo ?? throw new ArgumentNullException(nameof(quantityInfo)); + _ignoreCase = ignoreCase; + } + + /// + public override TUnit Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var nbBytes = reader.HasValueSequence ? checked((int)reader.ValueSequence.Length) : reader.ValueSpan.Length; + Span charBuffer = nbBytes <= StackAllocThreshold ? stackalloc char[nbBytes] : new char[nbBytes]; + var charsWritten = reader.CopyString(charBuffer); + ReadOnlySpan unitSpan = charBuffer.Slice(0, charsWritten); + if (!unitSpan.TrySplit('.', out _, out ReadOnlySpan unitName)) + { +#if NET + throw new JsonException($"Invalid unit format: \"{unitSpan}\""); +#else + throw new JsonException($"Invalid unit format: \"{unitSpan.ToString()}\""); +#endif + } + + IReadOnlyList> unitInfos = _quantityInfo.UnitInfos; + var nbUnits = unitInfos.Count; + if (_ignoreCase) + { + for (var i = 0; i < nbUnits; i++) + { + UnitInfo unitInfo = unitInfos[i]; + if (unitName.Equals(unitInfo.Name.AsSpan(), StringComparison.OrdinalIgnoreCase)) + { + return unitInfo.Value; + } + } + } + else + { + // TODO see if we want to also validate the first part of the format + for (var i = 0; i < nbUnits; i++) + { + UnitInfo unitInfo = unitInfos[i]; + if (unitName.SequenceEqual(unitInfo.Name.AsSpan())) + { + return unitInfo.Value; + } + } + } + + var unitNamePart = unitName.ToString(); + throw new UnitNotFoundException($"No unit was found for quantity '{_quantityInfo.Name}' with the name: '{unitNamePart}'.") + { + Data = { ["quantityName"] = _quantityInfo.Name, ["unitName"] = unitNamePart } + }; + } + + /// + public override TUnit ReadAsPropertyName(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return Read(ref reader, typeToConvert, options); + } + + /// + public override void Write(Utf8JsonWriter writer, TUnit value, JsonSerializerOptions options) + { + writer.WriteStringValues(typeof(TUnit).Name.AsSpan(), '.', _quantityInfo[value].Name.AsSpan()); + } + + /// + public override void WriteAsPropertyName(Utf8JsonWriter writer, TUnit value, JsonSerializerOptions options) + { + writer.WriteValuesAsPropertyName(typeof(TUnit).Name.AsSpan(), '.', _quantityInfo[value].Name.AsSpan()); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson/UnitsNet.Serialization.SystemTextJson.csproj b/UnitsNet.Serialization.SystemTextJson/UnitsNet.Serialization.SystemTextJson.csproj new file mode 100644 index 0000000000..d17a6cb66a --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson/UnitsNet.Serialization.SystemTextJson.csproj @@ -0,0 +1,54 @@ + + + + UnitsNet.Serialization.SystemTextJson + 6.0.0-pre018 + Andreas Gullberg Larsen + Units.NET Serialization with System.Text.Json + A helper library for serializing and deserializing types in Units.NET using System.Text.Json. + Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). + true + https://github.com/angularsen/UnitsNet + logo-32.png + https://raw.githubusercontent.com/angularsen/UnitsNet/ce85185429be345d77eb2ce09c99d59cc9ab8aed/Docs/Images/logo-32.png + https://github.com/angularsen/UnitsNet + MIT-0 + false + unit units measurement json System.Text.Json serialize deserialize serialization deserialization + Upgrade JSON.NET to 12.0.3. Support arrays. + true + + + + + 6.0.0.0 + latest + enable + enable + UnitsNet.Serialization.SystemTextJson + netstandard2.0;net8.0;net9.0 + + + + + ../UnitsNet.snk + false + true + + + + + + + + + + + + + + + + + + diff --git a/UnitsNet.Serialization.SystemTextJson/Value/BigIntegerConverter.cs b/UnitsNet.Serialization.SystemTextJson/Value/BigIntegerConverter.cs new file mode 100644 index 0000000000..9dd680b5d1 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson/Value/BigIntegerConverter.cs @@ -0,0 +1,120 @@ +// 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.Globalization; +using System.Numerics; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +#if NETSTANDARD2_0 +using System.Buffers; +#endif + +namespace UnitsNet.Serialization.SystemTextJson.Value; + +/// +/// Provides a custom JSON converter for . +/// This converter serializes values as JSON strings +/// and deserializes JSON strings back into values. +/// +public class BigIntegerConverter : JsonConverter +{ + /// + /// Gets the default instance of the . + /// + /// + /// This instance can be used as a singleton for converting + /// values to and from JSON without the need to create a new instance of . + /// + public static BigIntegerConverter Default { get; } = new(); + + /// + public override BigInteger Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + switch (reader.TokenType) + { + case JsonTokenType.Number: + { +#if NET + var nbBytes = reader.HasValueSequence ? checked((int)reader.ValueSequence.Length) : reader.ValueSpan.Length; + Span charBuffer = nbBytes <= 512 ? stackalloc char[nbBytes] : new char[nbBytes]; + var charsWritten = reader.HasValueSequence + ? Encoding.UTF8.GetChars(reader.ValueSequence, charBuffer) + : Encoding.UTF8.GetChars(reader.ValueSpan, charBuffer); + return BigInteger.Parse(charBuffer[..charsWritten], CultureInfo.InvariantCulture); +#else + var bytes = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan.ToArray(); + var charBuffer = new char[bytes.Length]; + var charsWritten = Encoding.UTF8.GetChars(bytes, 0, bytes.Length, charBuffer, 0); + return BigInteger.Parse(new string(charBuffer, 0, charsWritten), CultureInfo.InvariantCulture); +#endif + } + case JsonTokenType.String: + { + if ((options.NumberHandling & JsonNumberHandling.AllowReadingFromString) == 0) + { + throw new JsonException( + "String tokens are not supported with the current `NumberHandling` settings. Consider specifying 'JsonNumberHandling.AllowReadingFromString' (see https://learn.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling)"); + } + +#if NET + var nbBytes = reader.HasValueSequence ? checked((int)reader.ValueSequence.Length) : reader.ValueSpan.Length; + Span charBuffer = nbBytes <= 512 ? stackalloc char[nbBytes] : new char[nbBytes]; + var charsWritten = reader.CopyString(charBuffer); + return BigInteger.Parse(charBuffer[..charsWritten], CultureInfo.InvariantCulture); +#else + return BigInteger.Parse(reader.GetString()!, CultureInfo.InvariantCulture); +#endif + } + case JsonTokenType.None: + case JsonTokenType.StartObject: + case JsonTokenType.EndObject: + case JsonTokenType.StartArray: + case JsonTokenType.EndArray: + case JsonTokenType.PropertyName: + case JsonTokenType.Comment: + case JsonTokenType.True: + case JsonTokenType.False: + case JsonTokenType.Null: + default: + throw new JsonException($"Unexpected token type: {reader.TokenType}"); + } + } + + /// + public override void Write(Utf8JsonWriter writer, BigInteger value, JsonSerializerOptions options) + { + if ((options.NumberHandling & JsonNumberHandling.WriteAsString) == 0) + { +#if NET + Span charBuffer = stackalloc char[512]; + if (value.TryFormat(charBuffer, out var charsWritten, provider: NumberFormatInfo.InvariantInfo)) + { + writer.WriteRawValue(charBuffer[..charsWritten], true); + } + else // the number did not fit into the buffer + { + writer.WriteRawValue(value.ToString(NumberFormatInfo.InvariantInfo), true); + } +#else + writer.WriteRawValue(value.ToString(NumberFormatInfo.InvariantInfo), true); +#endif + } + else + { +#if NET + Span charBuffer = stackalloc char[512]; + if (value.TryFormat(charBuffer, out var charsWritten, provider: NumberFormatInfo.InvariantInfo)) + { + writer.WriteStringValue(charBuffer[..charsWritten]); + } + else // the number did not fit into the buffer + { + writer.WriteStringValue(value.ToString(NumberFormatInfo.InvariantInfo)); + } +#else + writer.WriteStringValue(value.ToString(NumberFormatInfo.InvariantInfo)); +#endif + } + } +} diff --git a/UnitsNet.Serialization.SystemTextJson/Value/QuantityValueDecimalConverter.cs b/UnitsNet.Serialization.SystemTextJson/Value/QuantityValueDecimalConverter.cs new file mode 100644 index 0000000000..c9c25dcea7 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson/Value/QuantityValueDecimalConverter.cs @@ -0,0 +1,86 @@ +// 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.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace UnitsNet.Serialization.SystemTextJson.Value; + +/// +/// A JSON converter for that serializes and deserializes values using the decimal type. +/// +/// +/// This converter is tailored for handling objects, ensuring precise serialization and +/// deserialization with support for arbitrary scale and precision. The value is written and read as a regular decimal, +/// with overflow behavior when the number exceeds the range of a decimal. Additionally, it supports +/// options, including reading and writing from strings and handling named floating-point literals. +/// +public class QuantityValueDecimalConverter : JsonConverter +{ + /// + public override QuantityValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + decimal value; + if (reader.TokenType == JsonTokenType.String) + { + var stringValue = reader.GetString()!; + CultureInfo culture = CultureInfo.InvariantCulture; + // TODO see if we want to support the named literals + if ((options.NumberHandling & JsonNumberHandling.AllowNamedFloatingPointLiterals) != 0) + { + if (stringValue == culture.NumberFormat.NaNSymbol) + { + return QuantityValue.NaN; + } + + if (stringValue == culture.NumberFormat.PositiveInfinitySymbol) + { + return QuantityValue.PositiveInfinity; + } + + if (stringValue == culture.NumberFormat.NegativeInfinitySymbol) + { + return QuantityValue.NegativeInfinity; + } + } + + if ((options.NumberHandling & JsonNumberHandling.AllowReadingFromString) == 0) + { + throw new JsonException( + "String tokens are not supported with the current `NumberHandling` settings. Consider specifying 'JsonNumberHandling.AllowReadingFromString' (see https://learn.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling)"); + } + + value = decimal.Parse(stringValue, culture); + } + else + { + value = reader.GetDecimal(); + } + + return new QuantityValue(value); + } + + /// + public override void Write(Utf8JsonWriter writer, QuantityValue value, JsonSerializerOptions options) + { + if ((options.NumberHandling & JsonNumberHandling.WriteAsString) != 0) + { + writer.WriteStringValue(value.ToDecimal().ToString(CultureInfo.InvariantCulture)); + } + else if (QuantityValue.IsNaN(value) || QuantityValue.IsInfinity(value)) + { + if ((options.NumberHandling & JsonNumberHandling.AllowNamedFloatingPointLiterals) == 0) + { + throw new JsonException( + $"Serializing '{value}' is not allowed. Consider specifying 'JsonNumberHandling.AllowNamedFloatingPointLiterals' (see https://learn.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling)"); + } + + writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture)); + } + else + { + writer.WriteNumberValue(value.ToDecimal()); + } + } +} diff --git a/UnitsNet.Serialization.SystemTextJson/Value/QuantityValueDecimalNotationConverter.cs b/UnitsNet.Serialization.SystemTextJson/Value/QuantityValueDecimalNotationConverter.cs new file mode 100644 index 0000000000..83104bac1f --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson/Value/QuantityValueDecimalNotationConverter.cs @@ -0,0 +1,180 @@ +// 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.Globalization; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +#if NETSTANDARD2_0 +using System.Buffers; +#endif + +namespace UnitsNet.Serialization.SystemTextJson.Value; + +/// +/// Provides functionality to convert instances to and from their JSON representation +/// using decimal notation, which supports arbitrary scale and precision. +/// +/// +/// This converter is designed to handle serialization and deserialization of objects +/// using decimal notation. A configurable maximum number of significant digits, corresponding to the `G` format +/// specifier, can be used to control the precision of the serialized output. +/// +/// While this converter supports arbitrary precision, without any limits on the scale, it should be noted that +/// the serialized payload may fall outside the capabilities of the standard numeric types. +/// +/// Values such as 1/3 cannot be represented exactly. +/// +public class QuantityValueDecimalNotationConverter : JsonConverter +{ + private const int StackAllocThreshold = 512; + + private readonly string _serializationFormat; + + /// + /// Initializes a new instance of the class + /// with a default maximum number of significant digits set to 17. + /// + /// + /// This constructor simplifies the creation of the converter by using a default precision of 17 significant digits, + /// which corresponds to the `G17` format specifier. + /// + public QuantityValueDecimalNotationConverter() + : this(17) + { + } + + /// + /// Initializes a new instance of the class with an optional + /// maximum number of significant digits for serialization. + /// + /// + /// The maximum number of significant digits to use during serialization. + /// + /// + /// Thrown when is less than 0. + /// + /// + /// This constructor allows configuring the precision of the serialized output by specifying the maximum + /// number of significant digits, which corresponds to the `G` format specifier. + /// + public QuantityValueDecimalNotationConverter(int maxNumberOfSignificantDigits) + { + if (maxNumberOfSignificantDigits < 0) + { + throw new ArgumentOutOfRangeException(nameof(maxNumberOfSignificantDigits), "The number of significant digits must greater or equal to 0."); + } + + _serializationFormat = "G" + maxNumberOfSignificantDigits; + } + + /// + public override QuantityValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + switch (reader.TokenType) + { + case JsonTokenType.Number: + { +#if NET + var nbBytes = reader.HasValueSequence ? checked((int)reader.ValueSequence.Length) : reader.ValueSpan.Length; + Span charBuffer = nbBytes <= StackAllocThreshold ? stackalloc char[nbBytes] : new char[nbBytes]; + var charsWritten = reader.HasValueSequence + ? Encoding.UTF8.GetChars(reader.ValueSequence, charBuffer) + : Encoding.UTF8.GetChars(reader.ValueSpan, charBuffer); + return QuantityValue.Parse(charBuffer[..charsWritten], NumberStyles.Float, CultureInfo.InvariantCulture); +#else + var bytes = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan.ToArray(); + var charBuffer = new char[bytes.Length]; + var charsWritten = Encoding.UTF8.GetChars(bytes, 0, bytes.Length, charBuffer, 0); + return QuantityValue.Parse(new string(charBuffer, 0, charsWritten), NumberStyles.Float, CultureInfo.InvariantCulture); +#endif + } + case JsonTokenType.String: + { + if ((options.NumberHandling & (JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.AllowNamedFloatingPointLiterals)) == 0) + { + throw new JsonException( + "String tokens are not supported with the current `NumberHandling` settings. Consider specifying 'JsonNumberHandling.AllowReadingFromString' (see https://learn.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling)"); + } + + var nbBytes = reader.HasValueSequence ? checked((int)reader.ValueSequence.Length) : reader.ValueSpan.Length; + Span charBuffer = nbBytes <= StackAllocThreshold ? stackalloc char[nbBytes] : new char[nbBytes]; + var charsWritten = reader.CopyString(charBuffer); +#if NET + return QuantityValue.Parse(charBuffer[..charsWritten], NumberStyles.Float, CultureInfo.InvariantCulture); +#else + return QuantityValue.Parse(charBuffer.Slice(0, charsWritten).ToString(), NumberStyles.Float, CultureInfo.InvariantCulture); +#endif + } + case JsonTokenType.None: + case JsonTokenType.StartObject: + case JsonTokenType.EndObject: + case JsonTokenType.StartArray: + case JsonTokenType.EndArray: + case JsonTokenType.PropertyName: + case JsonTokenType.Comment: + case JsonTokenType.True: + case JsonTokenType.False: + case JsonTokenType.Null: + default: + throw new JsonException($"Unexpected token type: {reader.TokenType}"); + } + + +// if (reader.TokenType is not (JsonTokenType.Number or JsonTokenType.String)) +// { +// throw new JsonException($"Expected a string or a number, not a {reader.TokenType}"); +// } +// +// if (reader.TokenType == JsonTokenType.String && (options.NumberHandling & (JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.AllowNamedFloatingPointLiterals)) == 0) +// { +// throw new JsonException("Reading numbers from string tokens is not allowed. Consider specifying 'JsonNumberHandling.AllowReadingFromString' (see https://learn.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling)"); +// } +// #if NET +// ReadOnlySpan bytes = reader.ValueSpan; +// var charCount = Encoding.UTF8.GetCharCount(bytes); +// Span charBuffer = charCount <= 256 ? stackalloc char[charCount] : new char[charCount]; +// Encoding.UTF8.GetChars(bytes, charBuffer); +// return QuantityValue.Parse(charBuffer, NumberStyles.Float, CultureInfo.InvariantCulture); +// #else +// var bytes = reader.ValueSpan.ToArray(); +// var charCount = Encoding.UTF8.GetCharCount(bytes); +// var charBuffer = new char[charCount]; +// Encoding.UTF8.GetChars(bytes, 0, bytes.Length, charBuffer, 0); +// return QuantityValue.Parse(new string(charBuffer), NumberStyles.Float, CultureInfo.InvariantCulture); +// #endif + } + + /// + public override void Write(Utf8JsonWriter writer, QuantityValue value, JsonSerializerOptions options) + { + if ((options.NumberHandling & JsonNumberHandling.WriteAsString) != 0) + { + writer.WriteStringValue(value.ToString(_serializationFormat, CultureInfo.InvariantCulture)); + } + else if (QuantityValue.IsNaN(value) || QuantityValue.IsInfinity(value)) + { + if ((options.NumberHandling & JsonNumberHandling.AllowNamedFloatingPointLiterals) == 0) + { + throw new JsonException($"Serializing '{value}' is not allowed. Consider specifying 'JsonNumberHandling.AllowNamedFloatingPointLiterals' (see https://learn.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling)"); + } + + writer.WriteStringValue(value.ToString(_serializationFormat, CultureInfo.InvariantCulture)); + } + else + { +#if NET + Span charBuffer = stackalloc char[256]; + int charsWritten; + while (!value.TryFormat(charBuffer, out charsWritten, _serializationFormat, CultureInfo.InvariantCulture)) + { + charBuffer = new char[charBuffer.Length * 2]; + } + + writer.WriteRawValue(charBuffer[..charsWritten], true); +#else + writer.WriteRawValue(value.ToString(_serializationFormat, CultureInfo.InvariantCulture), true); +#endif + } + } +} diff --git a/UnitsNet.Serialization.SystemTextJson/Value/QuantityValueDoubleConverter.cs b/UnitsNet.Serialization.SystemTextJson/Value/QuantityValueDoubleConverter.cs new file mode 100644 index 0000000000..47e04c09db --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson/Value/QuantityValueDoubleConverter.cs @@ -0,0 +1,110 @@ +// 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.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace UnitsNet.Serialization.SystemTextJson.Value; + +/// +/// Provides functionality to convert instances to and from their JSON representation +/// using double-precision floating-point notation. +/// +/// +/// This converter is designed to handle serialization and deserialization of objects +/// using double-precision floating-point notation. The configurable maximum number of significant digits is only +/// applied during deserialization to control the precision of the parsed input. +/// +/// Additionally, this converter supports the option for writing +/// numeric values as strings during serialization, and the +/// +/// option for deserializing named floating-point literals such as "NaN", "Infinity", and "-Infinity". +/// +/// +public class QuantityValueDoubleConverter : JsonConverter +{ + private readonly byte _maxNumberOfSignificantDigits; + + /// + /// Initializes a new instance of the class + /// with a default maximum number of significant digits set to 15. + /// + /// + /// This constructor simplifies the creation of the converter by using a default serialization precision of 15 + /// significant digits. + /// + public QuantityValueDoubleConverter() + : this(15) + { + } + + /// + /// Initializes a new instance of the class with an optional + /// maximum number of significant digits for serialization. + /// + /// + /// The maximum number of significant digits to use during serialization. + /// + /// + /// Thrown when the number of significant digits is less than 1 or greater than 17. + /// + /// + /// This constructor allows configuring the precision of the precision used when converting from double. + /// + public QuantityValueDoubleConverter(byte maxNumberOfSignificantDigits) + { + if (maxNumberOfSignificantDigits is < 1 or > 17) + { + throw new ArgumentOutOfRangeException(nameof(maxNumberOfSignificantDigits), maxNumberOfSignificantDigits, + "The maximum number of significant digits must be between 1 and 17."); + } + + _maxNumberOfSignificantDigits = maxNumberOfSignificantDigits; + } + + /// + public override QuantityValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + double value; + if (reader.TokenType == JsonTokenType.String) + { + if ((options.NumberHandling & (JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.AllowNamedFloatingPointLiterals)) == 0) + { + throw new JsonException( + "String tokens are not supported with the current `NumberHandling` settings. Consider specifying 'JsonNumberHandling.AllowReadingFromString' (see https://learn.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling)"); + } + + value = double.Parse(reader.GetString()!, CultureInfo.InvariantCulture); + } + else + { + value = reader.GetDouble(); + } + + return QuantityValue.FromDoubleRounded(value, _maxNumberOfSignificantDigits); + } + + /// + public override void Write(Utf8JsonWriter writer, QuantityValue value, JsonSerializerOptions options) + { + if ((options.NumberHandling & JsonNumberHandling.WriteAsString) != 0) + { + writer.WriteStringValue(value.ToString("R", CultureInfo.InvariantCulture)); + } + else if (QuantityValue.IsNaN(value) || QuantityValue.IsInfinity(value)) + { + if ((options.NumberHandling & JsonNumberHandling.AllowNamedFloatingPointLiterals) == 0) + { + throw new JsonException( + $"Serializing '{value}' is not allowed. Consider specifying 'JsonNumberHandling.AllowNamedFloatingPointLiterals' (see https://learn.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling)"); + } + + writer.WriteStringValue(value.ToString(CultureInfo.InvariantCulture)); + } + else + { + writer.WriteNumberValue(value.ToDouble()); + } + } +} diff --git a/UnitsNet.Serialization.SystemTextJson/Value/QuantityValueFractionalNotationConverter.cs b/UnitsNet.Serialization.SystemTextJson/Value/QuantityValueFractionalNotationConverter.cs new file mode 100644 index 0000000000..cb4deba6b3 --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson/Value/QuantityValueFractionalNotationConverter.cs @@ -0,0 +1,227 @@ +// 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.Numerics; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace UnitsNet.Serialization.SystemTextJson.Value; + +/// +/// Provides functionality for serializing and deserializing objects +/// to and from JSON format. +/// +/// +/// This converter handles the serialization and deserialization of objects +/// by utilizing a custom for values. +/// It ensures that the numerator and denominator properties of are +/// properly processed during JSON operations. +/// +public class QuantityValueFractionalNotationConverter : JsonConverter +{ + private static readonly JsonEncodedText PropName_Numerator = JsonEncodedText.Encode("N"); + private static readonly JsonEncodedText PropName_Numerator_Lowercase = JsonEncodedText.Encode("n"); + + private static readonly JsonEncodedText PropName_Denominator = JsonEncodedText.Encode("D"); + private static readonly JsonEncodedText PropName_Denominator_Lowercase = JsonEncodedText.Encode("d"); + + private readonly JsonConverter _bigIntegerConverter; + private readonly bool _reduceTerms; + + /// + /// Initializes a new instance of the class + /// with default settings. + /// + /// + /// This constructor sets up the converter to handle the serialization and deserialization + /// of objects in JSON format, using default behavior. + /// + public QuantityValueFractionalNotationConverter() + : this(false) + { + } + + /// + /// Initializes a new instance of the class + /// with the default configuration. + /// + /// + /// This constructor sets up the converter with default settings, where terms are not reduced + /// during serialization and deserialization. + /// + public QuantityValueFractionalNotationConverter(bool reduceTerms) + : this(BigIntegerConverter.Default, reduceTerms) + { + } + + /// + /// Initializes a new instance of the class + /// with the specified for values and an option + /// to reduce terms during serialization. + /// + /// + /// The used to handle serialization and deserialization of + /// values. + /// + /// + /// A boolean value indicating whether the terms should be reduced before serializing. + /// + /// + /// Thrown when the is null. + /// + public QuantityValueFractionalNotationConverter(JsonConverter bigIntegerConverter, bool reduceTerms = false) + { + _bigIntegerConverter = bigIntegerConverter ?? throw new ArgumentNullException(nameof(bigIntegerConverter)); + _reduceTerms = reduceTerms; + } + + /// + /// Gets the default instance of the . + /// + /// + /// This property provides a pre-configured, shared instance of the converter + /// with default settings, simplifying the serialization and deserialization + /// of objects in JSON format. + /// + public static QuantityValueFractionalNotationConverter Default { get; } = new(); + + /// + /// Gets an instance of configured to reduce terms + /// during serialization and deserialization. + /// + /// + /// This property provides a pre-configured converter that simplifies fractional representations + /// by reducing the numerator and denominator to their smallest terms. + /// + public static QuantityValueFractionalNotationConverter Reducing { get; } = new(true); + + /// + public override QuantityValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType != JsonTokenType.StartObject) + { + throw new JsonException("Expected StartObject token."); + } + + BigInteger? numerator = null; + BigInteger? denominator = null; + JsonEncodedText numeratorProperty, denominatorProperty; + if (options.PropertyNamesShouldStartWithLowercase()) + { + numeratorProperty = PropName_Numerator_Lowercase; + denominatorProperty = PropName_Denominator_Lowercase; + } + else + { + numeratorProperty = PropName_Numerator; + denominatorProperty = PropName_Denominator; + } + + if (options.PropertyNameCaseInsensitive) + { + while (reader.ReadNextProperty()) + { + var propertyName = reader.GetString(); + reader.Read(); + if (StringComparer.OrdinalIgnoreCase.Equals(propertyName, numeratorProperty.Value)) + { + numerator = _bigIntegerConverter.Read(ref reader, typeof(BigInteger), options); + } + else if (StringComparer.OrdinalIgnoreCase.Equals(propertyName, denominatorProperty.Value)) + { + denominator = _bigIntegerConverter.Read(ref reader, typeof(BigInteger), options); + } + else if (options.UnmappedMemberHandling == JsonUnmappedMemberHandling.Skip) + { + reader.Skip(); // Skip unknown properties + } + else + { + throw new JsonException($"'{propertyName}' was no found in the list of members of '{typeToConvert}'."); + } + } + } + else + { + while (reader.ReadNextProperty()) + { + if (reader.ValueTextEquals(numeratorProperty.EncodedUtf8Bytes)) + { + reader.Read(); + numerator = _bigIntegerConverter.Read(ref reader, typeof(BigInteger), options); + } + else if (reader.ValueTextEquals(denominatorProperty.EncodedUtf8Bytes)) + { + reader.Read(); + denominator = _bigIntegerConverter.Read(ref reader, typeof(BigInteger), options); + } + else if (options.UnmappedMemberHandling == JsonUnmappedMemberHandling.Skip) + { + reader.Skip(); // Skip unknown properties + } + else + { + throw new JsonException($"'{reader.GetString()}' was no found in the list of members of '{typeToConvert}'."); + } + } + } + + if (numerator.HasValue && denominator.HasValue) + { + return QuantityValue.FromTerms(numerator.Value, denominator.Value); + } + + if (numerator.HasValue) + { + return numerator.Value; + } + + return denominator.HasValue ? QuantityValue.FromTerms(BigInteger.Zero, denominator.Value) : QuantityValue.Zero; + } + + /// + public override void Write(Utf8JsonWriter writer, QuantityValue value, JsonSerializerOptions options) + { + writer.WriteStartObject(); + + (BigInteger numerator, BigInteger denominator) = _reduceTerms ? QuantityValue.Reduce(value) : value; + JsonEncodedText numeratorProperty, denominatorProperty; + if (options.PropertyNamesShouldStartWithLowercase()) + { + numeratorProperty = PropName_Numerator_Lowercase; + denominatorProperty = PropName_Denominator_Lowercase; + } + else + { + numeratorProperty = PropName_Numerator; + denominatorProperty = PropName_Denominator; + } + + if (options.DefaultIgnoreCondition == JsonIgnoreCondition.WhenWritingDefault) + { + // Write only if the property is non-default. + if (!numerator.IsZero) + { + WriteBigInteger(writer, options, numeratorProperty, numerator); + } + + if (!denominator.IsOne) + { + WriteBigInteger(writer, options, denominatorProperty, denominator); + } + } + else // For example, when DefaultIgnoreCondition is Never. + { + WriteBigInteger(writer, options, numeratorProperty, numerator); + WriteBigInteger(writer, options, denominatorProperty, denominator); + } + + writer.WriteEndObject(); + } + + private void WriteBigInteger(Utf8JsonWriter writer, JsonSerializerOptions options, JsonEncodedText propertyName, BigInteger value) + { + writer.WritePropertyName(propertyName); + _bigIntegerConverter.Write(writer, value, options); + } +} diff --git a/UnitsNet.Serialization.SystemTextJson/Value/QuantityValueMixedNotationConverter.cs b/UnitsNet.Serialization.SystemTextJson/Value/QuantityValueMixedNotationConverter.cs new file mode 100644 index 0000000000..3c30d7655a --- /dev/null +++ b/UnitsNet.Serialization.SystemTextJson/Value/QuantityValueMixedNotationConverter.cs @@ -0,0 +1,306 @@ +// 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.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Numerics; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; +#if NETSTANDARD2_0 +using System.Buffers; +#endif + +namespace UnitsNet.Serialization.SystemTextJson.Value; + +/// +/// Provides a custom JSON converter for serializing and deserializing objects +/// using mixed notation, supporting both fractional and decimal representations. +/// +/// +/// This converter ensures that any can round-trip exactly during serialization +/// and deserialization, even for values like 1/3 that cannot be represented precisely as a finite decimal. +/// For values with a finite decimal expansion, the shorter and more readable decimal format is used. +/// +[SuppressMessage("ReSharper", "ReplaceSliceWithRangeIndexer")] +public class QuantityValueMixedNotationConverter : JsonConverter +{ + private const int StackAllocThreshold = 512; + + /// + /// Gets the default instance of the . + /// + /// + /// This property provides a pre-configured, shared instance of the converter + /// with default settings, simplifying the serialization and deserialization + /// of objects in JSON format. + /// + public static QuantityValueMixedNotationConverter Default { get; } = new(); + + /// + public override QuantityValue Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + switch (reader.TokenType) + { + case JsonTokenType.Number: + { +#if NET + var nbBytes = reader.HasValueSequence ? checked((int)reader.ValueSequence.Length) : reader.ValueSpan.Length; + Span charBuffer = nbBytes <= StackAllocThreshold ? stackalloc char[nbBytes] : new char[nbBytes]; + var charsWritten = reader.HasValueSequence + ? Encoding.UTF8.GetChars(reader.ValueSequence, charBuffer) + : Encoding.UTF8.GetChars(reader.ValueSpan, charBuffer); + return QuantityValue.Parse(charBuffer[..charsWritten], NumberStyles.Float, CultureInfo.InvariantCulture); +#else + var bytes = reader.HasValueSequence ? reader.ValueSequence.ToArray() : reader.ValueSpan.ToArray(); + var charBuffer = new char[bytes.Length]; + var charsWritten = Encoding.UTF8.GetChars(bytes, 0, bytes.Length, charBuffer, 0); + return QuantityValue.Parse(new string(charBuffer, 0, charsWritten), NumberStyles.Float, CultureInfo.InvariantCulture); +#endif + } + case JsonTokenType.String: + { + var decimalNotationNotAllowed = (options.NumberHandling & JsonNumberHandling.AllowReadingFromString) == 0; + if (decimalNotationNotAllowed && reader.ValueIsEscaped) + { + throw new JsonException("Numbers can't contain escape characters."); + } + + var nbBytes = reader.HasValueSequence ? checked((int)reader.ValueSequence.Length) : reader.ValueSpan.Length; + Span charBuffer = nbBytes <= StackAllocThreshold ? stackalloc char[nbBytes] : new char[nbBytes]; + var charsWritten = reader.CopyString(charBuffer); + if (TryParseFraction(charBuffer.Slice(0, charsWritten), out QuantityValue quantityValue)) + { + return quantityValue; + } + + // falling back to the default quoted number handling + if (decimalNotationNotAllowed) + { + throw new JsonException( + "String tokens are not supported with the current `NumberHandling` settings. Consider specifying 'JsonNumberHandling.AllowReadingFromString' (see https://learn.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling)"); + } + +#if NET + return QuantityValue.Parse(charBuffer[..charsWritten], NumberStyles.Float, CultureInfo.InvariantCulture); +#else + return QuantityValue.Parse(charBuffer.Slice(0, charsWritten).ToString(), NumberStyles.Float, CultureInfo.InvariantCulture); +#endif + } + case JsonTokenType.None: + case JsonTokenType.StartObject: + case JsonTokenType.EndObject: + case JsonTokenType.StartArray: + case JsonTokenType.EndArray: + case JsonTokenType.PropertyName: + case JsonTokenType.Comment: + case JsonTokenType.True: + case JsonTokenType.False: + case JsonTokenType.Null: + default: + throw new JsonException($"Unexpected token type: {reader.TokenType}"); + } + } + + private static bool TryParseFraction(ReadOnlySpan value, out QuantityValue quantityValue) + { + if (value.TrySplit('/', out ReadOnlySpan numeratorSpan, out ReadOnlySpan denominatorSpan)) + { +#if NET + if (BigInteger.TryParse(numeratorSpan, out BigInteger numerator) && BigInteger.TryParse(denominatorSpan, out BigInteger denominator)) +#else + if (BigInteger.TryParse(numeratorSpan.ToString(), out BigInteger numerator) && + BigInteger.TryParse(denominatorSpan.ToString(), out BigInteger denominator)) +#endif + { + quantityValue = QuantityValue.FromTerms(numerator, denominator); + return true; + } + } + + quantityValue = default; + return false; + } + + /// + public override void Write(Utf8JsonWriter writer, QuantityValue value, JsonSerializerOptions options) + { + (BigInteger numerator, BigInteger denominator) = QuantityValue.Reduce(value); + // TODO see about using exponential notation + + if (denominator <= long.MaxValue / 10) + { + if (numerator <= long.MaxValue && numerator >= long.MinValue) + { + WriteSmallTerms(writer, (long)numerator, (long)denominator, options.NumberHandling); + return; + } + + if (denominator.IsOne) + { + BigIntegerConverter.Default.Write(writer, numerator, options); + return; + } + } + + if (!QuantityValue.HasNonDecimalFactors(denominator)) + { +#if NET + writer.WriteValuesAsString(numerator, '/', denominator); +#else + writer.WriteStringValues(numerator.ToString().AsSpan(), '/', denominator.ToString().AsSpan()); +#endif + return; + } + + var quotient = BigInteger.DivRem(numerator, denominator, out BigInteger remainder); + + // decimal number + var bufferSize = StackAllocThreshold; +#if NET + Span charBuffer = stackalloc char[bufferSize]; + int charsWritten; + while (!quotient.TryFormat(charBuffer, out charsWritten)) + { + bufferSize *= 4; + charBuffer = new char[bufferSize]; + } + + if (charsWritten + 2 > bufferSize) + { + bufferSize *= 2; + var extendedBuffer = new char[bufferSize * 2]; + charBuffer.CopyTo(extendedBuffer); + charBuffer = extendedBuffer; + } +#else + var quotientString = quotient.ToString(); + if (quotientString.Length + 2 > bufferSize) + { + bufferSize = quotientString.Length * 2; + } + + // Copy the quotient string into the char buffer + Span charBuffer = bufferSize <= StackAllocThreshold ? stackalloc char[bufferSize] : new char[bufferSize]; + quotientString.AsSpan().CopyTo(charBuffer); + var charsWritten = quotientString.Length; +#endif + + BigInteger ten = 10; + charBuffer[charsWritten++] = '.'; + remainder = BigInteger.Abs(remainder); + do + { + var digit = (int)BigInteger.DivRem(remainder * ten, denominator, out remainder); + if (charsWritten == bufferSize) + { + // extend the buffer + bufferSize *= 2; + var extendedBuffer = new char[bufferSize * 2]; + charBuffer.CopyTo(extendedBuffer); + charBuffer = extendedBuffer; + } + + charBuffer[charsWritten++] = (char)('0' + digit); + } while (!remainder.IsZero); + + if ((options.NumberHandling & JsonNumberHandling.WriteAsString) == 0) + { + writer.WriteRawValue(charBuffer.Slice(0, charsWritten), true); + } + else + { + writer.WriteStringValue(charBuffer.Slice(0, charsWritten)); + } + } + + private static void WriteSmallTerms(Utf8JsonWriter writer, long numerator, long denominator, JsonNumberHandling numberHandling) + { + switch (denominator) + { + case 0: + if ((numberHandling & JsonNumberHandling.AllowNamedFloatingPointLiterals) == 0) + { + throw new JsonException( + "NamedFloatingPointLiterals are not supported with the current `NumberHandling` settings. Consider specifying 'JsonNumberHandling.AllowNamedFloatingPointLiterals' (see https://learn.microsoft.com/dotnet/api/system.text.json.serialization.jsonnumberhandling)"); + } + + // NaN or Infinity + switch (numerator) + { + case > 0: + writer.WriteStringValue(NumberFormatInfo.InvariantInfo.PositiveInfinitySymbol); + return; + case < 0: + writer.WriteStringValue(NumberFormatInfo.InvariantInfo.NegativeInfinitySymbol); + return; + default: + writer.WriteStringValue(NumberFormatInfo.InvariantInfo.NaNSymbol); + return; + } + case 1: + if ((numberHandling & JsonNumberHandling.WriteAsString) == 0) + { + writer.WriteNumberValue(numerator); + } + else + { + writer.WriteStringValue(numerator.ToString()); + } + + return; + } + + var quotient = Math.DivRem(numerator, denominator, out var remainder); + + // decimal number + const int bufferSize = 45; + Span charBuffer = stackalloc char[bufferSize]; +#if NET + quotient.TryFormat(charBuffer, out var charsWritten); +#else + var quotientString = quotient.ToString(); + quotientString.AsSpan().CopyTo(charBuffer); + var charsWritten = quotientString.Length; +#endif + charBuffer[charsWritten++] = '.'; + remainder = Math.Abs(remainder); + do + { + var digit = Math.DivRem(remainder * 10, denominator, out remainder); + + charBuffer[charsWritten++] = (char)(digit + '0'); + if (remainder == 0) + { + if ((numberHandling & JsonNumberHandling.WriteAsString) == 0) + { + writer.WriteRawValue(charBuffer.Slice(0, charsWritten), true); + } + else + { + writer.WriteStringValue(charBuffer.Slice(0, charsWritten)); + } + + return; + } + } while (charsWritten < bufferSize); + + // failed to format the value as a decimal number + + // note: the following code is equivalent to the string interpolation: + // writer.WriteStringValue($"{numerator}/{denominator}"); +#if NET + numerator.TryFormat(charBuffer, out var numeratorLength); + charBuffer[numeratorLength] = '/'; + denominator.TryFormat(charBuffer[(numeratorLength + 1)..], out var denominatorLength); + writer.WriteStringValue(charBuffer[..(numeratorLength + denominatorLength + 1)]); +#else + ReadOnlySpan numeratorSpan = numerator.ToString().AsSpan(); + numeratorSpan.CopyTo(charBuffer); + charBuffer[numeratorSpan.Length] = '/'; + ReadOnlySpan denominatorSpan = denominator.ToString().AsSpan(); + denominatorSpan.CopyTo(charBuffer.Slice(numeratorSpan.Length + 1)); + writer.WriteStringValue(charBuffer.Slice(0, numeratorSpan.Length + denominatorSpan.Length + 1)); +#endif + } +} diff --git a/UnitsNet.Tests/AffineQuantityExtensionsTest.cs b/UnitsNet.Tests/AffineQuantityExtensionsTest.cs index 5da68a2030..ff768a86c0 100644 --- a/UnitsNet.Tests/AffineQuantityExtensionsTest.cs +++ b/UnitsNet.Tests/AffineQuantityExtensionsTest.cs @@ -7,8 +7,7 @@ public class AffineQuantityExtensionsTest { [Theory] [InlineData(25.0, 25.0, 0.1, true)] // Equal values - // [InlineData(25.0, 25.1, 0.1, true)] // Within tolerance (but fails due to rounding) - [InlineData(25.0, 25.1, 0.10001, true)] // Within tolerance + [InlineData(25.0, 25.1, 0.1, true)] // Within tolerance [InlineData(25.0, 25.2, 0.1, false)] // Outside tolerance [InlineData(25.0, 25.0, 0.0, true)] // Zero tolerance, equal values [InlineData(25.0, 25.1, 0.0, false)] // Zero tolerance, different values @@ -56,8 +55,7 @@ public void Equals_Temperature_TemperatureDelta_ThrowsArgumentOutOfRangeExceptio [Theory] [InlineData(25.0, 25.0, 0.1, true)] // Equal values - // [InlineData(25.0, 25.1, 0.1, true)] // Within tolerance (but fails due to rounding) - [InlineData(25.0, 25.1, 0.10001, true)] // Within tolerance + [InlineData(25.0, 25.1, 0.1, true)] // Within tolerance [InlineData(25.0, 25.2, 0.1, false)] // Outside tolerance [InlineData(25.0, 25.0, 0.0, true)] // Zero tolerance, equal values [InlineData(25.0, 25.1, 0.0, false)] // Zero tolerance, different values @@ -76,7 +74,7 @@ public void Equals_Temperature_IQuantity(double value1, double value2, double to public void Equals_Temperature_IQuantity_WithDifferentType_ReturnsFalse() { var temperature1 = Temperature.FromDegreesCelsius(25.0); - IQuantity length = Length.From(1, LengthUnit.Meter); + IQuantity length = Length.From(QuantityValue.One, LengthUnit.Meter); var tolerance = TemperatureDelta.FromDegreesCelsius(1); var result = temperature1.Equals(length, tolerance); diff --git a/UnitsNet.Tests/AssertEx.cs b/UnitsNet.Tests/AssertEx.cs index d052adfeec..989d872622 100644 --- a/UnitsNet.Tests/AssertEx.cs +++ b/UnitsNet.Tests/AssertEx.cs @@ -1,4 +1,5 @@ using System; +using System.Numerics; using Xunit; namespace UnitsNet.Tests @@ -8,21 +9,45 @@ namespace UnitsNet.Tests /// public static class AssertEx { - public static void EqualTolerance(double expected, double actual, double tolerance, ComparisonType comparisonType = ComparisonType.Relative) + public static void EqualTolerance(QuantityValue expected, QuantityValue actual, QuantityValue tolerance, ComparisonType comparisonType = ComparisonType.Relative) { if (comparisonType == ComparisonType.Relative) { - bool areEqual = Comparison.EqualsRelative(expected, actual, tolerance); - - double difference = Math.Abs(expected - actual); - double relativeDifference = difference / expected; - - Assert.True( areEqual, $"Values are not equal within relative tolerance: {tolerance:P4}\nExpected: {expected}\nActual: {actual}\nDiff: {relativeDifference:P4}" ); + var areEqual = Comparison.EqualsRelative(expected, actual, tolerance); + if (areEqual) + { + return; + } + + var difference = QuantityValue.Abs(expected - actual); + QuantityValue relativeDifference = difference / expected; + // Assert.True(areEqual, $"Values are not equal within relative tolerance: {tolerance:P4}\nExpected: {expected}\nActual: {actual}\nDiff: {relativeDifference:P4}"); + + int percentDecimals; + if (tolerance >= QuantityValue.One) + { + percentDecimals = 0; + } + else + { + (BigInteger _, BigInteger denominator) = tolerance; + percentDecimals = Math.Max(0, denominator.ToString().Length - 3); + } + + var toleranceFormat = "P" + percentDecimals; + var differenceFormat = "P" + (percentDecimals + 1); + var userMessage = $"Values are not equal within relative tolerance: {tolerance.ToString(toleranceFormat)}\nExpected: {expected}\nActual: {actual}\nDiff: {relativeDifference.ToString(differenceFormat)}"; + Assert.True(areEqual, userMessage); } 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}" ); + var areEqual = Comparison.EqualsAbsolute(expected, actual, tolerance); + if (areEqual) + { + return; + } + + Assert.True(areEqual, $"Values are not equal within absolute tolerance: {tolerance}\nExpected: {expected}\nActual: {actual}\nDiff: {actual - expected:e}" ); } } } diff --git a/UnitsNet.Tests/CompiledLambdasTests.cs b/UnitsNet.Tests/CompiledLambdasTests.cs index 2e6630de54..0c5cf51b61 100644 --- a/UnitsNet.Tests/CompiledLambdasTests.cs +++ b/UnitsNet.Tests/CompiledLambdasTests.cs @@ -2,6 +2,7 @@ namespace UnitsNet.Tests { + #if COMPILED_LAMBDAS_ENABLED public class CompiledLambdasTests { [Theory] @@ -91,4 +92,5 @@ public void GreaterThanOrEqualReturnsExpectedValues(TLeft left, T Assert.Equal(expected, CompiledLambdas.GreaterThanOrEqual(left, right)); } } + #endif } diff --git a/UnitsNet.Tests/ConversionExpressionTests.cs b/UnitsNet.Tests/ConversionExpressionTests.cs new file mode 100644 index 0000000000..015dc0d2c9 --- /dev/null +++ b/UnitsNet.Tests/ConversionExpressionTests.cs @@ -0,0 +1,450 @@ +// 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.Text; +using Xunit; + +namespace UnitsNet.Tests +{ + public class ConversionExpressionTest + { + [Fact] + public void Constructor_WithAllParameters_ShouldInitializeProperties() + { + // Arrange + QuantityValue coefficient = 2.0m; + ConvertValueDelegate? nestedFunction = value => value * 2; + var exponent = 3; + QuantityValue constantTerm = 5.0m; + // Act + var conversionExpression = new ConversionExpression(coefficient, nestedFunction, exponent, constantTerm); + // Assert + Assert.Equal(coefficient, conversionExpression.Coefficient); + Assert.Equal(exponent, conversionExpression.Exponent); + Assert.Equal(nestedFunction, conversionExpression.NestedFunction); + Assert.Equal(constantTerm, conversionExpression.ConstantTerm); + } + + [Fact] + public void Constructor_WithCoefficientAndConstantTerm_ShouldInitializeProperties() + { + // Arrange + QuantityValue coefficient = 2.0m; + QuantityValue constantTerm = 5.0m; + // Act + var conversionExpression = new ConversionExpression(coefficient, constantTerm); + // Assert + Assert.Equal(coefficient, conversionExpression.Coefficient); + Assert.Null(conversionExpression.NestedFunction); + Assert.Equal(1, conversionExpression.Exponent); + Assert.Equal(constantTerm, conversionExpression.ConstantTerm); + } + + [Fact] + public void Constructor_WithCoefficient_ShouldInitializeProperties() + { + // Arrange + QuantityValue coefficient = 2.0m; + // Act + var conversionExpression = new ConversionExpression(coefficient); + // Assert + Assert.Equal(coefficient, conversionExpression.Coefficient); + Assert.Null(conversionExpression.NestedFunction); + Assert.Equal(1, conversionExpression.Exponent); + Assert.True(QuantityValue.IsZero(conversionExpression.ConstantTerm)); + } + + [Fact] + public void ImplicitConversion_FromQuantityValue_ShouldInitializeTheCoefficient() + { + // Arrange + QuantityValue quantityValue = 2.0m; + // Act + ConversionExpression conversionExpression = quantityValue; + // Assert + Assert.Equal(quantityValue, conversionExpression.Coefficient); + Assert.Null(conversionExpression.NestedFunction); + Assert.Equal(1, conversionExpression.Exponent); + Assert.True(QuantityValue.IsZero(conversionExpression.ConstantTerm)); + } + + [Fact] + public void ImplicitConversion_FromInt_ShouldInitializeTheCoefficient() + { + // Arrange + var value = 2; + // Act + ConversionExpression conversionExpression = value; + // Assert + Assert.Equal(value, conversionExpression.Coefficient); + Assert.Null(conversionExpression.NestedFunction); + Assert.Equal(1, conversionExpression.Exponent); + Assert.True(QuantityValue.IsZero(conversionExpression.ConstantTerm)); + } + + [Fact] + public void ImplicitConversion_FromLong_ShouldInitializeTheCoefficient() + { + // Arrange + long value = 2; + // Act + ConversionExpression conversionExpression = value; + // Assert + Assert.Equal(value, conversionExpression.Coefficient); + Assert.Null(conversionExpression.NestedFunction); + Assert.Equal(1, conversionExpression.Exponent); + Assert.True(QuantityValue.IsZero(conversionExpression.ConstantTerm)); + } + + [Theory] + [InlineData(0, 1, 0, 0, 0)] + [InlineData(1, 1, 2, 3, 5)] // x + 2 with x = 3 -> 3 + 2 = 5 + [InlineData(2, 2, 3, 4, 35)] // 2x^2 + 3 with x = 4 -> 2 * 16 + 3 = 35 + [InlineData(-1, 1, -2, -3, 1)] // -x - 2 with x = -3 -> 3 - 2 = 1 + public void Evaluate_Value_ReturnsExpectedResult(double coefficient, int exponent, double constantTerm, double value, double expected) + { + var expression = new ConversionExpression(coefficient, null, exponent, constantTerm); + QuantityValue result = expression.Evaluate(value); + Assert.Equal(expected, result); + } + + [Theory] + [InlineData(0, 1, 0, 0, 0)] + [InlineData(1, 1, 2, 3, 0.5)] // g(x) + 2 with x = 3 -> -1.5 + 2 = 0.5 + [InlineData(2, 2, 3, 4, 11)] // 2 * g(x)^2 + 3 with x = 4 -> 2 * (-2)^2 + 3 = 11 + [InlineData(-1, 1, -2, -3, -3.5)] // -g(x) - 2 with x = -3 -> -1.5 - 2 = -3.5 + public void Evaluate_Value_WithNestedFunction_ReturnsExpectedResult(double coefficient, int exponent, double constantTerm, double value, + double expected) + { + var expression = new ConversionExpression(coefficient, quantityValue => -quantityValue / 2, exponent, constantTerm); + QuantityValue result = expression.Evaluate(value); + Assert.Equal(expected, result); + } + + [Theory] + [InlineData(0, 1, 0)] + [InlineData(1, 1, 0)] + [InlineData(10, 1, 0)] + [InlineData(-1, 1, 0)] + [InlineData(-10, 1, 0)] + [InlineData(0, 1, 5)] + [InlineData(1, 1, 5)] + [InlineData(10, 1, 5)] + [InlineData(-1, 1, 5)] + [InlineData(-10, 1, 5)] + [InlineData(0, 1, -5)] + [InlineData(1, 1, -5)] + [InlineData(10, 1, -5)] + [InlineData(-10, 1, -5)] + [InlineData(-1, 1, -5)] + [InlineData(0, -1, 0)] + [InlineData(1, -1, 0)] + [InlineData(10, -1, 0)] + [InlineData(-1, -1, 0)] + [InlineData(-10, -1, 0)] + [InlineData(0, -1, 5)] + [InlineData(1, -1, 5)] + [InlineData(10, -1, 5)] + [InlineData(-10, -1, 5)] + [InlineData(-1, -1, 5)] + [InlineData(0, -1, -5)] + [InlineData(1, -1, -5)] + [InlineData(10, -1, -5)] + [InlineData(-1, -1, -5)] + [InlineData(-10, -1, -5)] + [InlineData(0, 2, 0)] + [InlineData(1, 2, 0)] + [InlineData(10, 2, 0)] + [InlineData(-10, 2, 0)] + [InlineData(-1, 2, 0)] + [InlineData(0, 2, 5)] + [InlineData(1, 2, 5)] + [InlineData(10, 2, 5)] + [InlineData(-1, 2, 5)] + [InlineData(-10, 2, 5)] + [InlineData(0, 2, -5)] + [InlineData(1, 2, -5)] + [InlineData(10, 2, -5)] + [InlineData(-1, 2, -5)] + [InlineData(-10, 2, -5)] + [InlineData(0, -2, 0)] + [InlineData(1, -2, 0)] + [InlineData(10, -2, 0)] + [InlineData(-1, -2, 0)] + [InlineData(-10, -2, 0)] + [InlineData(0, -2, 5)] + [InlineData(1, -2, 5)] + [InlineData(10, -2, 5)] + [InlineData(-1, -2, 5)] + [InlineData(-10, -2, 5)] + [InlineData(0, -2, -5)] + [InlineData(1, -2, -5)] + [InlineData(10, -2, -5)] + [InlineData(-1, -2, -5)] + [InlineData(-10, -2, -5)] + public void ExpressionWithoutNestedFunction_ConvertsTo_ConvertValueDelegate(double coefficient, int exponent, double constantTerm) + { + // Arrange + var expression = new ConversionExpression(coefficient, null, exponent, constantTerm); + QuantityValue expectedValueFor10 = expression.Evaluate(QuantityValue.Ten); + // Act + ConvertValueDelegate conversionFunction = expression; + // Assert + Assert.Equal(expectedValueFor10, conversionFunction(QuantityValue.Ten)); + } + + [Theory] + [InlineData(0, 1, 0)] + [InlineData(1, 1, 0)] + [InlineData(10, 1, 0)] + [InlineData(-1, 1, 0)] + [InlineData(-10, 1, 0)] + [InlineData(0, 1, 5)] + [InlineData(1, 1, 5)] + [InlineData(10, 1, 5)] + [InlineData(-1, 1, 5)] + [InlineData(-10, 1, 5)] + [InlineData(0, 1, -5)] + [InlineData(1, 1, -5)] + [InlineData(10, 1, -5)] + [InlineData(-10, 1, -5)] + [InlineData(-1, 1, -5)] + [InlineData(0, -1, 0)] + [InlineData(1, -1, 0)] + [InlineData(10, -1, 0)] + [InlineData(-1, -1, 0)] + [InlineData(-10, -1, 0)] + [InlineData(0, -1, 5)] + [InlineData(1, -1, 5)] + [InlineData(10, -1, 5)] + [InlineData(-10, -1, 5)] + [InlineData(-1, -1, 5)] + [InlineData(0, -1, -5)] + [InlineData(1, -1, -5)] + [InlineData(10, -1, -5)] + [InlineData(-1, -1, -5)] + [InlineData(-10, -1, -5)] + [InlineData(0, 2, 0)] + [InlineData(1, 2, 0)] + [InlineData(10, 2, 0)] + [InlineData(-10, 2, 0)] + [InlineData(-1, 2, 0)] + [InlineData(0, 2, 5)] + [InlineData(1, 2, 5)] + [InlineData(10, 2, 5)] + [InlineData(-1, 2, 5)] + [InlineData(-10, 2, 5)] + [InlineData(0, 2, -5)] + [InlineData(1, 2, -5)] + [InlineData(10, 2, -5)] + [InlineData(-1, 2, -5)] + [InlineData(-10, 2, -5)] + [InlineData(0, -2, 0)] + [InlineData(1, -2, 0)] + [InlineData(10, -2, 0)] + [InlineData(-1, -2, 0)] + [InlineData(-10, -2, 0)] + [InlineData(0, -2, 5)] + [InlineData(1, -2, 5)] + [InlineData(10, -2, 5)] + [InlineData(-1, -2, 5)] + [InlineData(-10, -2, 5)] + [InlineData(0, -2, -5)] + [InlineData(1, -2, -5)] + [InlineData(10, -2, -5)] + [InlineData(-1, -2, -5)] + [InlineData(-10, -2, -5)] + public void ExpressionWithNestedFunction_ConvertsTo_ConvertValueDelegate(double coefficient, int exponent, double constantTerm) + { + // Arrange + var expression = new ConversionExpression(coefficient, quantityValue => -quantityValue / 2, exponent, constantTerm); + QuantityValue expectedValueFor10 = expression.Evaluate(QuantityValue.Ten); + // Act + ConvertValueDelegate conversionFunction = expression; + // Assert + Assert.Equal(expectedValueFor10, conversionFunction(QuantityValue.Ten)); + } + + [Theory] + [InlineData(0, 1, 0, 0, 1, 0)] + [InlineData(10, 1, 0, 2, 1, 0)] + [InlineData(0.1, 2, 0, 4, -1, 0)] + [InlineData(-1, 1, -2, -3, -2, 0)] + [InlineData(10, 1, 5, 2, 1, 0)] + [InlineData(2, 1, 0, 3, 1, 10)] + [InlineData(1, 1, 2, 3, 1, 10)] + [InlineData(2, 2, 3, 4, -1, 38)] + [InlineData(-1, 1, -2, -3, -2, -14)] + [InlineData(0, -1, 0, 0, 1, 0)] + [InlineData(10, -1, 0, 2, 1, 0)] + [InlineData(0.1, -2, 0, 4, -1, 0)] + [InlineData(-1, -1, -2, -3, -2, 0)] + [InlineData(10, -1, 5, 2, 1, 0)] + [InlineData(2, -1, 0, 3, 1, 10)] + [InlineData(1, -1, 2, 3, 1, 10)] + [InlineData(2, -2, 3, 4, -1, 38)] + [InlineData(-1, -1, -2, -3, -2, -14)] + public void Evaluate_IntermediateExpression_ReturnsExpectedResult(decimal coefficient1, int exponent1, decimal constantTerm1, + decimal coefficient2, int exponent2, decimal constantTerm2) + { + // Arrange + var expression1 = new ConversionExpression(coefficient1, null, exponent1, constantTerm1); + var expression2 = new ConversionExpression(coefficient2, null, exponent2, constantTerm2); + QuantityValue expectedValueFor10 = expression1.Evaluate(expression2.Evaluate(QuantityValue.Ten)); + // Act + ConversionExpression compositeExpression = expression1.Evaluate(expression2); + // Assert + if (expression1.Exponent == 1 || expression1.Exponent == -1 && expression2.ConstantTerm == QuantityValue.Zero) + { + Assert.Null(compositeExpression.NestedFunction); + } + else + { + Assert.NotNull(compositeExpression.NestedFunction); + } + + Assert.Equal(expectedValueFor10, compositeExpression.Evaluate(QuantityValue.Ten)); + } + + [Theory] + [InlineData(0, 1, 0, 0, 1, 0)] + [InlineData(10, 1, 0, 2, 1, 0)] + [InlineData(0.1, 2, 0, 4, -1, 0)] + [InlineData(-1, 1, -2, -3, -2, 0)] + [InlineData(10, 1, 5, 2, 1, 0)] + [InlineData(2, 1, 0, 3, 1, 10)] + [InlineData(1, 1, 2, 3, 1, 10)] + [InlineData(2, 2, 3, 4, -1, 38)] + [InlineData(-1, 1, -2, -3, -2, -14)] + [InlineData(0, -1, 0, 0, 1, 0)] + [InlineData(10, -1, 0, 2, 1, 0)] + [InlineData(0.1, -2, 0, 4, -1, 0)] + [InlineData(-1, -1, -2, -3, -2, 0)] + [InlineData(10, -1, 5, 2, 1, 0)] + [InlineData(2, -1, 0, 3, 1, 10)] + [InlineData(1, -1, 2, 3, 1, 10)] + [InlineData(2, -2, 3, 4, -1, 38)] + [InlineData(-1, -1, -2, -3, -2, -14)] + public void EvaluateAndReduce_IntermediateExpression_ReturnsExpectedResult(decimal coefficient1, int exponent1, decimal constantTerm1, + decimal coefficient2, int exponent2, decimal constantTerm2) + { + // Arrange + var expression1 = new ConversionExpression(coefficient1, null, exponent1, constantTerm1); + var expression2 = new ConversionExpression(coefficient2, null, exponent2, constantTerm2); + QuantityValue expectedValueFor10 = expression1.Evaluate(expression2.Evaluate(QuantityValue.Ten)); + // Act + ConversionExpression compositeExpression = expression1.Evaluate(expression2, true); + // Assert + if (expression1.Exponent == 1 || expression1.Exponent == -1 && expression2.ConstantTerm == QuantityValue.Zero) + { + Assert.Null(compositeExpression.NestedFunction); + } + else + { + Assert.NotNull(compositeExpression.NestedFunction); + } + + Assert.True(QuantityValue.IsCanonical(compositeExpression.Coefficient)); + Assert.Equal(expectedValueFor10, compositeExpression.Evaluate(QuantityValue.Ten)); + } + + [Theory] + [InlineData(0, 1, 0, 0, 1, 0)] + [InlineData(10, 1, 0, 2, 1, 0)] + [InlineData(0.1, 2, 0, 4, -1, 0)] + [InlineData(-1, 1, -2, -3, -2, 0)] + [InlineData(10, 1, 5, 2, 1, 0)] + [InlineData(2, 1, 0, 3, 1, 10)] + [InlineData(1, 1, 2, 3, 1, 10)] + [InlineData(2, 2, 3, 4, -1, 38)] + [InlineData(-1, 1, -2, -3, -2, -14)] + [InlineData(0, -1, 0, 0, 1, 0)] + [InlineData(10, -1, 0, 2, 1, 0)] + [InlineData(0.1, -2, 0, 4, -1, 0)] + [InlineData(-1, -1, -2, -3, -2, 0)] + [InlineData(10, -1, 5, 2, 1, 0)] + [InlineData(2, -1, 0, 3, 1, 10)] + [InlineData(1, -1, 2, 3, 1, 10)] + [InlineData(2, -2, 3, 4, -1, 38)] + [InlineData(-1, -1, -2, -3, -2, -14)] + public void Evaluate_IntermediateExpression_WithNestedFunctions_ReturnsExpectedResult(decimal coefficient1, int exponent1, decimal constantTerm1, + decimal coefficient2, int exponent2, decimal constantTerm2) + { + // Arrange + var expression1 = new ConversionExpression(coefficient1, QuantityValue.Abs, exponent1, constantTerm1); + var expression2 = new ConversionExpression(coefficient2, QuantityValue.Inverse, exponent2, constantTerm2); + QuantityValue expectedValueFor10 = expression1.Evaluate(expression2.Evaluate(QuantityValue.Ten)); + // Act + ConversionExpression compositeExpression = expression1.Evaluate(expression2); + // Assert + Assert.Equal(expression1.Coefficient, compositeExpression.Coefficient); + Assert.NotNull(compositeExpression.NestedFunction); + Assert.NotEqual(expression1.NestedFunction, compositeExpression.NestedFunction); + Assert.NotEqual(expression2.NestedFunction, compositeExpression.NestedFunction); + Assert.Equal(expression1.Exponent, compositeExpression.Exponent); + Assert.Equal(expression1.ConstantTerm, compositeExpression.ConstantTerm); + Assert.Equal(expectedValueFor10, compositeExpression.Evaluate(QuantityValue.Ten)); + } + + [Theory] + [InlineData(1, 1, 2)] + [InlineData(2, 2, 3)] + [InlineData(0, 1, 0)] + [InlineData(-1, 1, -2)] + public void Negate_ReturnsExpectedResult(double coefficient, int exponent, double constantTerm) + { + // Arrange + var expression = new ConversionExpression(coefficient, null, exponent, constantTerm); + QuantityValue expectedCoefficient = -expression.Coefficient; + QuantityValue expectedConstantTerm = -expression.ConstantTerm; + // Act + ConversionExpression negatedExpression = -expression; + // Assert + Assert.Equal(expectedCoefficient, negatedExpression.Coefficient); + Assert.Null(negatedExpression.NestedFunction); + Assert.Equal(expression.Exponent, negatedExpression.Exponent); + Assert.Equal(expectedConstantTerm, negatedExpression.ConstantTerm); + } + + [Theory] + [InlineData(0, 1, 0, "0 * x")] + [InlineData(1, 1, 2, "x + 2")] + [InlineData(2, 2, 3, "2 * x^2 + 3")] + [InlineData(-1, 1, -2, "-x - 2")] + [InlineData(-2.5, 1, -2, "-2.5 * x - 2")] + [InlineData(2, -1, 2, "2 / x + 2")] + [InlineData(2, -2, 2, "2 * x^-2 + 2")] + public void ToString_ReturnsExpectedResult(double coefficient, int exponent, double constantTerm, string expected) + { + var expression = new ConversionExpression(coefficient, null, exponent, constantTerm); + var result = expression.ToString(); + Assert.Equal(expected, result); + } + + [Fact] + public void PrintMembers_ShouldReturnCorrectString() + { + var conversionExpression = new ConversionExpression(1); + var stringBuilder = new StringBuilder(); + + var success = conversionExpression.GetType().GetMethod("PrintMembers", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)! + .Invoke(conversionExpression, [stringBuilder]); + + Assert.Equal(true, success); + Assert.Equal("Coefficient = 1, Exponent = 1, ConstantTerm = 0", stringBuilder.ToString()); + } + + [Fact] + public void PrintMembers_WithNestedFunction_ShouldReturnCorrectString() + { + var conversionExpression = new ConversionExpression(1, QuantityValue.Inverse); + var stringBuilder = new StringBuilder(); + + var success = conversionExpression.GetType().GetMethod("PrintMembers", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)! + .Invoke(conversionExpression, [stringBuilder]); + + Assert.Equal(true, success); + Assert.Equal("Coefficient = 1, Exponent = 1, ConstantTerm = 0, NestedFunction = Inverse", stringBuilder.ToString()); + } + } +} diff --git a/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs b/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs index a9123f08af..c4a3e663d4 100644 --- a/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs +++ b/UnitsNet.Tests/CustomCode/AmplitudeRatioTests.cs @@ -79,9 +79,10 @@ public void ExpectAmplitudeRatioConvertedToVoltageCorrectly(double amplitudeRati public void AmplitudeRatioToPowerRatio_50OhmImpedance(double dBmV, double expected) { AmplitudeRatio ampRatio = AmplitudeRatio.FromDecibelMillivolts(dBmV); - - var actual = Math.Round(ampRatio.ToPowerRatio(ElectricResistance.FromOhms(50)).DecibelMilliwatts, 2); - Assert.Equal(expected, actual); + + QuantityValue actual = ampRatio.ToPowerRatio(ElectricResistance.FromOhms(50)).DecibelMilliwatts; + + AssertEx.EqualTolerance(expected, actual, 1e-2m, ComparisonType.Absolute); } [Theory] @@ -92,9 +93,10 @@ public void AmplitudeRatioToPowerRatio_50OhmImpedance(double dBmV, double expect public void AmplitudeRatioToPowerRatio_75OhmImpedance(double dBmV, double expected) { AmplitudeRatio ampRatio = AmplitudeRatio.FromDecibelMillivolts(dBmV); - - var actual = Math.Round(ampRatio.ToPowerRatio(ElectricResistance.FromOhms(75)).DecibelMilliwatts, 2); - Assert.Equal(expected, actual); + + QuantityValue actual = ampRatio.ToPowerRatio(ElectricResistance.FromOhms(75)).DecibelMilliwatts; + + AssertEx.EqualTolerance(expected, actual, 1e-2m, ComparisonType.Absolute); } } } diff --git a/UnitsNet.Tests/CustomCode/AreaTests.cs b/UnitsNet.Tests/CustomCode/AreaTests.cs index df6a6dbc62..cf58105265 100644 --- a/UnitsNet.Tests/CustomCode/AreaTests.cs +++ b/UnitsNet.Tests/CustomCode/AreaTests.cs @@ -73,9 +73,9 @@ public void AreaFromCircleDiameterCalculatedCorrectly(double diameterMeters, dou { Length diameter = Length.FromMeters(diameterMeters); - double actual = Area.FromCircleDiameter(diameter).SquareMeters; + QuantityValue actual = Area.FromCircleDiameter(diameter).SquareMeters; - Assert.Equal(expected, actual); + AssertEx.EqualTolerance(expected, actual, SquareMetersTolerance); } [Theory] @@ -87,9 +87,9 @@ public void AreaFromCircleRadiusCalculatedCorrectly(double radiusMeters, double { Length radius = Length.FromMeters(radiusMeters); - double actual = Area.FromCircleRadius(radius).SquareMeters; + QuantityValue actual = Area.FromCircleRadius(radius).SquareMeters; - Assert.Equal(expected, actual); + AssertEx.EqualTolerance(expected, actual, SquareMetersTolerance); } [Fact] diff --git a/UnitsNet.Tests/CustomCode/EnergyDensityTests.cs b/UnitsNet.Tests/CustomCode/EnergyDensityTests.cs index 854615278f..5e4bf65513 100644 --- a/UnitsNet.Tests/CustomCode/EnergyDensityTests.cs +++ b/UnitsNet.Tests/CustomCode/EnergyDensityTests.cs @@ -56,7 +56,7 @@ public void CombustionEnergy() Energy energy = EnergyDensity.CombustionEnergy(EnergyDensity.FromKilowattHoursPerCubicMeter(9.88), Volume.FromCubicMeters(1), Ratio.FromDecimalFractions(0.9543)); - Assert.Equal(9.428484, energy.KilowattHours, 5); + Assert.Equal(9.428484, energy.KilowattHours); } } } diff --git a/UnitsNet.Tests/CustomCode/IQuantityTests.cs b/UnitsNet.Tests/CustomCode/IQuantityTests.cs index 012f0cc09f..cbae3a2f64 100644 --- a/UnitsNet.Tests/CustomCode/IQuantityTests.cs +++ b/UnitsNet.Tests/CustomCode/IQuantityTests.cs @@ -2,7 +2,10 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; +using System.Diagnostics.CodeAnalysis; using System.Linq; +using System.Numerics; +using UnitsNet.Units; using Xunit; namespace UnitsNet.Tests @@ -15,17 +18,95 @@ public void As_GivenWrongUnitType_ThrowsArgumentException() { Assert.All(Quantity.Infos.Select(x => x.Zero), quantity => { - Assert.Throws(() => quantity.As(ComparisonType.Absolute)); + Assert.Throws(() => quantity.As(ComparisonType.Absolute)); }); } + // [Fact] + // public void As_GivenNullUnitSystem_ThrowsArgumentNullException() + // { + // Assert.All(Quantity.Infos.Select(x => x.Zero), quantity => + // { + // Assert.Throws(() => quantity.As((UnitSystem)null!)); + // }); + // } + + // [Fact] + // public void As_GivenSIUnitSystem_ReturnsSIValue() + // { + // IQuantity inches = new Length(2.0, LengthUnit.Inch); + // Assert.Equal(0.0508, inches.As(UnitSystem.SI)); + // } + [Fact] public void ToUnit_GivenWrongUnitType_ThrowsArgumentException() { Assert.All(Quantity.Infos.Select(x => x.Zero), quantity => { - Assert.Throws(() => quantity.ToUnit(ComparisonType.Absolute)); + Assert.Throws(() => quantity.ToUnit(ComparisonType.Absolute)); }); } + + // [Fact] + // public void ToUnit_GivenNullUnitSystem_ThrowsArgumentNullException() + // { + // Assert.All(Quantity.Infos.Select(x => x.Zero), quantity => + // { + // Assert.Throws(() => quantity.ToUnit((UnitSystem)null!)); + // }); + // } + // + // [Fact] + // public void ToUnit_GivenSIUnitSystem_ReturnsSIQuantity() + // { + // IQuantity inches = new Length(2.0, LengthUnit.Inch); + // + // IQuantity inSI = inches.ToUnit(UnitSystem.SI); + // + // Assert.Equal(0.0508, inSI.Value); + // Assert.Equal(LengthUnit.Meter, inSI.Unit); + // } + + #if NET + + [Fact] + public void ILinearQuantity_AdditiveIdentity_ReturnsZero() + { + AssertThat_ILinearQuantity_AdditiveIdentity_ReturnsZero(); + } + + private static void AssertThat_ILinearQuantity_AdditiveIdentity_ReturnsZero() + where TQuantity : ILinearQuantity + { + Assert.Equal(TQuantity.Zero, TQuantity.AdditiveIdentity); + } + + [Fact] + public void ILogarithmicQuantity_MultiplicativeIdentity_ReturnsZero() + { + AssertThat_ILogarithmicQuantity_MultiplicativeIdentity_ReturnsZero(); + } + + private static void AssertThat_ILogarithmicQuantity_MultiplicativeIdentity_ReturnsZero() + where TQuantity : ILogarithmicQuantity + { + Assert.Equal(TQuantity.Zero, TQuantity.MultiplicativeIdentity); + } + + [Fact] + public void IAffineQuantity_AdditiveIdentity_ReturnsTheZeroOffset() + { + AssertThat_ILinearQuantity_AdditiveIdentity_ReturnsZero(); + AssertThat_IAffineQuantity_AdditiveIdentity_ReturnsTheZeroOffset(); + } + + private static void AssertThat_IAffineQuantity_AdditiveIdentity_ReturnsTheZeroOffset() + where TQuantity : IAffineQuantity + where TOffset : IAdditiveIdentity + { + Assert.Equal(TOffset.AdditiveIdentity, TQuantity.AdditiveIdentity); + } + + #endif } } diff --git a/UnitsNet.Tests/CustomCode/LengthTests.FeetInches.cs b/UnitsNet.Tests/CustomCode/LengthTests.FeetInches.cs index 4c4855b436..c1fdedfe6e 100644 --- a/UnitsNet.Tests/CustomCode/LengthTests.FeetInches.cs +++ b/UnitsNet.Tests/CustomCode/LengthTests.FeetInches.cs @@ -5,108 +5,110 @@ using System.Globalization; using Xunit; -namespace UnitsNet.Tests +namespace UnitsNet.Tests; + +public class FeetInchesTests { - public class FeetInchesTests + private const string EnglishUs = "en-US"; + private const string GermanSwitzerland = "de-CH"; + + [Fact] + public void FeetInchesFrom() { - private static readonly CultureInfo EnglishUs = new("en-US", useUserOverride: false); - private static readonly CultureInfo GermanSwitzerland = new("de-CH", useUserOverride: false); - private const double FeetInOneMeter = 3.28084; - private const double InchesInOneMeter = 39.37007874; - private const double FeetTolerance = 1e-5; - private const double InchesTolerance = 1e-5; - - [Fact] - public void FeetInchesFrom() - { - Length meter = Length.FromFeetInches(2, 3); - double expectedMeters = 2/FeetInOneMeter + 3/InchesInOneMeter; - AssertEx.EqualTolerance(expectedMeters, meter.Meters, FeetTolerance); - } + var meter = Length.FromFeetInches(2, 3); + Assert.Equal(0.6858m, meter.Meters); + } - [Fact] - public void FeetInchesRoundTrip() - { - Length meter = Length.FromFeetInches(2, 3); - FeetInches feetInches = meter.FeetInches; - AssertEx.EqualTolerance(2, feetInches.Feet, FeetTolerance); - AssertEx.EqualTolerance(3, feetInches.Inches, InchesTolerance); - } + [Fact] + public void FeetInchesRoundTrip() + { + var meter = Length.FromFeetInches(2, 3); + FeetInches feetInches = meter.FeetInches; + Assert.Equal(2, feetInches.Feet); + Assert.Equal(3, feetInches.Inches); + } - public static IEnumerable ValidData => new List - { - new object[]{"1'", 1, EnglishUs}, // Feet only - new object[]{"1′", 1, EnglishUs}, // Feet only - new object[]{"1,000′", 1000, EnglishUs}, // Feet only, with seperator - new object[]{"1e3'", 1000, EnglishUs}, // Feet only, exponential notation - new object[]{"1\"", 0.08333333, EnglishUs}, // Inches only - new object[]{"1″", 0.08333333, EnglishUs}, // Inches only - new object[]{"0' 1\"", 0.08333333, EnglishUs}, // Inches only - new object[]{"0' 1″", 0.08333333, EnglishUs}, // Inches only - new object[]{"0′ 1\"", 0.08333333, EnglishUs}, // Inches only - new object[]{"0′ 1″", 0.08333333, EnglishUs}, // Inches only - new object[]{"1' 1\"", 1.08333333, EnglishUs}, // Normal form - new object[]{"1′ 1″", 1.08333333, EnglishUs}, // Normal form - new object[]{" 1′ 1″ ", 1.08333333, EnglishUs}, // Normal form, requires trimming - new object[]{"1'1\"", 1.08333333, EnglishUs}, // Without space - new object[]{"1′1″", 1.08333333, EnglishUs}, // Without space - new object[]{"1 ft 1 in", 1.08333333, EnglishUs}, - new object[]{"1ft 1in", 1.08333333, EnglishUs}, - new object[]{"-1'", -1, EnglishUs}, // Feet only - new object[]{"-1′", -1, EnglishUs}, // Feet only - new object[]{"-1,000′", -1000, EnglishUs}, // Feet only, with seperator - new object[]{"-1e3'", -1000, EnglishUs}, // Feet only, exponential notation - new object[]{"-1\"", -0.08333333, EnglishUs}, // Inches only - new object[]{"-1″", -0.08333333, EnglishUs}, // Inches only - new object[]{"-0' 1\"", -0.08333333, EnglishUs}, // Inches only - new object[]{"-0' 1″", -0.08333333, EnglishUs}, // Inches only - new object[]{"-0′ 1\"", -0.08333333, EnglishUs}, // Inches only - new object[]{"-0′ 1″", -0.08333333, EnglishUs}, // Inches only - new object[]{"-1' 1\"", -1.08333333, EnglishUs}, // Normal form - new object[]{"-1′ 1″", -1.08333333, EnglishUs}, // Normal form - new object[]{" -1′ 1″ ", -1.08333333, EnglishUs}, // Normal form, requires trimming - new object[]{"-1'1\"", -1.08333333, EnglishUs}, // Without space - new object[]{"-1′1″", -1.08333333, EnglishUs}, // Without space - new object[]{"-1 ft 1 in", -1.08333333, EnglishUs}, - new object[]{"-1ft 1in", -1.08333333, EnglishUs}, - new object[]{"1’000′", 1000, GermanSwitzerland}, // Feet only, with seperator - new object[]{"1’000′ 6\"", 1000.5, GermanSwitzerland}, // Normal form, using separators for culture - }; + public static IEnumerable ValidData + { + get => + [ + ["1'", 1, EnglishUs], // Feet only + ["1′", 1, EnglishUs], // Feet only + ["1,000′", 1000, EnglishUs], // Feet only, with separator + ["1e3'", 1000, EnglishUs], // Feet only, exponential notation + ["1\"", 0.08333333, EnglishUs], // Inches only + ["1″", 0.08333333, EnglishUs], // Inches only + ["0' 1\"", 0.08333333, EnglishUs], // Inches only + ["0' 1″", 0.08333333, EnglishUs], // Inches only + ["0′ 1\"", 0.08333333, EnglishUs], // Inches only + ["0′ 1″", 0.08333333, EnglishUs], // Inches only + ["1' 1\"", 1.08333333, EnglishUs], // Normal form + ["1′ 1″", 1.08333333, EnglishUs], // Normal form + [" 1′ 1″ ", 1.08333333, EnglishUs], // Normal form, requires trimming + ["1'1\"", 1.08333333, EnglishUs], // Without space + ["1′1″", 1.08333333, EnglishUs], // Without space + ["1 ft 1 in", 1.08333333, EnglishUs], + ["1ft 1in", 1.08333333, EnglishUs], + ["-1'", -1, EnglishUs], // Feet only + ["-1′", -1, EnglishUs], // Feet only + ["-1,000′", -1000, EnglishUs], // Feet only, with separator + ["-1e3'", -1000, EnglishUs], // Feet only, exponential notation + ["-1\"", -0.08333333, EnglishUs], // Inches only + ["-1″", -0.08333333, EnglishUs], // Inches only + ["-0' 1\"", -0.08333333, EnglishUs], // Inches only + ["-0' 1″", -0.08333333, EnglishUs], // Inches only + ["-0′ 1\"", -0.08333333, EnglishUs], // Inches only + ["-0′ 1″", -0.08333333, EnglishUs], // Inches only + ["-1' 1\"", -1.08333333, EnglishUs], // Normal form + ["-1′ 1″", -1.08333333, EnglishUs], // Normal form + [" -1′ 1″ ", -1.08333333, EnglishUs], // Normal form, requires trimming + ["-1'1\"", -1.08333333, EnglishUs], // Without space + ["-1′1″", -1.08333333, EnglishUs], // Without space + ["-1 ft 1 in", -1.08333333, EnglishUs], + ["-1ft 1in", -1.08333333, EnglishUs], + ["1’000′", 1000, GermanSwitzerland], // Feet only, with separator + ["1’000′ 6\"", 1000.5, GermanSwitzerland] // Normal form, using separators for culture + ]; + } - [Theory] - [MemberData(nameof(ValidData))] - public void TryParseFeetInches(string str, double expectedFeet, CultureInfo formatProvider) - { - Assert.True(Length.TryParseFeetInches(str, out Length result, formatProvider)); - AssertEx.EqualTolerance(expectedFeet, result.Feet, 1e-5); - } + [Theory] + [MemberData(nameof(ValidData))] + public void TryParseFeetInches(string str, double expectedFeet, string cultureName) + { + var formatProvider = new CultureInfo(cultureName, false); + Assert.True(Length.TryParseFeetInches(str, out Length result, formatProvider)); + AssertEx.EqualTolerance(expectedFeet, result.Feet, 1e-5); + } - public static IEnumerable InvalidData => new List - { - new object[]{"a", EnglishUs}, // Missing or invalid apostrophe or double prime chars - new object[]{"1", EnglishUs}, - new object[]{"1`", EnglishUs}, - new object[]{"1^", EnglishUs}, - new object[]{"1' 1'", EnglishUs}, // Feet apostrophe twice - new object[]{"1′ 1′", EnglishUs}, - new object[]{"1' 1", EnglishUs}, // No inches double prime - new object[]{"1′ 1", EnglishUs}, - new object[]{"1′ 1`", EnglishUs}, // Invalid inches double prime - new object[]{"1' 1`", EnglishUs}, - new object[]{"1'1'", EnglishUs}, // Same without space - new object[]{"1′1′", EnglishUs}, - new object[]{"1'1", EnglishUs}, - new object[]{"1′1", EnglishUs}, - new object[]{"1′1`", EnglishUs}, - new object[]{"1'1`", EnglishUs} - }; + public static IEnumerable InvalidData + { + get => + [ + ["a", EnglishUs], // Missing or invalid apostrophe or double prime chars + ["1", EnglishUs], + ["1`", EnglishUs], + ["1^", EnglishUs], + ["1' 1'", EnglishUs], // Feet apostrophe twice + ["1′ 1′", EnglishUs], + ["1' 1", EnglishUs], // No inches double prime + ["1′ 1", EnglishUs], + ["1′ 1`", EnglishUs], // Invalid inches double prime + ["1' 1`", EnglishUs], + ["1'1'", EnglishUs], // Same without space + ["1′1′", EnglishUs], + ["1'1", EnglishUs], + ["1′1", EnglishUs], + ["1′1`", EnglishUs], + ["1'1`", EnglishUs] + ]; + } - [Theory] - [MemberData(nameof(InvalidData))] - public void TryParseFeetInches_GivenInvalidString_ReturnsFalseAndZeroOut(string str, CultureInfo formatProvider) - { - Assert.False(Length.TryParseFeetInches(str, out Length result, formatProvider)); - Assert.Equal(Length.Zero, result); - } + [Theory] + [MemberData(nameof(InvalidData))] + public void TryParseFeetInches_GivenInvalidString_ReturnsFalseAndZeroOut(string str, string cultureName) + { + var formatProvider = new CultureInfo(cultureName, false); + Assert.False(Length.TryParseFeetInches(str, out Length result, formatProvider)); + Assert.Equal(Length.Zero, result); } } diff --git a/UnitsNet.Tests/CustomCode/ParseTests.cs b/UnitsNet.Tests/CustomCode/ParseTests.cs index d53a55a1f5..1bbc0a3ee1 100644 --- a/UnitsNet.Tests/CustomCode/ParseTests.cs +++ b/UnitsNet.Tests/CustomCode/ParseTests.cs @@ -27,7 +27,7 @@ public class ParseTests public void ParseLengthToMetersUsEnglish(string s, double expected) { CultureInfo usEnglish = CultureInfo.GetCultureInfo("en-US"); - double actual = Length.Parse(s, usEnglish).Meters; + QuantityValue actual = Length.Parse(s, usEnglish).Meters; Assert.Equal(expected, actual); } @@ -49,7 +49,7 @@ public void ParseLength_InvalidString_USEnglish_ThrowsException(string? s, Type [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, double expected) { var numberFormat = (NumberFormatInfo) CultureInfo.InvariantCulture.NumberFormat.Clone(); numberFormat.NumberGroupSeparator = " "; @@ -57,7 +57,7 @@ public void ParseWithCultureUsingSpaceAsThousandSeparators(string? s, double exp numberFormat.NumberDecimalSeparator = "."; numberFormat.CurrencyDecimalSeparator = "."; - double actual = Length.Parse(s!, numberFormat).Meters; + QuantityValue actual = Length.Parse(s, numberFormat).Meters; Assert.Equal(expected, actual); } @@ -88,7 +88,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 b310bed861..0464048c65 100644 --- a/UnitsNet.Tests/CustomCode/PowerRatioTests.cs +++ b/UnitsNet.Tests/CustomCode/PowerRatioTests.cs @@ -68,8 +68,9 @@ public void PowerRatioToAmplitudeRatio_50OhmImpedance(double dBmW, double expect { PowerRatio powerRatio = PowerRatio.FromDecibelMilliwatts(dBmW); - double actual = Math.Round(powerRatio.ToAmplitudeRatio(ElectricResistance.FromOhms(50)).DecibelMillivolts, 2); - Assert.Equal(expected, actual); + QuantityValue actual = powerRatio.ToAmplitudeRatio(ElectricResistance.FromOhms(50)).DecibelMillivolts; + + AssertEx.EqualTolerance(expected, actual, 1e-2m, ComparisonType.Absolute); } [Theory] @@ -81,8 +82,9 @@ public void PowerRatioToAmplitudeRatio_75OhmImpedance(double dBmW, double expect { PowerRatio powerRatio = PowerRatio.FromDecibelMilliwatts(dBmW); - double actual = Math.Round(powerRatio.ToAmplitudeRatio(ElectricResistance.FromOhms(75)).DecibelMillivolts, 2); - Assert.Equal(expected, actual); + QuantityValue actual = powerRatio.ToAmplitudeRatio(ElectricResistance.FromOhms(75)).DecibelMillivolts; + + AssertEx.EqualTolerance(expected, actual, 1e-2m, ComparisonType.Absolute); } } } diff --git a/UnitsNet.Tests/CustomCode/PressureTests.cs b/UnitsNet.Tests/CustomCode/PressureTests.cs index f536bfa00c..295b6daf77 100644 --- a/UnitsNet.Tests/CustomCode/PressureTests.cs +++ b/UnitsNet.Tests/CustomCode/PressureTests.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Linq; using UnitsNet.CustomCode.Units; +using UnitsNet.InternalHelpers; using UnitsNet.Units; using UnitsNet.Wrappers; using Xunit; @@ -169,7 +170,7 @@ public void ReferencePressure_WithInvalidPressureReference_ThrowsNotImplementedE [Fact] public void ReferencePressureReferences_ReturnsTheExpectedEnumValues() { - IEnumerable expectedValues = Enum.GetValues(); + IEnumerable expectedValues = EnumHelper.GetValues(); PressureReference[] actualValues = ReferencePressure.References; @@ -285,16 +286,16 @@ public void PressureDividedByTimeSpanEqualsPressureChangeRate() [Fact] public void PressureFromElevation_ConvertsWithRounding() { - var pressureFromElevation = Pressure.FromElevation(new Length(129149.9769457631, LengthUnit.Foot)); - Assert.Equal(1, pressureFromElevation.Pascals, PascalsTolerance); + var pressureFromElevation = Pressure.FromElevation(new Length(129149.9769457631m, LengthUnit.Foot), 13); + Assert.Equal(1, pressureFromElevation.Pascals); } [Fact] public void ElevationFromPressure_ConvertsWithRounding() { - Length elevationFromPressure = Pressure.FromPascals(1).ToElevation(); + Length elevationFromPressure = Pressure.FromPascals(1).ToElevation(15); Assert.Equal(LengthUnit.Foot, elevationFromPressure.Unit); - Assert.Equal(129149.976945763, elevationFromPressure.Value, 9); + Assert.Equal(129149.976945763m, elevationFromPressure.Value); } } } diff --git a/UnitsNet.Tests/CustomCode/QuantityInfos/Builder/QuantitiesInfoBuilderTest.cs b/UnitsNet.Tests/CustomCode/QuantityInfos/Builder/QuantitiesInfoBuilderTest.cs new file mode 100644 index 0000000000..0edc5bc22e --- /dev/null +++ b/UnitsNet.Tests/CustomCode/QuantityInfos/Builder/QuantitiesInfoBuilderTest.cs @@ -0,0 +1,69 @@ +// 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 UnitsNet.Units; +using Xunit; + +namespace UnitsNet.Tests.QuantityInfos.Builder; + +public class QuantitiesInfoBuilderTest +{ + [Fact] + public void ConfigureQuantity_ValidInput_AddsCustomization() + { + var builder = new QuantitiesInfoBuilder(); + + builder.ConfigureQuantity(() => + new QuantityInfo(LengthUnit.Centimeter, Length.LengthInfo.GetDefaultMappings(), BaseDimensions.Dimensionless, Length.From)); + + QuantityInfo result = builder.CreateOrDefault(Length.Info); + + Assert.Equal(LengthUnit.Centimeter, result.BaseUnitInfo.Value); + Assert.Equal(BaseDimensions.Dimensionless, result.BaseDimensions); + } + + [Fact] + public void ConfigureQuantity_NullDelegate_ThrowsArgumentNullException() + { + var builder = new QuantitiesInfoBuilder(); + + Assert.Throws(() => + builder.ConfigureQuantity(null!)); + } + + [Fact] + public void CreateOrDefault_NoCustomization_ReturnsDefault() + { + var builder = new QuantitiesInfoBuilder(); + QuantityInfo defaultConfig = Length.Info; + + QuantityInfo result = builder.CreateOrDefault(defaultConfig); + + Assert.Equal(defaultConfig, result); + } + + [Fact] + public void CreateOrDefault_Generic_NoCustomization_ReturnsDefault() + { + var builder = new QuantitiesInfoBuilder(); + + QuantityInfo result = builder.CreateOrDefault(() => Length.Info); + + Assert.Equal(Length.Info, result); + } + + [Fact] + public void CreateOrDefault_Generic_WithCustomization_ReturnsCustomized() + { + var builder = new QuantitiesInfoBuilder(); + + builder.ConfigureQuantity(() => + new QuantityInfo(LengthUnit.Centimeter, Length.LengthInfo.GetDefaultMappings(), BaseDimensions.Dimensionless, Length.From)); + + QuantityInfo result = builder.CreateOrDefault(() => Length.Info); + + Assert.Equal(LengthUnit.Centimeter, result.BaseUnitInfo.Value); + Assert.Equal(BaseDimensions.Dimensionless, result.BaseDimensions); + } +} diff --git a/UnitsNet.Tests/CustomCode/QuantityInfos/Builder/QuantitiesSelectorTest.cs b/UnitsNet.Tests/CustomCode/QuantityInfos/Builder/QuantitiesSelectorTest.cs new file mode 100644 index 0000000000..705917033e --- /dev/null +++ b/UnitsNet.Tests/CustomCode/QuantityInfos/Builder/QuantitiesSelectorTest.cs @@ -0,0 +1,65 @@ +// 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.Collections.Generic; +using UnitsNet.Units; +using Xunit; + +namespace UnitsNet.Tests.QuantityInfos.Builder; + +public class QuantitiesSelectorTest +{ + [Fact] + public void Constructor_InitializesQuantitiesSelected() + { + var selector = new QuantitiesSelector(() => []); + Assert.Empty(selector.GetQuantityInfos()); + } + + [Fact] + public void WithAdditionalQuantities_AddsQuantities() + { + QuantitiesSelector selector = new QuantitiesSelector(() => [Length.Info]) + .WithAdditionalQuantities([Mass.Info]); + + Assert.Equal([Length.Info, Mass.Info], selector.GetQuantityInfos()); + } + + [Fact] + public void Configure_AddsCustomConfiguration() + { + var selector = new QuantitiesSelector(() => [Length.Info, Mass.Info]); + var customLengthConfig = + new QuantityInfo(LengthUnit.Centimeter, Length.LengthInfo.GetDefaultMappings(), BaseDimensions.Dimensionless, Length.From); + + selector.Configure(() => customLengthConfig); + + Assert.Equal([customLengthConfig, Mass.Info], selector.GetQuantityInfos()); + Assert.Equal(customLengthConfig, selector.CreateOrDefault(() => Length.Info)); + Assert.Equal(Mass.Info, selector.CreateOrDefault(() => Mass.Info)); + } + + [Fact] + public void Configure_AdditionalQuantity_AddsCustomConfiguration() + { + QuantitiesSelector selector = new QuantitiesSelector(() => [Mass.Info]).WithAdditionalQuantities([Length.Info]); + var customLengthConfig = + new QuantityInfo(LengthUnit.Centimeter, Length.LengthInfo.GetDefaultMappings(), BaseDimensions.Dimensionless, Length.From); + + selector.Configure(() => customLengthConfig); + + Assert.Equal([Mass.Info, customLengthConfig], selector.GetQuantityInfos()); + Assert.Equal(customLengthConfig, selector.CreateOrDefault(() => Length.Info)); + Assert.Equal(Mass.Info, selector.CreateOrDefault(() => Mass.Info)); + } + + [Fact] + public void BuildSelection_ReturnsDefaultQuantities_WhenNoAdditionalOrCustomQuantities() + { + var selector = new QuantitiesSelector(() => [Length.Info]); + + IEnumerable result = selector.GetQuantityInfos(); + + Assert.Equal([Length.Info], result); + } +} diff --git a/UnitsNet.Tests/CustomCode/QuantityInfos/Builder/QuantityInfoBuilderExtensionsTest.cs b/UnitsNet.Tests/CustomCode/QuantityInfos/Builder/QuantityInfoBuilderExtensionsTest.cs new file mode 100644 index 0000000000..bd1835a75e --- /dev/null +++ b/UnitsNet.Tests/CustomCode/QuantityInfos/Builder/QuantityInfoBuilderExtensionsTest.cs @@ -0,0 +1,91 @@ +// 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. + +namespace UnitsNet.Tests.QuantityInfos.Builder; + +public class QuantityInfoBuilderExtensionsTest +{ + [Fact] + public void SelectUnits_FiltersCorrectly() + { + LengthUnit[] filterUnits = [LengthUnit.Centimeter, LengthUnit.Inch]; + + IEnumerable> result = Length.LengthInfo.GetDefaultMappings().SelectUnits(filterUnits); + + Assert.Equal(filterUnits, result.Select(u => u.Value).ToArray()); + } + + [Fact] + public void ExcludeUnits_FiltersCorrectly() + { + var unitDefinitions = Length.LengthInfo.GetDefaultMappings() + .Where(x => x.Value is LengthUnit.Centimeter or LengthUnit.Meter or LengthUnit.Foot) + .ToList(); + + IEnumerable> result = unitDefinitions.ExcludeUnits(LengthUnit.Meter, LengthUnit.Centimeter); + + Assert.Single(result, unitDefinition => unitDefinition.Value == LengthUnit.Foot); + } + + [Fact] + public void Configure_UpdatesSpecificUnit() + { + var unitDefinitions = Length.LengthInfo.GetDefaultMappings() + .Where(x => x.Value is LengthUnit.Centimeter or LengthUnit.Meter or LengthUnit.Foot) + .ToList(); + var customMeterDefinition = new UnitDefinition(LengthUnit.Meter, "UpdatedMeter", "UpdatedMeters", BaseUnits.Undefined); + + var result = unitDefinitions.Configure(LengthUnit.Meter, _ => customMeterDefinition).ToList(); + + Assert.Equal("UpdatedMeter", result.First(u => u.Value == LengthUnit.Meter).Name); + Assert.Equal("Centimeter", result.First(u => u.Value == LengthUnit.Centimeter).Name); + Assert.Equal("Foot", result.First(u => u.Value == LengthUnit.Foot).Name); + } + + [Fact] + public void WithConversionFromBase_CreatesNewDefinition() + { + UnitDefinition oldDefinition = Length.LengthInfo.GetDefaultMappings().First(); + + UnitDefinition newDefinition = oldDefinition.WithConversionFromBase(20); + + Assert.Equal(oldDefinition.Value, newDefinition.Value); + Assert.Equal(oldDefinition.Name, newDefinition.Name); + Assert.Equal(oldDefinition.PluralName, newDefinition.PluralName); + Assert.Equal(20, newDefinition.ConversionFromBase); + Assert.Equal(QuantityValue.Inverse(20), newDefinition.ConversionToBase); + Assert.Equal(oldDefinition.BaseUnits, newDefinition.BaseUnits); + } + + [Fact] + public void WithConversionToBase_CreatesNewDefinition() + { + UnitInfo oldDefinition = Length.Info.BaseUnitInfo; + + UnitDefinition newDefinition = oldDefinition.WithConversionToBase(20); + + Assert.Equal(oldDefinition.Value, newDefinition.Value); + Assert.Equal(oldDefinition.Name, newDefinition.Name); + Assert.Equal(oldDefinition.PluralName, newDefinition.PluralName); + Assert.Equal(QuantityValue.Inverse(20), newDefinition.ConversionFromBase); + Assert.Equal(20, newDefinition.ConversionToBase); + Assert.Equal(oldDefinition.BaseUnits, newDefinition.BaseUnits); + } + + [Fact] + public void WithConversionExpression_CreatesNewDefinition() + { + UnitInfo oldDefinition = Length.Info.BaseUnitInfo; + var conversionFromBase = new ConversionExpression(20); + var conversionToBase = new ConversionExpression(0.05); + + UnitDefinition newDefinition = oldDefinition.WithConversionExpression(conversionFromBase, conversionToBase); + + Assert.Equal(oldDefinition.Value, newDefinition.Value); + Assert.Equal(oldDefinition.Name, newDefinition.Name); + Assert.Equal(oldDefinition.PluralName, newDefinition.PluralName); + Assert.Equal(conversionFromBase, newDefinition.ConversionFromBase); + Assert.Equal(conversionToBase, newDefinition.ConversionToBase); + Assert.Equal(oldDefinition.BaseUnits, newDefinition.BaseUnits); + } +} diff --git a/UnitsNet.Tests/CustomCode/QuantityInfos/Builder/QuantityInfoBuilderTest.cs b/UnitsNet.Tests/CustomCode/QuantityInfos/Builder/QuantityInfoBuilderTest.cs new file mode 100644 index 0000000000..10931e1e90 --- /dev/null +++ b/UnitsNet.Tests/CustomCode/QuantityInfos/Builder/QuantityInfoBuilderTest.cs @@ -0,0 +1,55 @@ +// 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 UnitsNet.Units; +using Xunit; + +namespace UnitsNet.Tests.QuantityInfos.Builder; + +public class QuantityInfoBuilderTest +{ + [Fact] + public void Constructor_NullFactory_ThrowsArgumentNullException() + { + Assert.Throws(() => new QuantityInfoBuilder(null!)); + } + + [Fact] + public void Constructor_ValidFactory_DoesNotThrow() + { + var builder = new QuantityInfoBuilder(() => Length.Info); + Assert.NotNull(builder); + } + + [Fact] + public void Build_ValidFactory_ReturnsQuantityInfo() + { + var builder = new QuantityInfoBuilder(() => Length.Info); + + QuantityInfo result = builder.Build(); + + Assert.Same(Length.Info, result); + } + + [Fact] + public void Build_CalledMultipleTimes_ReturnsSameInstance() + { + var builder = new QuantityInfoBuilder(() => Length.Info); + + QuantityInfo firstResult = builder.Build(); + QuantityInfo secondResult = builder.Build(); + + Assert.Same(firstResult, secondResult); + } + + [Fact] + public void Build_InterfaceImplementation_ReturnsQuantityInfo() + { + IQuantityInfoBuilder builder = new QuantityInfoBuilder(() => Length.Info); + + QuantityInfo result = builder.Build(); + + Assert.Same(Length.Info, result); + } +} diff --git a/UnitsNet.Tests/CustomCode/QuantityInfos/QuantityInfoExtensionsTest.cs b/UnitsNet.Tests/CustomCode/QuantityInfos/QuantityInfoExtensionsTest.cs index 24085e6b4a..b68eff6a34 100644 --- a/UnitsNet.Tests/CustomCode/QuantityInfos/QuantityInfoExtensionsTest.cs +++ b/UnitsNet.Tests/CustomCode/QuantityInfos/QuantityInfoExtensionsTest.cs @@ -1,9 +1,7 @@ // 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 UnitsNet.Units; -using Xunit; +using UnitsNet.Tests.CustomQuantities; namespace UnitsNet.Tests.QuantityInfos; @@ -68,4 +66,401 @@ public void GetDefaultUnit_ReturnsTheBaseUnit_WhenGivenADimensionlessQuantity() () => Assert.Equal(AngleUnit.Radian, Angle.Info.GetDefaultUnit(UnitSystem.SI)), () => Assert.Equal(SolidAngleUnit.Steradian, SolidAngle.Info.GetDefaultUnit(UnitSystem.SI))); } + + [Fact] + public void ConvertValueToBaseUnit_ReturnsValueInBaseUnit() + { + Assert.Equal(1000, Length.Info[LengthUnit.Kilometer].ConvertValueToBaseUnit(1)); + } + + [Fact] + public void ConvertValueToFromUnit_ReturnsValueInTargetUnit() + { + Assert.Equal(1, Length.Info[LengthUnit.Kilometer].ConvertValueFromBaseUnit(1000)); + } + + [Fact] + public void GetValueFrom_ReturnsValueInTargetUnit() + { + QuantityValue valueToConvert = 123.45m; + foreach (QuantityInfo quantityInfo in Quantity.Infos) + { + foreach (UnitInfo fromUnit in quantityInfo.UnitInfos) + { + IQuantity fromQuantity = quantityInfo.From(valueToConvert, fromUnit.Value); + foreach (UnitInfo toUnit in quantityInfo.UnitInfos) + { + QuantityValue expectedValue = fromQuantity.As(toUnit.Value); + Assert.Equal(expectedValue, toUnit.GetValueFrom(valueToConvert, fromUnit)); + } + } + } + } + + [Theory] + [InlineData(AreaUnit.SquareMeter, ReciprocalAreaUnit.InverseSquareMeter)] + [InlineData(AreaUnit.SquareCentimeter, ReciprocalAreaUnit.InverseSquareCentimeter)] + [InlineData(AreaUnit.SquareFoot, ReciprocalAreaUnit.InverseSquareFoot)] + [InlineData(AreaUnit.Acre, ReciprocalAreaUnit.InverseSquareMeter)] + public void TryToConvertFrom_QuantityWithInverseDimensions_ToQuantity(AreaUnit fromUnit, ReciprocalAreaUnit expectedUnit) + { + QuantityValue valueToConvert = 100; + UnitInfo fromUnitInfo = Area.Info[fromUnit]; + ReciprocalArea expectedResult = Area.From(valueToConvert, fromUnit).Inverse(); + + var success = ReciprocalArea.Info.TryConvertFrom(valueToConvert, fromUnitInfo, out ReciprocalArea result); + + Assert.True(success); + Assert.Equal(expectedResult, result); + Assert.Equal(expectedUnit, result.Unit); + } + + [Theory] + [InlineData(AreaUnit.SquareMeter, ReciprocalAreaUnit.InverseSquareMeter)] + [InlineData(AreaUnit.SquareCentimeter, ReciprocalAreaUnit.InverseSquareCentimeter)] + [InlineData(AreaUnit.SquareFoot, ReciprocalAreaUnit.InverseSquareFoot)] + [InlineData(AreaUnit.Acre, ReciprocalAreaUnit.InverseSquareMeter)] + public void TryToConvertFrom_QuantityWithInverseDimensions_ToIQuantity(AreaUnit fromUnit, ReciprocalAreaUnit expectedUnit) + { + QuantityValue valueToConvert = 100; + UnitInfo fromUnitInfo = Area.Info[fromUnit]; + QuantityInfo targetQuantityInfo = ReciprocalArea.Info; + + IQuantity expectedResult = Area.From(valueToConvert, fromUnit).Inverse(); + + var success = targetQuantityInfo.TryConvertFrom(valueToConvert, fromUnitInfo, out IQuantity? result); + + Assert.True(success); + Assert.Equal(expectedResult, result); + Assert.Equal(expectedUnit, result!.Unit); + } + + [Theory] + [InlineData(AreaUnit.SquareMeter, ReciprocalAreaUnit.InverseSquareMeter)] + [InlineData(AreaUnit.SquareCentimeter, ReciprocalAreaUnit.InverseSquareCentimeter)] + [InlineData(AreaUnit.SquareFoot, ReciprocalAreaUnit.InverseSquareFoot)] + [InlineData(AreaUnit.Acre, ReciprocalAreaUnit.InverseSquareMeter)] + public void ConvertFrom_QuantityWithInverseDimensions_ToQuantity(AreaUnit fromUnit, ReciprocalAreaUnit expectedUnit) + { + QuantityValue valueToConvert = 100; + UnitInfo fromUnitInfo = Area.Info[fromUnit]; + + ReciprocalArea expectedResult = Area.From(valueToConvert, fromUnit).Inverse(); + + ReciprocalArea convertedQuantity = ReciprocalArea.Info.ConvertFrom(valueToConvert, fromUnitInfo); + + Assert.Equal(expectedResult, convertedQuantity); + Assert.Equal(expectedUnit, convertedQuantity.Unit); + } + + [Theory] + [InlineData(AreaUnit.SquareMeter, ReciprocalAreaUnit.InverseSquareMeter)] + [InlineData(AreaUnit.SquareCentimeter, ReciprocalAreaUnit.InverseSquareCentimeter)] + [InlineData(AreaUnit.SquareFoot, ReciprocalAreaUnit.InverseSquareFoot)] + [InlineData(AreaUnit.Acre, ReciprocalAreaUnit.InverseSquareMeter)] + public void ConvertFrom_QuantityWithInverseDimensions_ToIQuantity(AreaUnit fromUnit, ReciprocalAreaUnit expectedUnit) + { + QuantityValue valueToConvert = 100; + UnitInfo fromUnitInfo = Area.Info[fromUnit]; + QuantityInfo targetQuantityInfo = ReciprocalArea.Info; + + IQuantity expectedResult = Area.From(valueToConvert, fromUnit).Inverse(); + + IQuantity convertedQuantity = targetQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + + Assert.Equal(expectedResult, convertedQuantity); + Assert.Equal(expectedUnit, convertedQuantity.Unit); + } + + [Theory] + [InlineData(MassConcentrationUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicMeter)] + [InlineData(MassConcentrationUnit.GramPerCubicMeter, DensityUnit.GramPerCubicMeter)] + [InlineData(MassConcentrationUnit.PoundPerCubicFoot, DensityUnit.PoundPerCubicFoot)] + [InlineData(MassConcentrationUnit.GramPerLiter, DensityUnit.GramPerLiter)] + [InlineData(MassConcentrationUnit.PoundPerUSGallon, DensityUnit.KilogramPerCubicMeter)] + public void TryToConvertFrom_QuantityWithSameDimensions_ToQuantity(MassConcentrationUnit fromUnit, DensityUnit expectedUnit) + { + QuantityValue valueToConvert = 100; + UnitInfo fromUnitInfo = MassConcentration.Info[fromUnit]; + + var expectedResult = Density.From(MassConcentration.From(valueToConvert, fromUnit).KilogramsPerCubicMeter, DensityUnit.KilogramPerCubicMeter); + + var success = Density.Info.TryConvertFrom(valueToConvert, fromUnitInfo, out Density result); + + Assert.True(success); + Assert.Equal(expectedResult, result); + Assert.Equal(expectedUnit, result.Unit); + } + + [Theory] + [InlineData(MassConcentrationUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicMeter)] + [InlineData(MassConcentrationUnit.GramPerCubicMeter, DensityUnit.GramPerCubicMeter)] + [InlineData(MassConcentrationUnit.PoundPerCubicFoot, DensityUnit.PoundPerCubicFoot)] + [InlineData(MassConcentrationUnit.GramPerLiter, DensityUnit.GramPerLiter)] + [InlineData(MassConcentrationUnit.PoundPerUSGallon, DensityUnit.KilogramPerCubicMeter)] + public void TryToConvertFrom_QuantityWithSameDimensions_ToIQuantity(MassConcentrationUnit fromUnit, DensityUnit expectedUnit) + { + QuantityValue valueToConvert = 100; + UnitInfo fromUnitInfo = MassConcentration.Info[fromUnit]; + QuantityInfo targetQuantityInfo = Density.Info; + + IQuantity expectedResult = Density.From(MassConcentration.From(valueToConvert, fromUnit).KilogramsPerCubicMeter, DensityUnit.KilogramPerCubicMeter); + + var success = targetQuantityInfo.TryConvertFrom(valueToConvert, fromUnitInfo, out IQuantity? result); + + Assert.True(success); + Assert.Equal(expectedResult, result); + Assert.Equal(expectedUnit, result!.Unit); + } + + [Theory] + [InlineData(MassFractionUnit.DecimalFraction, RatioUnit.DecimalFraction)] + [InlineData(MassFractionUnit.Percent, RatioUnit.DecimalFraction)] + [InlineData(MassFractionUnit.GramPerKilogram, RatioUnit.DecimalFraction)] + public void TryToConvertFrom_DimensionlessQuantity_ToQuantity(MassFractionUnit fromUnit, RatioUnit expectedUnit) + { + QuantityValue valueToConvert = 100; + UnitInfo fromUnitInfo = MassFraction.Info[fromUnit]; + + var expectedResult = Ratio.From(MassFraction.From(valueToConvert, fromUnit).DecimalFractions, RatioUnit.DecimalFraction); + + var success = Ratio.Info.TryConvertFrom(valueToConvert, fromUnitInfo, out Ratio result); + + Assert.True(success); + Assert.Equal(expectedResult, result); + Assert.Equal(expectedUnit, result.Unit); + } + + [Theory] + [InlineData(MassFractionUnit.DecimalFraction, RatioUnit.DecimalFraction)] + [InlineData(MassFractionUnit.Percent, RatioUnit.DecimalFraction)] + [InlineData(MassFractionUnit.GramPerKilogram, RatioUnit.DecimalFraction)] + public void TryToConvertFrom_DimensionlessQuantity_ToIQuantity(MassFractionUnit fromUnit, RatioUnit expectedUnit) + { + QuantityValue valueToConvert = 100; + UnitInfo fromUnitInfo = MassFraction.Info[fromUnit]; + + var expectedResult = Ratio.From(MassFraction.From(valueToConvert, fromUnit).DecimalFractions, RatioUnit.DecimalFraction); + + var success = Ratio.Info.TryConvertFrom(valueToConvert, fromUnitInfo, out IQuantity? result); + + Assert.True(success); + Assert.Equal(expectedResult, result); + Assert.Equal(expectedUnit, result!.Unit); + } + + [Theory] + [InlineData(HowMuchUnit.ATon, MassUnit.Tonne, 1)] + [InlineData(HowMuchUnit.Some, MassUnit.Tonne, 0.1)] + [InlineData(HowMuchUnit.AShitTon, MassUnit.Tonne, 10)] + public void TryToConvertFrom_QuantityWithoutSIBase_ToQuantity(HowMuchUnit fromUnit, MassUnit expectedUnit, double expectedValue) + { + QuantityValue valueToConvert = QuantityValue.One; + UnitInfo fromUnitInfo = HowMuch.Info[fromUnit]; + + var success = Mass.Info.TryConvertFrom(valueToConvert, fromUnitInfo, out Mass result); + + Assert.True(success); + Assert.Equal(expectedValue, result.Value); + Assert.Equal(expectedUnit, result.Unit); + } + + [Theory] + [InlineData(MassUnit.Tonne, HowMuchUnit.ATon, 1)] + [InlineData(MassUnit.Kilogram, HowMuchUnit.ATon, 0.001)] + [InlineData(MassUnit.Gram, HowMuchUnit.ATon, 0.000001)] + public void TryToConvertFrom_QuantityWithoutMatchingSIBase_ToIQuantity(MassUnit fromUnit, HowMuchUnit expectedUnit, double expectedValue) + { + QuantityValue valueToConvert = QuantityValue.One; + UnitInfo fromUnitInfo = Mass.Info[fromUnit]; + var success = HowMuch.Info.TryConvertFrom(valueToConvert, fromUnitInfo, out IQuantity? result); + + Assert.True(success); + Assert.Equal(expectedValue, result!.Value); + Assert.Equal(expectedUnit, result.Unit); + } + + [Theory] + [InlineData(TemperatureChangeRateUnit.DegreeKelvinPerSecond, TemperatureChangeRateUnit.DegreeKelvinPerSecond, 1)] + [InlineData(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, 1)] + [InlineData(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, 10)] + public void TryToConvertFrom_QuantityBaseDifferentFromSI_ToQuantity(TemperatureChangeRateUnit fromUnit, TemperatureChangeRateUnit expectedUnit, + double expectedValue) + { + QuantityValue valueToConvert = QuantityValue.One; + UnitInfo fromUnitInfo = TemperatureChangeRate.Info[fromUnit]; + // we simulate a different quantity type, having a non-standard base unit (note: the "official" TemperatureChangeRate is currently using DegreeCelsiusPerSecond) + var customQuantityInfo = new TemperatureChangeRate.TemperatureChangeRateInfo("TestTemperature", TemperatureChangeRateUnit.DegreeKelvinPerSecond, + TemperatureChangeRate.TemperatureChangeRateInfo.GetDefaultMappings(), TemperatureChangeRate.Zero, TemperatureChangeRate.BaseDimensions); + + var success = customQuantityInfo.TryConvertFrom(valueToConvert, fromUnitInfo, out TemperatureChangeRate result); + + Assert.True(success); + Assert.Equal(expectedValue, result.Value); + Assert.Equal(expectedUnit, result.Unit); + } + + [Theory] + [InlineData(TemperatureChangeRateUnit.DegreeKelvinPerSecond, TemperatureChangeRateUnit.DegreeKelvinPerSecond, 1)] + [InlineData(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, 1)] + [InlineData(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, 10)] + public void TryToConvertFrom_QuantityBaseDifferentFromSI_ToIQuantity(TemperatureChangeRateUnit fromUnit, TemperatureChangeRateUnit expectedUnit, + double expectedValue) + { + QuantityValue valueToConvert = QuantityValue.One; + UnitInfo fromUnitInfo = TemperatureChangeRate.Info[fromUnit]; + // we simulate a different quantity type, having a non-standard base unit (note: the "official" TemperatureChangeRate is currently using DegreeCelsiusPerSecond) + QuantityInfo customQuantityInfo = new TemperatureChangeRate.TemperatureChangeRateInfo("TestTemperature", TemperatureChangeRateUnit.DegreeKelvinPerSecond, + TemperatureChangeRate.TemperatureChangeRateInfo.GetDefaultMappings(), TemperatureChangeRate.Zero, TemperatureChangeRate.BaseDimensions); + + var success = customQuantityInfo.TryConvertFrom(valueToConvert, fromUnitInfo, out IQuantity? result); + + Assert.True(success); + Assert.Equal(expectedValue, result!.Value); + Assert.Equal(expectedUnit, result.Unit); + } + + [Theory] + [InlineData(MassConcentrationUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicMeter)] + [InlineData(MassConcentrationUnit.GramPerCubicMeter, DensityUnit.GramPerCubicMeter)] + [InlineData(MassConcentrationUnit.PoundPerCubicFoot, DensityUnit.PoundPerCubicFoot)] + [InlineData(MassConcentrationUnit.GramPerLiter, DensityUnit.GramPerLiter)] + [InlineData(MassConcentrationUnit.PoundPerUSGallon, DensityUnit.KilogramPerCubicMeter)] + public void ConvertFrom_QuantityWithSameDimensions_ToQuantity(MassConcentrationUnit fromUnit, DensityUnit expectedUnit) + { + QuantityValue valueToConvert = 100; + UnitInfo fromUnitInfo = MassConcentration.Info[fromUnit]; + + var expectedResult = Density.From(MassConcentration.From(valueToConvert, fromUnit).KilogramsPerCubicMeter, DensityUnit.KilogramPerCubicMeter); + + Density result = Density.Info.ConvertFrom(valueToConvert, fromUnitInfo); + + Assert.Equal(expectedResult, result); + Assert.Equal(expectedUnit, result.Unit); + } + + [Theory] + [InlineData(MassConcentrationUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicMeter)] + [InlineData(MassConcentrationUnit.GramPerCubicMeter, DensityUnit.GramPerCubicMeter)] + [InlineData(MassConcentrationUnit.PoundPerCubicFoot, DensityUnit.PoundPerCubicFoot)] + [InlineData(MassConcentrationUnit.GramPerLiter, DensityUnit.GramPerLiter)] + [InlineData(MassConcentrationUnit.PoundPerUSGallon, DensityUnit.KilogramPerCubicMeter)] + public void ConvertFrom_QuantityWithSameDimensions_ToIQuantity(MassConcentrationUnit fromUnit, DensityUnit expectedUnit) + { + QuantityValue valueToConvert = 100; + UnitInfo fromUnitInfo = MassConcentration.Info[fromUnit]; + QuantityInfo targetQuantityInfo = Density.Info; + + IQuantity expectedResult = Density.From(MassConcentration.From(valueToConvert, fromUnit).KilogramsPerCubicMeter, DensityUnit.KilogramPerCubicMeter); + + IQuantity result = targetQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + + Assert.Equal(expectedResult, result); + Assert.Equal(expectedUnit, result.Unit); + } + + [Fact] + public void TryToConvertFrom_QuantityWithIncompatibleDimensions_ToQuantity_ReturnsFalse() + { + UnitInfo fromUnitInfo = MassConcentration.Info[MassConcentrationUnit.GramPerCubicMeter]; + + var success = Volume.Info.TryConvertFrom(1, fromUnitInfo, out Volume _); + + Assert.False(success); + } + + [Fact] + public void TryToConvertFrom_QuantityWithIncompatibleDimensions_ToIQuantity_ReturnsFalse() + { + UnitInfo fromUnitInfo = MassConcentration.Info[MassConcentrationUnit.GramPerCubicMeter]; + QuantityInfo targetQuantityInfo = Volume.Info; + + var success = targetQuantityInfo.TryConvertFrom(1, fromUnitInfo, out IQuantity? _); + + Assert.False(success); + } + + [Fact] + public void TryToConvertFrom_QuantityWithNoMatchingBaseUnits_ToQuantity_ReturnsFalse() + { + UnitInfo fromUnitInfo = MassConcentration.Info[MassConcentrationUnit.GramPerCubicMeter]; + // we simulate a target quantity without any base units + var targetQuantityInfo = Density.DensityInfo.CreateDefault(unitInfos => + unitInfos.Select(x => new UnitDefinition(x.Value, x.PluralName, BaseUnits.Undefined))); + + var success = targetQuantityInfo.TryConvertFrom(1, fromUnitInfo, out Density _); + + Assert.False(success); + } + + [Fact] + public void TryToConvertFrom_QuantityWithNoMatchingBaseUnits_ToIQuantity_ReturnsFalse() + { + UnitInfo fromUnitInfo = MassConcentration.Info[MassConcentrationUnit.GramPerCubicMeter]; + // we simulate a target quantity without any base units + QuantityInfo targetQuantityInfo = Density.DensityInfo.CreateDefault(unitInfos => + unitInfos.Select(x => new UnitDefinition(x.Value, x.PluralName, BaseUnits.Undefined))); + + var success = targetQuantityInfo.TryConvertFrom(1, fromUnitInfo, out IQuantity? _); + + Assert.False(success); + } + + [Fact] + public void ConvertFrom_QuantityWithIncompatibleDimensions_ToQuantity_ThrowsInvalidConversionException() + { + UnitInfo fromUnitInfo = MassConcentration.Info[MassConcentrationUnit.GramPerCubicMeter]; + + Assert.Throws(() => Volume.Info.ConvertFrom(1, fromUnitInfo)); + } + + [Fact] + public void ConvertFrom_QuantityWithIncompatibleDimensions_ToIQuantity_ThrowsInvalidConversionException() + { + UnitInfo fromUnitInfo = MassConcentration.Info[MassConcentrationUnit.GramPerCubicMeter]; + QuantityInfo targetQuantityInfo = Volume.Info; + + Assert.Throws(() => targetQuantityInfo.ConvertFrom(1, fromUnitInfo)); + } + + [Fact] + public void ConvertFrom_QuantityWithNoMatchingBaseUnits_ToQuantity_ThrowsInvalidConversionException() + { + UnitInfo fromUnitInfo = MassConcentration.Info[MassConcentrationUnit.GramPerCubicMeter]; + // we simulate a target quantity without any base units + var targetQuantityInfo = Density.DensityInfo.CreateDefault(unitInfos => + unitInfos.Select(x => new UnitDefinition(x.Value, x.PluralName, BaseUnits.Undefined))); + + Assert.Throws(() => targetQuantityInfo.ConvertFrom(1, fromUnitInfo)); + } + + [Fact] + public void ConvertFrom_QuantityWithNoMatchingBaseUnits_ToIQuantity_ThrowsInvalidConversionException() + { + UnitInfo fromUnitInfo = MassConcentration.Info[MassConcentrationUnit.GramPerCubicMeter]; + // we simulate a target quantity without any base units + QuantityInfo targetQuantityInfo = Density.DensityInfo.CreateDefault(unitInfos => + unitInfos.Select(x => new UnitDefinition(x.Value, x.PluralName, BaseUnits.Undefined))); + + Assert.Throws(() => targetQuantityInfo.ConvertFrom(1, fromUnitInfo)); + } + + [Theory] + [InlineData(1, 0, 0, 0, 0, 0, 0)] + [InlineData(0, 1, 0, 0, 0, 0, 0)] + [InlineData(0, 0, 1, 0, 0, 0, 0)] + [InlineData(0, 0, 0, 1, 0, 0, 0)] + [InlineData(0, 0, 0, 0, 1, 0, 0)] + [InlineData(0, 0, 0, 0, 0, 1, 0)] + [InlineData(0, 0, 0, 0, 0, 0, 1)] + public void IsInverse_BaseDimension_ReturnsTheExpectedValue(int length, int mass, int time, int current, int temperature, int amount, int luminousIntensity) + { + var baseDimensions = new BaseDimensions(length, mass, time, current, temperature, amount, luminousIntensity); + var inverseDimensions = new BaseDimensions(-length, -mass, -time, -current, -temperature, -amount, -luminousIntensity); + Assert.True(baseDimensions.IsInverseOf(inverseDimensions)); + Assert.True(inverseDimensions.IsInverseOf(baseDimensions)); + Assert.False(baseDimensions.IsInverseOf(baseDimensions)); + Assert.False(baseDimensions.IsInverseOf(BaseDimensions.Dimensionless)); + Assert.False(BaseDimensions.Dimensionless.IsInverseOf(baseDimensions)); + } } diff --git a/UnitsNet.Tests/CustomCode/RadiationEquivalentDoseRateTests.cs b/UnitsNet.Tests/CustomCode/RadiationEquivalentDoseRateTests.cs index 9016a68d03..555a0b4843 100644 --- a/UnitsNet.Tests/CustomCode/RadiationEquivalentDoseRateTests.cs +++ b/UnitsNet.Tests/CustomCode/RadiationEquivalentDoseRateTests.cs @@ -1,3 +1,19 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by \generate-code.bat. +// +// Changes to this file will be lost when the code is regenerated. +// The build server regenerates the code before each build and a pre-build +// step will regenerate the code on each local build. +// +// See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. +// +// Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. +// Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. +// +// +//------------------------------------------------------------------------------ + // 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. diff --git a/UnitsNet.Tests/CustomCode/TemperatureTests.cs b/UnitsNet.Tests/CustomCode/TemperatureTests.cs index b75e306809..b81bc30ef2 100644 --- a/UnitsNet.Tests/CustomCode/TemperatureTests.cs +++ b/UnitsNet.Tests/CustomCode/TemperatureTests.cs @@ -33,73 +33,73 @@ public void AllBaseQuantityUnitsAreBaseUnits() public static IEnumerable TemperatureDeltaPlusTemperatureEqualsTemperatureData { get; } = [ - [-10d, TemperatureUnit.DegreeCelsius, 0d, TemperatureDeltaUnit.DegreeCelsius, -10d, TemperatureUnit.DegreeCelsius], - [-10d, TemperatureUnit.DegreeCelsius, 10d, TemperatureDeltaUnit.DegreeCelsius, 0d, TemperatureUnit.DegreeCelsius], - [-10d, TemperatureUnit.DegreeCelsius, 20d, TemperatureDeltaUnit.DegreeCelsius, 10d, TemperatureUnit.DegreeCelsius], - [-10d, TemperatureUnit.DegreeFahrenheit, 0d, TemperatureDeltaUnit.DegreeFahrenheit, -10d, TemperatureUnit.DegreeFahrenheit], - [-10d, TemperatureUnit.DegreeFahrenheit, 10d, TemperatureDeltaUnit.DegreeFahrenheit, 0d, TemperatureUnit.DegreeFahrenheit], - [-10d, TemperatureUnit.DegreeFahrenheit, 20d, TemperatureDeltaUnit.DegreeFahrenheit, 10d, TemperatureUnit.DegreeFahrenheit] + [-10m, TemperatureUnit.DegreeCelsius, 0m, TemperatureDeltaUnit.DegreeCelsius, -10m, TemperatureUnit.DegreeCelsius], + [-10m, TemperatureUnit.DegreeCelsius, 10m, TemperatureDeltaUnit.DegreeCelsius, 0m, TemperatureUnit.DegreeCelsius], + [-10m, TemperatureUnit.DegreeCelsius, 20m, TemperatureDeltaUnit.DegreeCelsius, 10m, TemperatureUnit.DegreeCelsius], + [-10m, TemperatureUnit.DegreeFahrenheit, 0m, TemperatureDeltaUnit.DegreeFahrenheit, -10m, TemperatureUnit.DegreeFahrenheit], + [-10m, TemperatureUnit.DegreeFahrenheit, 10m, TemperatureDeltaUnit.DegreeFahrenheit, 0m, TemperatureUnit.DegreeFahrenheit], + [-10m, TemperatureUnit.DegreeFahrenheit, 20m, TemperatureDeltaUnit.DegreeFahrenheit, 10m, TemperatureUnit.DegreeFahrenheit] ]; [Theory] [MemberData(nameof(TemperatureDeltaPlusTemperatureEqualsTemperatureData))] - public void TemperatureDeltaPlusTemperatureEqualsTemperature(double temperatureValue, TemperatureUnit temperatureUnit, double deltaValue, - TemperatureDeltaUnit deltaUnit, double expectedValue, TemperatureUnit expectedUnit) + public void TemperatureDeltaPlusTemperatureEqualsTemperature(decimal temperatureValue, TemperatureUnit temperatureUnit, decimal deltaValue, + TemperatureDeltaUnit deltaUnit, decimal expectedValue, TemperatureUnit expectedUnit) { var temperature = new Temperature(temperatureValue, temperatureUnit); var temperatureDelta = new TemperatureDelta(deltaValue, deltaUnit); var expectedTemperature = new Temperature(expectedValue, expectedUnit); - + Temperature result = temperature + temperatureDelta; - - Assert.True(expectedTemperature.Equals(result, TemperatureDelta.FromKelvins(KelvinsTolerance))); + + Assert.Equal(expectedTemperature, result); } public static IEnumerable TemperatureMinusTemperatureDeltaEqualsTemperatureData { get; } = [ - [20d, TemperatureUnit.DegreeCelsius, 10d, TemperatureDeltaUnit.DegreeCelsius, 10d, TemperatureUnit.DegreeCelsius], - [20d, TemperatureUnit.DegreeCelsius, 20d, TemperatureDeltaUnit.DegreeCelsius, 0d, TemperatureUnit.DegreeCelsius], - [20d, TemperatureUnit.DegreeCelsius, 30d, TemperatureDeltaUnit.DegreeCelsius, -10d, TemperatureUnit.DegreeCelsius], - [20d, TemperatureUnit.DegreeFahrenheit, 10d, TemperatureDeltaUnit.DegreeFahrenheit, 10d, TemperatureUnit.DegreeFahrenheit], - [20d, TemperatureUnit.DegreeFahrenheit, 20d, TemperatureDeltaUnit.DegreeFahrenheit, 0d, TemperatureUnit.DegreeFahrenheit], - [20d, TemperatureUnit.DegreeFahrenheit, 30d, TemperatureDeltaUnit.DegreeFahrenheit, -10d, TemperatureUnit.DegreeFahrenheit] + [20m, TemperatureUnit.DegreeCelsius, 10m, TemperatureDeltaUnit.DegreeCelsius, 10m, TemperatureUnit.DegreeCelsius], + [20m, TemperatureUnit.DegreeCelsius, 20m, TemperatureDeltaUnit.DegreeCelsius, 0m, TemperatureUnit.DegreeCelsius], + [20m, TemperatureUnit.DegreeCelsius, 30m, TemperatureDeltaUnit.DegreeCelsius, -10m, TemperatureUnit.DegreeCelsius], + [20m, TemperatureUnit.DegreeFahrenheit, 10m, TemperatureDeltaUnit.DegreeFahrenheit, 10m, TemperatureUnit.DegreeFahrenheit], + [20m, TemperatureUnit.DegreeFahrenheit, 20m, TemperatureDeltaUnit.DegreeFahrenheit, 0m, TemperatureUnit.DegreeFahrenheit], + [20m, TemperatureUnit.DegreeFahrenheit, 30m, TemperatureDeltaUnit.DegreeFahrenheit, -10m, TemperatureUnit.DegreeFahrenheit] ]; [Theory] [MemberData(nameof(TemperatureMinusTemperatureDeltaEqualsTemperatureData))] - public void TemperatureMinusTemperatureDeltaEqualsTemperature(double temperatureValue, TemperatureUnit temperatureUnit, double deltaValue, - TemperatureDeltaUnit deltaUnit, double expectedValue, TemperatureUnit expectedUnit) + public void TemperatureMinusTemperatureDeltaEqualsTemperature(decimal temperatureValue, TemperatureUnit temperatureUnit, decimal deltaValue, + TemperatureDeltaUnit deltaUnit, decimal expectedValue, TemperatureUnit expectedUnit) { var temp = new Temperature(temperatureValue, temperatureUnit); var delta = new TemperatureDelta(deltaValue, deltaUnit); var expectedTemperature = new Temperature(expectedValue, expectedUnit); - + Temperature result = temp - delta; - - Assert.True(expectedTemperature.Equals(result, TemperatureDelta.FromKelvins(KelvinsTolerance))); + + Assert.Equal(expectedTemperature, result); } public static IEnumerable TemperaturePlusTemperatureDeltaEqualsTemperatureData { get; } = [ - [-10d, TemperatureUnit.DegreeCelsius, 0d, TemperatureDeltaUnit.DegreeCelsius, -10d, TemperatureUnit.DegreeCelsius], - [-10d, TemperatureUnit.DegreeCelsius, 10d, TemperatureDeltaUnit.DegreeCelsius, 0d, TemperatureUnit.DegreeCelsius], - [-10d, TemperatureUnit.DegreeCelsius, 20d, TemperatureDeltaUnit.DegreeCelsius, 10d, TemperatureUnit.DegreeCelsius], - [-10d, TemperatureUnit.DegreeFahrenheit, 0d, TemperatureDeltaUnit.DegreeFahrenheit, -10d, TemperatureUnit.DegreeFahrenheit], - [-10d, TemperatureUnit.DegreeFahrenheit, 10d, TemperatureDeltaUnit.DegreeFahrenheit, 0d, TemperatureUnit.DegreeFahrenheit], - [-10d, TemperatureUnit.DegreeFahrenheit, 20d, TemperatureDeltaUnit.DegreeFahrenheit, 10d, TemperatureUnit.DegreeFahrenheit] + [-10m, TemperatureUnit.DegreeCelsius, 0m, TemperatureDeltaUnit.DegreeCelsius, -10m, TemperatureUnit.DegreeCelsius], + [-10m, TemperatureUnit.DegreeCelsius, 10m, TemperatureDeltaUnit.DegreeCelsius, 0m, TemperatureUnit.DegreeCelsius], + [-10m, TemperatureUnit.DegreeCelsius, 20m, TemperatureDeltaUnit.DegreeCelsius, 10m, TemperatureUnit.DegreeCelsius], + [-10m, TemperatureUnit.DegreeFahrenheit, 0m, TemperatureDeltaUnit.DegreeFahrenheit, -10m, TemperatureUnit.DegreeFahrenheit], + [-10m, TemperatureUnit.DegreeFahrenheit, 10m, TemperatureDeltaUnit.DegreeFahrenheit, 0m, TemperatureUnit.DegreeFahrenheit], + [-10m, TemperatureUnit.DegreeFahrenheit, 20m, TemperatureDeltaUnit.DegreeFahrenheit, 10m, TemperatureUnit.DegreeFahrenheit] ]; [Theory] [MemberData(nameof(TemperaturePlusTemperatureDeltaEqualsTemperatureData))] - public void TemperaturePlusTemperatureDeltaEqualsTemperature(double temperatureValue, TemperatureUnit temperatureUnit, double deltaValue, - TemperatureDeltaUnit deltaUnit, double expectedValue, TemperatureUnit expectedUnit) + public void TemperaturePlusTemperatureDeltaEqualsTemperature(decimal temperatureValue, TemperatureUnit temperatureUnit, decimal deltaValue, + TemperatureDeltaUnit deltaUnit, decimal expectedValue, TemperatureUnit expectedUnit) { var temp = new Temperature(temperatureValue, temperatureUnit); var delta = new TemperatureDelta(deltaValue, deltaUnit); var expectedTemperature = new Temperature(expectedValue, expectedUnit); - + Temperature result = temp + delta; - - Assert.True(expectedTemperature.Equals(result, TemperatureDelta.FromKelvins(KelvinsTolerance))); + + Assert.Equal(expectedTemperature, result); } } diff --git a/UnitsNet.Tests/CustomCode/ThermalInsulanceTests.cs b/UnitsNet.Tests/CustomCode/ThermalInsulanceTests.cs index 12acb2d0aa..d7dab49423 100644 --- a/UnitsNet.Tests/CustomCode/ThermalInsulanceTests.cs +++ b/UnitsNet.Tests/CustomCode/ThermalInsulanceTests.cs @@ -32,6 +32,15 @@ public class ThermalInsulanceTests : ThermalInsulanceTestsBase protected override double SquareMeterKelvinsPerWattInOneSquareMeterKelvinPerKilowatt => 0.001; protected override double SquareMillimeterKelvinsPerWattInOneSquareMeterKelvinPerKilowatt => 1000; + // TODO see about changing the base unit + + // protected override double HourSquareFeetDegreesFahrenheitPerBtuInOneSquareMeterKelvinPerWatt => 5.678263337; + // protected override double SquareCentimeterHourDegreesCelsiusPerKilocalorieInOneSquareMeterKelvinPerWatt => 418.68; + // protected override double SquareCentimeterKelvinsPerWattInOneSquareMeterKelvinPerWatt => 1e4; + // protected override double SquareMeterDegreesCelsiusPerWattInOneSquareMeterKelvinPerWatt => 1; + // protected override double SquareMeterKelvinsPerKilowattInOneSquareMeterKelvinPerWatt => 1e-3; + // protected override double SquareMeterKelvinsPerWattInOneSquareMeterKelvinPerWatt => 1; + [Fact(Skip = "See about changing the BaseUnit to SquareMeterKelvinPerWatt")] public override void BaseUnit_HasSIBase() { diff --git a/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ArithmeticOperations.cs b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ArithmeticOperations.cs new file mode 100644 index 0000000000..dec9c89048 --- /dev/null +++ b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ArithmeticOperations.cs @@ -0,0 +1,736 @@ +using Xunit.Abstractions; + +namespace UnitsNet.Tests; + +public partial class QuantityValueTests +{ + public class ArithmeticOperatorTests + { + [Theory] + [ClassData(typeof(AdditionTestData))] + public void AdditionOperatorTests(OperatorTestCase testCase) + { + var (value1, value2, expectedValue) = testCase; + Assert.Multiple(() => + { + // the operation is implemented as expected + Assert.Equal(expectedValue, value1 + value2); + Assert.Equal(expectedValue, value2 + value1); + }, () => + { +#if NET + // double-checking that the expectations are correct + var doubleResult = (double)value1 + (double)value2; + if (double.IsFinite(doubleResult)) + { + Assert.Equal((double)expectedValue, doubleResult, 15); + } + else + { + Assert.Equal((double)expectedValue, doubleResult); + } +#endif + }); + } + + [Fact] + public void UnaryIncrementOperator_IncrementsTheValueByOne() + { + var value = new QuantityValue(1, 2); + value++; + Assert.Equal(new QuantityValue(3, 2), value); + } + + [Fact] + public void PlusOperator_ReturnsTheSameValue() + { + Assert.Equal(QuantityValue.One, +QuantityValue.One); + Assert.Equal(QuantityValue.MinusOne, +QuantityValue.MinusOne); + Assert.Equal(QuantityValue.Zero, +QuantityValue.Zero); + } + + [Fact] + public void MinusOperator_ReturnsTheNegatedValue() + { + Assert.Equal(QuantityValue.MinusOne, -QuantityValue.One); + Assert.Equal(QuantityValue.One, -QuantityValue.MinusOne); + Assert.Equal(QuantityValue.Zero, -QuantityValue.Zero); + } + + [Theory] + [ClassData(typeof(SubtractionTestData))] + public void SubtractionOperatorTests(OperatorTestCase testCase) + { + var (value1, value2, expectedValue) = testCase; + Assert.Multiple(() => + { + // the operation is implemented as expected + Assert.Equal(expectedValue, value1 - value2); + }, () => + { +#if NET + // double-checking that the expectations are correct + var doubleResult = (double)value1 - (double)value2; + if (double.IsFinite(doubleResult)) + { + Assert.Equal((double)expectedValue, doubleResult, 15); + } + else + { + Assert.Equal((double)expectedValue, doubleResult); + } +#endif + }); + } + + [Fact] + public void UnaryDecrementOperator_DecrementsTheValueByOne() + { + var value = new QuantityValue(1, 2); + value--; + Assert.Equal(new QuantityValue(-1, 2), value); + } + + [Theory] + [ClassData(typeof(MultiplicationTestData))] + public void MultiplicationOperatorTests(OperatorTestCase testCase) + { + var (value1, value2, expectedValue) = testCase; + Assert.Multiple(() => + { + // the operation is implemented as expected + Assert.Equal(expectedValue, value1 * value2); + Assert.Equal(expectedValue, value2 * value1); + }, () => + { +#if NET + // double-checking that the expectations are correct + var doubleResult = (double)value1 * (double)value2; + if (double.IsFinite(doubleResult)) + { + Assert.Equal((double)expectedValue, doubleResult, 15); + } + else + { + Assert.Equal((double)expectedValue, doubleResult); + } +#endif + }); + } + + [Theory] + [ClassData(typeof(DivisionTestData))] + public void DivisionOperatorTests(OperatorTestCase testCase) + { + var (value1, value2, expectedValue) = testCase; + Assert.Multiple(() => + { + // the operation is implemented as expected + Assert.Equal(expectedValue, value1 / value2); + }, () => + { +#if NET + // double-checking that the expectations are correct + var doubleResult = (double)value1 / (double)value2; + if (double.IsFinite(doubleResult)) + { + Assert.Equal((double)expectedValue, doubleResult, 14); + } + else + { + Assert.Equal((double)expectedValue, doubleResult); + } +#endif + }); + } + + [Theory] + [ClassData(typeof(ModulusTestData))] + public void ModulusOperatorTests(OperatorTestCase testCase) + { + var (value1, value2, expectedValue) = testCase; + Assert.Multiple(() => + { + // the operation is implemented as expected + Assert.Equal(expectedValue, value1 % value2); + }, () => + { +#if NET + // double-checking that the expectations are correct + var doubleResult = (double)value1 % (double)value2; + if (double.IsFinite(doubleResult)) + { + Assert.Equal((double)expectedValue, doubleResult, 15); + } + else + { + Assert.Equal((double)expectedValue, doubleResult); + } +#endif + }); + } + + public abstract record OperatorTestCase : IXunitSerializable + { + protected OperatorTestCase(QuantityValue value1, QuantityValue value2, QuantityValue expectedValue) + { + Value1 = value1; + Value2 = value2; + ExpectedValue = expectedValue; + } + + public QuantityValue Value1 { get; private set; } + public QuantityValue Value2 { get; private set; } + public QuantityValue ExpectedValue { get; private set; } + + public void Deconstruct(out QuantityValue value1, out QuantityValue value2, out QuantityValue expectedValue) + { + value1 = Value1; + value2 = Value2; + expectedValue = ExpectedValue; + } + + #region Implementation of IXunitSerializable + + public OperatorTestCase() + { + } + + public void Serialize(IXunitSerializationInfo info) + { + info.AddValue("v1", (QuantityValueData)Value1); + info.AddValue("v2", (QuantityValueData)Value2); + info.AddValue("expected", (QuantityValueData)ExpectedValue); + } + + public void Deserialize(IXunitSerializationInfo info) + { + Value1 = info.GetValue("v1"); + Value2 = info.GetValue("v2"); + ExpectedValue = info.GetValue("expected"); + } + + #endregion + } + + public sealed class AdditionTestData : TheoryData + { + public AdditionTestData() + { + // zero + Add(QuantityValue.Zero, new QuantityValue(0, 10), QuantityValue.Zero); + Add(QuantityValue.Zero, QuantityValue.One, QuantityValue.One); + Add(QuantityValue.Zero, QuantityValue.MinusOne, QuantityValue.MinusOne); + + // positive + // 4.2 + 0.5 = 4.7 + Add(new QuantityValue(42, 10), + new QuantityValue(1, 2), + new QuantityValue(47, 10)); + // 4.2 + (-0.333..) = 3.666.. + Add(new QuantityValue(42, 10), + new QuantityValue(-1, 3), + new QuantityValue(116, 30)); + + // negative + // -4.2 + 0.5 = -3.7 + Add(new QuantityValue(-42, 10), + new QuantityValue(1, 2), + new QuantityValue(-37, 10)); + + // -4.2 + (-0.333..) = -4.533.. + Add(new QuantityValue(-42, 10), + new QuantityValue(-1, 3), + new QuantityValue(-136, 30)); + + // positive infinity + Add(QuantityValue.PositiveInfinity, QuantityValue.Zero, QuantityValue.PositiveInfinity); + Add(QuantityValue.PositiveInfinity, QuantityValue.One, QuantityValue.PositiveInfinity); + Add(QuantityValue.PositiveInfinity, QuantityValue.MinusOne, QuantityValue.PositiveInfinity); + Add(QuantityValue.PositiveInfinity, new QuantityValue(10, 0), QuantityValue.PositiveInfinity); + Add(QuantityValue.PositiveInfinity, new QuantityValue(-10, 0), QuantityValue.NaN); + + // negative infinity + Add(QuantityValue.NegativeInfinity, QuantityValue.Zero, QuantityValue.NegativeInfinity); + Add(QuantityValue.NegativeInfinity, QuantityValue.One, QuantityValue.NegativeInfinity); + Add(QuantityValue.NegativeInfinity, QuantityValue.MinusOne, QuantityValue.NegativeInfinity); + Add(QuantityValue.NegativeInfinity, new QuantityValue(-10, 0), QuantityValue.NegativeInfinity); + Add(QuantityValue.NegativeInfinity, new QuantityValue(10, 0), QuantityValue.NaN); + + // NaN + Add(QuantityValue.NaN, QuantityValue.NaN, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.Zero, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.One, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.MinusOne, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.PositiveInfinity, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.NegativeInfinity, QuantityValue.NaN); + } + + private void Add(QuantityValue value1, QuantityValue value2, QuantityValue expectedValue) + { + Add(new AdditionOperationTestCase(value1, value2, expectedValue)); + } + + public sealed record AdditionOperationTestCase : OperatorTestCase + { + public AdditionOperationTestCase() + { + } + + public AdditionOperationTestCase(QuantityValue value1, QuantityValue value2, QuantityValue expectedValue) + : base(value1, value2, expectedValue) + { + } + + public override string ToString() + { + // return $"{Value1} + {Value2} = {ExpectedValue}"; + return $"{Value1.Numerator}/{Value1.Denominator} + {Value2.Numerator}/{Value2.Denominator} = {ExpectedValue.Numerator}/{ExpectedValue.Denominator}"; + } + } + } + + public sealed class SubtractionTestData : TheoryData + { + public SubtractionTestData() + { + // zero + Add(QuantityValue.Zero, new QuantityValue(0, 10), QuantityValue.Zero); + Add(QuantityValue.Zero, QuantityValue.One, QuantityValue.MinusOne); + Add(QuantityValue.Zero, QuantityValue.MinusOne, QuantityValue.One); + + // positive + // 4.2 - 0.5 = 3.7 + Add(new QuantityValue(42, 10), + new QuantityValue(1, 2), + new QuantityValue(37, 10)); + // 4.2 - (-0.333..) = 4.533.. + Add(new QuantityValue(42, 10), + new QuantityValue(-1, 3), + new QuantityValue(136, 30)); + + // negative + // -4.2 - 0.5 = -4.7 + Add(new QuantityValue(-42, 10), + new QuantityValue(1, 2), + new QuantityValue(-47, 10)); + + // -4.2 - (-0.333..) = -3.866.. + Add(new QuantityValue(-42, 10), + new QuantityValue(-1, 3), + new QuantityValue(-116, 30)); + + // positive infinity + Add(QuantityValue.PositiveInfinity, QuantityValue.Zero, QuantityValue.PositiveInfinity); + Add(QuantityValue.PositiveInfinity, QuantityValue.One, QuantityValue.PositiveInfinity); + Add(QuantityValue.PositiveInfinity, QuantityValue.MinusOne, QuantityValue.PositiveInfinity); + Add(QuantityValue.PositiveInfinity, new QuantityValue(10, 0), QuantityValue.NaN); + Add(QuantityValue.PositiveInfinity, new QuantityValue(-10, 0), QuantityValue.PositiveInfinity); + + // negative infinity + Add(QuantityValue.NegativeInfinity, QuantityValue.Zero, QuantityValue.NegativeInfinity); + Add(QuantityValue.NegativeInfinity, QuantityValue.One, QuantityValue.NegativeInfinity); + Add(QuantityValue.NegativeInfinity, QuantityValue.MinusOne, QuantityValue.NegativeInfinity); + Add(QuantityValue.NegativeInfinity, new QuantityValue(-10, 0), QuantityValue.NaN); + Add(QuantityValue.NegativeInfinity, new QuantityValue(10, 0), QuantityValue.NegativeInfinity); + + // NaN + Add(QuantityValue.NaN, QuantityValue.NaN, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.Zero, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.One, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.MinusOne, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.PositiveInfinity, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.NegativeInfinity, QuantityValue.NaN); + } + + private void Add(QuantityValue value1, QuantityValue value2, QuantityValue expectedValue) + { + Add(new SubtractionOperationTestCase(value1, value2, expectedValue)); + } + + public sealed record SubtractionOperationTestCase : OperatorTestCase + { + public SubtractionOperationTestCase() + { + } + + public SubtractionOperationTestCase(QuantityValue value1, QuantityValue value2, QuantityValue expectedValue) + : base(value1, value2, expectedValue) + { + } + + public override string ToString() + { + // return $"{Value1} - {Value2} = {ExpectedValue}"; + return $"{Value1.Numerator}/{Value1.Denominator} - {Value2.Numerator}/{Value2.Denominator} = {ExpectedValue.Numerator}/{ExpectedValue.Denominator}"; + } + } + } + + public sealed class MultiplicationTestData : TheoryData + { + public MultiplicationTestData() + { + // zero + Add(QuantityValue.Zero, new QuantityValue(0, 10), QuantityValue.Zero); + Add(QuantityValue.Zero, QuantityValue.One, QuantityValue.Zero); + Add(QuantityValue.Zero, QuantityValue.MinusOne, QuantityValue.Zero); + + // positive + // 4.2 * 0.5 = 2.1 + Add(new QuantityValue(42, 10), + new QuantityValue(1, 2), + new QuantityValue(21, 10)); + // 4.2 * (-0.333..) = -1.4 + Add(new QuantityValue(42, 10), + new QuantityValue(-1, 3), + new QuantityValue(-14, 10)); + + // negative + // -4.2 * 0.5 = -2.1 + Add(new QuantityValue(-42, 10), + new QuantityValue(1, 2), + new QuantityValue(-21, 10)); + + // -4.2 * (-0.333..) = 1.4 + Add(new QuantityValue(-42, 10), + new QuantityValue(-1, 3), + new QuantityValue(14, 10)); + + // positive infinity + Add(QuantityValue.PositiveInfinity, QuantityValue.Zero, QuantityValue.NaN); + Add(QuantityValue.PositiveInfinity, QuantityValue.One, QuantityValue.PositiveInfinity); + Add(QuantityValue.PositiveInfinity, QuantityValue.MinusOne, QuantityValue.NegativeInfinity); + Add(QuantityValue.PositiveInfinity, new QuantityValue(10, 0), QuantityValue.PositiveInfinity); + Add(QuantityValue.PositiveInfinity, new QuantityValue(-10, 0), QuantityValue.NegativeInfinity); + + // negative infinity + Add(QuantityValue.NegativeInfinity, QuantityValue.Zero, QuantityValue.NaN); + Add(QuantityValue.NegativeInfinity, QuantityValue.One, QuantityValue.NegativeInfinity); + Add(QuantityValue.NegativeInfinity, QuantityValue.MinusOne, QuantityValue.PositiveInfinity); + Add(QuantityValue.NegativeInfinity, new QuantityValue(-10, 0), QuantityValue.PositiveInfinity); + Add(QuantityValue.NegativeInfinity, new QuantityValue(10, 0), QuantityValue.NegativeInfinity); + + // NaN + Add(QuantityValue.NaN, QuantityValue.NaN, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.Zero, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.One, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.MinusOne, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.PositiveInfinity, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.NegativeInfinity, QuantityValue.NaN); + } + + private void Add(QuantityValue value1, QuantityValue value2, QuantityValue expectedValue) + { + Add(new MultiplicationOperationTestCase(value1, value2, expectedValue)); + } + + public sealed record MultiplicationOperationTestCase : OperatorTestCase + { + public MultiplicationOperationTestCase() + { + } + + public MultiplicationOperationTestCase(QuantityValue value1, QuantityValue value2, QuantityValue expectedValue) + : base(value1, value2, expectedValue) + { + } + + public override string ToString() + { + // return $"{Value1} * {Value2} = {ExpectedValue}"; + return $"{Value1.Numerator}/{Value1.Denominator} * {Value2.Numerator}/{Value2.Denominator} = {ExpectedValue.Numerator}/{ExpectedValue.Denominator}"; + } + } + } + + public sealed class DivisionTestData : TheoryData + { + public DivisionTestData() + { + // zero + Add(QuantityValue.Zero, new QuantityValue(0, 10), QuantityValue.NaN); + Add(QuantityValue.Zero, QuantityValue.NaN, QuantityValue.NaN); + Add(QuantityValue.Zero, QuantityValue.One, QuantityValue.Zero); + Add(QuantityValue.Zero, QuantityValue.MinusOne, QuantityValue.Zero); + + // division by zero + Add(QuantityValue.One, QuantityValue.Zero, QuantityValue.PositiveInfinity); + Add(QuantityValue.MinusOne, QuantityValue.Zero, QuantityValue.NegativeInfinity); + + #region positive / positive + + // 4.2 / 1 = 8.4 + Add(new QuantityValue(42, 10), + new QuantityValue(1, 1), + new QuantityValue(42, 10)); + + // 4.2 / 0.5 = 8.4 + Add(new QuantityValue(42, 10), + new QuantityValue(1, 2), + new QuantityValue(84, 10)); + + // 4.2 / 1.5 = 2.8 + Add(new QuantityValue(42, 10), + new QuantityValue(3, 2), + new QuantityValue(28, 10)); + + // 4.2 / 2 = 2.1 + Add(new QuantityValue(42, 10), + new QuantityValue(2, 1), + new QuantityValue(21, 10)); + + // 42 / 2 = 21 + Add(new QuantityValue(42, 1), + new QuantityValue(2, 1), + new QuantityValue(21, 1)); + + // 1 / 45.6 = {10/456} + Add(new QuantityValue(1, 1), + new QuantityValue(456, 10), + new QuantityValue(10, 456)); + + // 0.025 / 0.01 = 2.5 + Add(new QuantityValue(1, 40), + new QuantityValue(1, 100), + new QuantityValue(100, 40)); + + // 0.05 / 0.01 = 5 + Add(new QuantityValue(2, 40), + new QuantityValue(1, 100), + new QuantityValue(200, 40)); + + // 0.25 / 4.2 = {5/84} + Add(new QuantityValue(1, 4), + new QuantityValue(42, 10), + new QuantityValue(5, 84)); + + // 0.33.. / 4.2 = {10/126} + Add(new QuantityValue(1, 3), + new QuantityValue(42, 10), + new QuantityValue(10, 126)); + + // 0.5 / 4.2 = {10/84} + Add(new QuantityValue(1, 2), + new QuantityValue(42, 10), + new QuantityValue(10, 84)); + + // 1.5 / 4.2 = {30/84} + Add(new QuantityValue(3, 2), + new QuantityValue(42, 10), + new QuantityValue(30, 84)); + + // 123 / 45.6 = {1230/456} + Add(new QuantityValue(123, 1), + new QuantityValue(456, 10), + new QuantityValue(1230, 456)); + + #endregion + + #region positive / negative + + // 4.2 / -0.333.. = -12.6 + Add(new QuantityValue(42, 10), + new QuantityValue(-1, 3), + new QuantityValue(-126, 10)); + + // 4.2 / -0.5 = -8.4 + Add(new QuantityValue(42, 10), + new QuantityValue(-1, 2), + new QuantityValue(-84, 10)); + + // 0.01 / -0.05 = -0.2 + Add(new QuantityValue(1, 100), + new QuantityValue(-2, 40), + new QuantityValue(-40, 200)); + + #endregion + + #region negative / positive + + // -4.2 / 1 = -8.4 + Add(new QuantityValue(-42, 10), + new QuantityValue(1, 1), + new QuantityValue(-42, 10)); + + // -4.2 / 0.5 = -8.4 + Add(new QuantityValue(-42, 10), + new QuantityValue(1, 2), + new QuantityValue(-84, 10)); + + // -4.2 / 1.5 = 2.8 + Add(new QuantityValue(-42, 10), + new QuantityValue(3, 2), + new QuantityValue(-28, 10)); + + // -4.2 / 2 = -2.1 + Add(new QuantityValue(-42, 10), + new QuantityValue(2, 1), + new QuantityValue(-21, 10)); + + // -42 / 2 = -21 + Add(new QuantityValue(-42, 1), + new QuantityValue(2, 1), + new QuantityValue(-21, 1)); + + // -1 / 45.6 = {10/456} + Add(new QuantityValue(-1, 1), + new QuantityValue(456, 10), + new QuantityValue(-10, 456)); + + // -0.025 / 0.01 = 2.5 + Add(new QuantityValue(-1, 40), + new QuantityValue(1, 100), + new QuantityValue(-100, 40)); + + // -0.05 / 0.01 = 5 + Add(new QuantityValue(-2, 40), + new QuantityValue(1, 100), + new QuantityValue(-200, 40)); + + // -0.25 / 4.2 = {5/84} + Add(new QuantityValue(-1, 4), + new QuantityValue(42, 10), + new QuantityValue(-5, 84)); + + // -0.33.. / 4.2 = {10/126} + Add(new QuantityValue(-1, 3), + new QuantityValue(42, 10), + new QuantityValue(-10, 126)); + + // -0.5 / 4.2 = {-10/84} + Add(new QuantityValue(-1, 2), + new QuantityValue(42, 10), + new QuantityValue(-10, 84)); + + // -1.5 / 4.2 = {-30/84} + Add(new QuantityValue(-3, 2), + new QuantityValue(42, 10), + new QuantityValue(-30, 84)); + + // -123 / 45.6 = {-1230/456} + Add(new QuantityValue(-123, 1), + new QuantityValue(456, 10), + new QuantityValue(-1230, 456)); + + #endregion + + #region negative / negative + + // -4.2 / (-0.333..) = 12.6 + Add(new QuantityValue(-42, 10), + new QuantityValue(-1, 3), + new QuantityValue(126, 10)); + + // -4.2 / -0.5 = 8.4 + Add(new QuantityValue(-42, 10), + new QuantityValue(-1, 2), + new QuantityValue(84, 10)); + + // -0.01 / -0.05 = 0.2 + Add(new QuantityValue(-1, 100), + new QuantityValue(-2, 40), + new QuantityValue(40, 200)); + + #endregion + + // positive infinity + Add(QuantityValue.PositiveInfinity, QuantityValue.Zero, QuantityValue.PositiveInfinity); + Add(QuantityValue.PositiveInfinity, QuantityValue.One, QuantityValue.PositiveInfinity); + Add(QuantityValue.PositiveInfinity, QuantityValue.MinusOne, QuantityValue.NegativeInfinity); + Add(QuantityValue.PositiveInfinity, new QuantityValue(10, 0), QuantityValue.NaN); + Add(QuantityValue.PositiveInfinity, new QuantityValue(-10, 0), QuantityValue.NaN); + + // division by positive infinity + Add(QuantityValue.Zero, QuantityValue.PositiveInfinity, QuantityValue.Zero); + Add(QuantityValue.One, QuantityValue.PositiveInfinity, QuantityValue.Zero); + Add(QuantityValue.MinusOne, QuantityValue.PositiveInfinity, QuantityValue.Zero); + + // negative infinity + Add(QuantityValue.NegativeInfinity, QuantityValue.Zero, QuantityValue.NegativeInfinity); + Add(QuantityValue.NegativeInfinity, QuantityValue.One, QuantityValue.NegativeInfinity); + Add(QuantityValue.NegativeInfinity, QuantityValue.MinusOne, QuantityValue.PositiveInfinity); + Add(QuantityValue.NegativeInfinity, new QuantityValue(-10, 0), QuantityValue.NaN); + Add(QuantityValue.NegativeInfinity, new QuantityValue(10, 0), QuantityValue.NaN); + + // division by negative infinity + Add(QuantityValue.Zero, QuantityValue.NegativeInfinity, QuantityValue.Zero); + Add(QuantityValue.One, QuantityValue.NegativeInfinity, QuantityValue.Zero); + Add(QuantityValue.MinusOne, QuantityValue.NegativeInfinity, QuantityValue.Zero); + + // NaN + Add(QuantityValue.NaN, QuantityValue.NaN, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.Zero, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.One, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.MinusOne, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.PositiveInfinity, QuantityValue.NaN); + Add(QuantityValue.NaN, QuantityValue.NegativeInfinity, QuantityValue.NaN); + } + + private void Add(QuantityValue value1, QuantityValue value2, QuantityValue expectedValue) + { + Add(new DivisionOperationTestCase(value1, value2, expectedValue)); + } + + public sealed record DivisionOperationTestCase : OperatorTestCase + { + public DivisionOperationTestCase() + { + } + + public DivisionOperationTestCase(QuantityValue value1, QuantityValue value2, QuantityValue expectedValue) + : base(value1, value2, expectedValue) + { + } + + public override string ToString() + { + // return $"{Value1} / {Value2} = {ExpectedValue}"; + return $"{Value1.Numerator}/{Value1.Denominator} / {Value2.Numerator}/{Value2.Denominator} = {ExpectedValue.Numerator}/{ExpectedValue.Denominator}"; + } + } + } + + public sealed class ModulusTestData : TheoryData + { + public ModulusTestData() + { + Add(QuantityValue.One, QuantityValue.Zero, QuantityValue.NaN); + Add(QuantityValue.Zero, QuantityValue.NaN, QuantityValue.NaN); + Add(QuantityValue.Zero, QuantityValue.One, QuantityValue.Zero); + Add(QuantityValue.PositiveInfinity, QuantityValue.One, QuantityValue.NaN); + Add(QuantityValue.NegativeInfinity, QuantityValue.One, QuantityValue.NaN); + Add(QuantityValue.One, QuantityValue.PositiveInfinity, QuantityValue.One); + Add(QuantityValue.One, QuantityValue.NegativeInfinity, QuantityValue.One); + Add(1, 2, 1); + Add(new QuantityValue(1, 2), new QuantityValue(1, 5), new QuantityValue(1, 10)); + Add(new QuantityValue(1, 4), new QuantityValue(1, 2), new QuantityValue(1, 4)); + Add(new QuantityValue(1, 2), new QuantityValue(1, 4), QuantityValue.Zero); + Add(new QuantityValue(1, 4), new QuantityValue(1, 10), new QuantityValue(5, 100)); + } + + private void Add(QuantityValue value1, QuantityValue value2, QuantityValue expectedValue) + { + Add(new ModulusOperationTestCase(value1, value2, expectedValue)); + } + + public sealed record ModulusOperationTestCase : OperatorTestCase + { + public ModulusOperationTestCase() + { + } + + public ModulusOperationTestCase(QuantityValue value1, QuantityValue value2, QuantityValue expectedValue) + : base(value1, value2, expectedValue) + { + } + + public override string ToString() + { + // return $"{Value1} % {Value2} = {ExpectedValue}"; + return $"{Value1.Numerator}/{Value1.Denominator} % {Value2.Numerator}/{Value2.Denominator} = {ExpectedValue.Numerator}/{ExpectedValue.Denominator}"; + } + } + } + } +} \ No newline at end of file diff --git a/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ComparisonOperations.cs b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ComparisonOperations.cs new file mode 100644 index 0000000000..08cc8ddfd2 --- /dev/null +++ b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ComparisonOperations.cs @@ -0,0 +1,482 @@ +using System.Diagnostics.CodeAnalysis; +using Xunit.Abstractions; + +namespace UnitsNet.Tests; + +public partial class QuantityValueTests +{ + public static class ComparisonTests + { + #region Test cases + + /// + /// Represents a pair of instances that are considered equal for comparison purposes. + /// + /// + /// This record is used in unit tests to validate equality and comparison operations between two + /// instances. + /// It implements to support serialization and deserialization of test data. + /// + public sealed record EqualValuesPair : IXunitSerializable + { + public EqualValuesPair(QuantityValue value1, QuantityValue value2) + { + Value1 = value1; + Value2 = value2; + } + + public QuantityValue Value1 { get; private set; } + + public QuantityValue Value2 { get; private set; } + + public void Deconstruct(out QuantityValue value1, out QuantityValue value2) + { + value1 = Value1; + value2 = Value2; + } + + public override string ToString() + { + return $"{Value1.Numerator}/{Value1.Denominator} == {Value2.Numerator}/{Value2.Denominator}"; + } + + #region Implementation of IXunitSerializable + + public EqualValuesPair() + { + } + + public void Serialize(IXunitSerializationInfo info) + { + info.AddValue("v1", (QuantityValueData)Value1); + info.AddValue("v2", (QuantityValueData)Value2); + } + + public void Deserialize(IXunitSerializationInfo info) + { + Value1 = info.GetValue("v1"); + Value2 = info.GetValue("v2"); + } + + #endregion + } + + /// + /// Provides a collection of test cases for verifying the equality of instances. + /// + /// + /// This class is used in unit tests to supply pairs of instances that are expected to be + /// equal. + /// It extends to facilitate parameterized testing with xUnit. + /// + public sealed class EqualTestCases : TheoryData + { + public EqualTestCases() + { + Add(QuantityValue.PositiveInfinity, QuantityValue.PositiveInfinity); + Add(QuantityValue.NegativeInfinity, QuantityValue.NegativeInfinity); + Add(QuantityValue.Zero, QuantityValue.Zero); + Add(QuantityValue.Zero, new QuantityValue(0, 2)); + Add(new QuantityValue(0, 2), QuantityValue.Zero); + Add(QuantityValue.One, new QuantityValue(2, 2)); + Add(QuantityValue.MinusOne, new QuantityValue(-2, 2)); + Add(new QuantityValue(1, 2), new QuantityValue(2, 4)); + Add(new QuantityValue(-1, 2), new QuantityValue(-2, 4)); + Add(42, 42); + Add(-42, -42); + } + + private void Add(QuantityValue value1, QuantityValue value2) + { + Add(new EqualValuesPair(value1, value2)); + } + } + + /// + /// Represents a pair of unequal instances, where one value is smaller than the other. + /// + /// + /// This record is used in unit tests to validate comparison operations between instances. + /// It implements to support serialization and deserialization for test cases. + /// + public sealed record UnequalValuesPair : IXunitSerializable + { + public UnequalValuesPair(QuantityValue smaller, QuantityValue larger) + { + Smaller = smaller; + Larger = larger; + } + + public QuantityValue Smaller { get; private set; } + + public QuantityValue Larger { get; private set; } + + public void Deconstruct(out QuantityValue smaller, out QuantityValue larger) + { + smaller = Smaller; + larger = Larger; + } + + public override string ToString() + { + return $"{Smaller.Numerator}/{Smaller.Denominator} < {Larger.Numerator}/{Larger.Denominator}"; + } + + #region Implementation of IXunitSerializable + + public UnequalValuesPair() + { + } + + public void Serialize(IXunitSerializationInfo info) + { + info.AddValue("v1", (QuantityValueData)Smaller); + info.AddValue("v2", (QuantityValueData)Larger); + } + + public void Deserialize(IXunitSerializationInfo info) + { + Smaller = info.GetValue("v1"); + Larger = info.GetValue("v2"); + } + + #endregion + } + + /// + /// Provides a collection of test cases for validating the behavior of comparison operations + /// between unequal instances. + /// + /// + /// This class is used in unit tests to supply pairs of instances + /// where one value is smaller than the other. It extends to + /// facilitate parameterized tests with . + /// + public sealed class UnequalTestCases : TheoryData + { + public UnequalTestCases() + { + Add(QuantityValue.NegativeInfinity, QuantityValue.PositiveInfinity); + Add(QuantityValue.NegativeInfinity, new QuantityValue(1, 2)); + Add(new QuantityValue(1, 2), QuantityValue.PositiveInfinity); + Add(QuantityValue.Zero, QuantityValue.One); + Add(QuantityValue.MinusOne, QuantityValue.Zero); + Add(QuantityValue.MinusOne, QuantityValue.One); + Add(QuantityValue.Zero, new QuantityValue(1, 2)); + Add(new QuantityValue(-1, 2), QuantityValue.Zero); + Add(new QuantityValue(-1, 2), new QuantityValue(2, 4)); + Add(new QuantityValue(1, 3), new QuantityValue(1, 2)); + Add(new QuantityValue(-1, 2), new QuantityValue(-1, 3)); + Add(new QuantityValue(3, 2), new QuantityValue(2, 1)); + Add(new QuantityValue(-2, 1), new QuantityValue(-3, 2)); + Add(new QuantityValue(3, 5), new QuantityValue(2, 3)); + Add(new QuantityValue(-2, 3), new QuantityValue(-3, 5)); + Add(new QuantityValue(2, 3), new QuantityValue(4, 5)); + Add(new QuantityValue(-4, 5), new QuantityValue(-2, 3)); + Add(new QuantityValue(4, 2), new QuantityValue(9, 4)); + Add(new QuantityValue(-9, 4), new QuantityValue(-4, 2)); + Add(new QuantityValue(8, 5), new QuantityValue(4, 2)); + Add(new QuantityValue(-4, 2), new QuantityValue(-8, 5)); + Add(42, 43); + Add(-43, -42); + } + + private void Add(QuantityValue value1, QuantityValue value2) + { + Add(new UnequalValuesPair(value1, value2)); + } + } + + #endregion + + public class EqualityContractTests + { + [Fact] + [SuppressMessage("ReSharper", "EqualExpressionComparison")] + [SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")] + public void Equals_WithNaN_ReturnsTrue() + { + Assert.True(double.NaN.Equals(double.NaN)); + Assert.True(QuantityValue.NaN.Equals(QuantityValue.NaN)); + } + + [Fact] + public void Equals_WithAnotherType_ReturnsFalse() + { + // ReSharper disable once SuspiciousTypeConversion.Global + Assert.False(QuantityValue.Zero.Equals("text")); + } + + [Fact] + public void Equals_WithNull_ReturnsFalse() + { + Assert.False(QuantityValue.Zero.Equals(null)); + } + + [Theory] + [ClassData(typeof(EqualTestCases))] + public void Equals_WithSameValueAsObject_ReturnsTrue(EqualValuesPair test) + { + Assert.True(test.Value1.Equals((object)test.Value2)); + Assert.True(test.Value2.Equals((object)test.Value1)); + } + + [Theory] + [ClassData(typeof(UnequalTestCases))] + public void Equals_WithAnotherValueAsObject_ReturnsFalse(UnequalValuesPair test) + { + Assert.False(test.Smaller.Equals((object)test.Larger)); + Assert.False(test.Larger.Equals((object)test.Smaller)); + } + + [Theory] + [ClassData(typeof(EqualTestCases))] + public void GetHashCode_WithSameValues_ReturnsTheSameCode(EqualValuesPair test) + { + Assert.Equal(test.Value1.GetHashCode(), test.Value2.GetHashCode()); + } + } + + public class EqualityOperatorTests + { + [Theory] + [ClassData(typeof(EqualTestCases))] + public void EqualityOperator_WithEqualValues_ReturnsTrue(EqualValuesPair testCase) + { + Assert.True(testCase.Value1 == testCase.Value2); + Assert.True(testCase.Value2 == testCase.Value1); + } + + [Theory] + [ClassData(typeof(UnequalTestCases))] + public void EqualityOperator_WithDifferentValues_ReturnsFalse(UnequalValuesPair testCase) + { + Assert.False(testCase.Smaller == testCase.Larger); + Assert.False(testCase.Larger == testCase.Smaller); + } + + [Fact] + [SuppressMessage("ReSharper", "EqualExpressionComparison")] + [SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")] + public void EqualityOperator_WithNaN_ReturnsFalse() + { +#pragma warning disable CS1718 + Assert.False(double.NaN == double.NaN); +#pragma warning restore CS1718 + + Assert.Multiple( + () => Assert.False(QuantityValue.NaN == QuantityValue.NaN), + () => Assert.False(QuantityValue.Zero == QuantityValue.NaN), + () => Assert.False(QuantityValue.NaN == QuantityValue.Zero)); + } + + [Theory] + [ClassData(typeof(EqualTestCases))] + public void InequalityOperator_WithEqualValues_ReturnsFalse(EqualValuesPair testCase) + { + Assert.False(testCase.Value1 != testCase.Value2); + Assert.False(testCase.Value2 != testCase.Value1); + } + + [Theory] + [ClassData(typeof(UnequalTestCases))] + public void InequalityOperator_WithDifferentValues_ReturnsTrue(UnequalValuesPair testCase) + { + Assert.True(testCase.Smaller != testCase.Larger); + Assert.True(testCase.Larger != testCase.Smaller); + } + + [Fact] + [SuppressMessage("ReSharper", "EqualExpressionComparison")] + [SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")] + public void InequalityOperator_WithNaN_ReturnsTrue() + { +#pragma warning disable CS1718 + Assert.True(double.NaN != double.NaN); +#pragma warning restore CS1718 + + Assert.Multiple( + () => Assert.True(QuantityValue.NaN != QuantityValue.NaN), + () => Assert.True(QuantityValue.Zero != QuantityValue.NaN), + () => Assert.True(QuantityValue.NaN != QuantityValue.Zero)); + } + } + + public class ComparableContractTests + { + [Fact] + [SuppressMessage("ReSharper", "EqualExpressionComparison")] + [SuppressMessage("ReSharper", "CompareOfFloatsByEqualityOperator")] + public void CompareTo_WithNaN_ReturnsZero() + { + Assert.Equal(0, double.NaN.CompareTo(double.NaN)); + Assert.Equal(0, QuantityValue.NaN.CompareTo(QuantityValue.NaN)); + } + + [Fact] + public void CompareTo_WithAnotherType_ThrowsArgumentException() + { + Assert.Throws(() => QuantityValue.Zero.CompareTo("text")); + } + + [Fact] + public void CompareTo_WithNull_ReturnsOne() + { + Assert.Equal(1, double.NegativeInfinity.CompareTo(null)); + Assert.Equal(1, QuantityValue.NegativeInfinity.CompareTo(null)); + } + + [Theory] + [ClassData(typeof(EqualTestCases))] + public void CompareTo_WithSameValueAsObject_ReturnsZero(EqualValuesPair test) + { + Assert.Equal(0, test.Value1.CompareTo((object)test.Value2)); + } + + [Theory] + [ClassData(typeof(UnequalTestCases))] + public void CompareTo_WithLargerValueAsObject_ReturnsOne(UnequalValuesPair test) + { + Assert.Equal(1, test.Larger.CompareTo((object)test.Smaller)); + } + + [Theory] + [ClassData(typeof(UnequalTestCases))] + public void CompareTo_WithSmallerValueAsObject_ReturnsMinusOne(UnequalValuesPair test) + { + Assert.Equal(-1, test.Smaller.CompareTo((object)test.Larger)); + } + } + + public class ComparisonOperatorTests + { + [Theory] + [ClassData(typeof(EqualTestCases))] + public void SmallerThanOperator_WithEqualValues_ReturnsFalse(EqualValuesPair testCase) + { + Assert.False(testCase.Value1 < testCase.Value2); + Assert.False(testCase.Value2 < testCase.Value1); + } + + [Theory] + [ClassData(typeof(UnequalTestCases))] + public void SmallerThanOperator_WithDifferentValues_ReturnsTheExpectedResult(UnequalValuesPair testCase) + { + Assert.True(testCase.Smaller < testCase.Larger); + Assert.False(testCase.Larger < testCase.Smaller); + } + + [Fact] + [SuppressMessage("ReSharper", "EqualExpressionComparison")] + public void SmallerThanOperator_WithNaN_ReturnsFalse() + { + Assert.Multiple( + () => Assert.False(QuantityValue.NaN < QuantityValue.NaN), + () => Assert.False(QuantityValue.NegativeInfinity < QuantityValue.NaN), + () => Assert.False(QuantityValue.NaN < QuantityValue.PositiveInfinity), +#pragma warning disable CS1718 + () => Assert.False(double.NaN < double.NaN), +#pragma warning restore CS1718 + () => Assert.False(double.NegativeInfinity < double.NaN), + () => Assert.False(double.NaN < double.PositiveInfinity)); + } + + [Theory] + [ClassData(typeof(EqualTestCases))] + public void SmallerThanOrEqualsOperator_WithEqualValues_ReturnsTrue(EqualValuesPair testCase) + { + Assert.True(testCase.Value1 <= testCase.Value2); + Assert.True(testCase.Value2 <= testCase.Value1); + } + + [Theory] + [ClassData(typeof(UnequalTestCases))] + public void SmallerThanOrEqualsOperator_WithDifferentValues_ReturnsTheExpectedResult(UnequalValuesPair testCase) + { + Assert.True(testCase.Smaller <= testCase.Larger); + Assert.False(testCase.Larger <= testCase.Smaller); + } + + [Fact] + [SuppressMessage("ReSharper", "EqualExpressionComparison")] + public void SmallerThanOrEqualsOperator_WithNaN_ReturnsFalse() + { +#pragma warning disable CS1718 + Assert.False(double.NaN <= double.NaN); +#pragma warning disable CS1718 + Assert.False(double.NegativeInfinity <= double.NaN); + Assert.False(double.NaN <= double.PositiveInfinity); + + Assert.Multiple( + () => Assert.False(QuantityValue.NaN <= QuantityValue.NaN), + () => Assert.False(QuantityValue.NegativeInfinity <= QuantityValue.NaN), + () => Assert.False(QuantityValue.NaN <= QuantityValue.PositiveInfinity)); + } + + + [Theory] + [ClassData(typeof(EqualTestCases))] + public void LargerThanOperator_WithEqualValues_ReturnsFalse(EqualValuesPair testCase) + { + Assert.False(testCase.Value1 > testCase.Value2); + Assert.False(testCase.Value2 > testCase.Value1); + } + + [Theory] + [ClassData(typeof(UnequalTestCases))] + public void LargerThanOperator_WithDifferentValues_ReturnsTheExpectedResult(UnequalValuesPair testCase) + { + Assert.True(testCase.Larger > testCase.Smaller); + Assert.False(testCase.Smaller > testCase.Larger); + } + + [Fact] + [SuppressMessage("ReSharper", "EqualExpressionComparison")] + public void LargerThanOperator_WithNaN_ReturnsFalse() + { +#pragma warning disable CS1718 + Assert.False(double.NaN > double.NaN); +#pragma warning disable CS1718 + Assert.False(double.PositiveInfinity > double.NaN); + Assert.False(double.NaN > double.NegativeInfinity); + + Assert.Multiple( + () => Assert.False(QuantityValue.NaN > QuantityValue.NaN), + () => Assert.False(QuantityValue.PositiveInfinity > QuantityValue.NaN), + () => Assert.False(QuantityValue.NaN > QuantityValue.NegativeInfinity)); + } + + [Theory] + [ClassData(typeof(EqualTestCases))] + public void LargerThanOrEqualsOperator_WithEqualValues_ReturnsTrue(EqualValuesPair testCase) + { + Assert.True(testCase.Value1 >= testCase.Value2); + Assert.True(testCase.Value2 >= testCase.Value1); + } + + [Theory] + [ClassData(typeof(UnequalTestCases))] + public void LargerThanOrEqualsOperator_WithDifferentValues_ReturnsTheExpectedResult(UnequalValuesPair testCase) + { + Assert.True(testCase.Larger >= testCase.Smaller); + Assert.False(testCase.Smaller >= testCase.Larger); + } + + [Fact] + [SuppressMessage("ReSharper", "EqualExpressionComparison")] + public void LargerThanOrEqualsOperator_WithNaN_ReturnsFalse() + { +#pragma warning disable CS1718 + Assert.False(double.NaN >= double.NaN); +#pragma warning disable CS1718 + Assert.False(double.PositiveInfinity >= double.NaN); + Assert.False(double.NaN >= double.NegativeInfinity); + + Assert.Multiple( + () => Assert.False(QuantityValue.NaN >= QuantityValue.NaN), + () => Assert.False(QuantityValue.PositiveInfinity >= QuantityValue.NaN), + () => Assert.False(QuantityValue.NaN >= QuantityValue.NegativeInfinity)); + } + } + } +} \ No newline at end of file diff --git a/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ConvertFromNumber.cs b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ConvertFromNumber.cs new file mode 100644 index 0000000000..249d6ea8d8 --- /dev/null +++ b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ConvertFromNumber.cs @@ -0,0 +1,430 @@ +using System.Numerics; + +namespace UnitsNet.Tests; + +public partial class QuantityValueTests +{ + public class ConvertFromNumberTests + { + [Theory] + [InlineData(2.5123, 1, 3, 1)] + [InlineData(2.5123, 2, 25, 10)] + [InlineData(2.5123, 3, 251, 100)] + [InlineData(25.123, 1, 25, 1)] + [InlineData(251.23, 1, 250, 1)] + [InlineData(double.PositiveInfinity, 1, 1, 0)] + [InlineData(double.NegativeInfinity, 1, -1, 0)] + [InlineData(double.NaN, 1, 0, 0)] + public void FromDoubleRounded(double value, byte digits, BigInteger numerator, BigInteger denominator) + { + var convertedValue = QuantityValue.FromDoubleRounded(value, digits); + Assert.Equal(numerator, convertedValue.Numerator); + Assert.Equal(denominator, convertedValue.Denominator); + } + + [Fact] + public void FromDoubleRounded_WithZeroSignificantDigits_ThrowsArgumentOutOfRangeException() + { + Assert.Throws(() => QuantityValue.FromDoubleRounded(2.5123, 0)); + } + + [Fact] + public void FromDoubleRounded_WithMoreThan17SignificantDigits_ThrowsArgumentOutOfRangeException() + { + Assert.Throws(() => QuantityValue.FromDoubleRounded(2.5123, 18)); + } + + [Theory] + [InlineData(2, 3, 2, 3)] + [InlineData(-2, -3, 2, 3)] + [InlineData(-2, 3, -2, 3)] + [InlineData(2, -3, -2, 3)] + public void FromTerms_ReturnsTheExpectedResult(BigInteger numerator, BigInteger denominator, BigInteger expectedNumerator, BigInteger expectedDenominator) + { + Assert.Equal(new QuantityValue(expectedNumerator, expectedDenominator), QuantityValue.FromTerms(numerator, denominator)); + } + + [Theory] + [InlineData(2, 3, 3, 2e3, 3)] + [InlineData(-2, -3, 3, 2e3, 3)] + [InlineData(-2, 3, 3, -2e3, 3)] + [InlineData(2, -3, 3, -2e3, 3)] + [InlineData(2, 3, -3, 2, 3e3)] + [InlineData(-2, -3, -3, 2, 3e3)] + [InlineData(-2, 3, -3, -2, 3e3)] + [InlineData(2, -3, -3, -2, 3e3)] + public void FromPowerOfTen_ReturnsTheExpectedResult(BigInteger numerator, BigInteger denominator, int powerOfTen, BigInteger expectedNumerator, BigInteger expectedDenominator) + { + Assert.Equal(new QuantityValue(expectedNumerator, expectedDenominator), QuantityValue.FromPowerOfTen(numerator, denominator, powerOfTen)); + } + + [Fact] + public void FromPowerOfTen_WithWholeNumber_ReturnsTheExpectedResult() + { + Assert.Equal(0.05m, QuantityValue.FromPowerOfTen(5, -2)); + } + + public class ImplicitConversionTests + { + [Fact] + public void ImplicitConversionFromByte() + { + const byte valueToConvert = 10; + QuantityValue convertedValue = valueToConvert; + Assert.Equal(convertedValue.Numerator, valueToConvert); + Assert.Equal(convertedValue.Denominator, BigInteger.One); + } + + [Fact] + public void ImplicitConversionFromSByte() + { + const sbyte valueToConvert = -10; + QuantityValue convertedValue = valueToConvert; + Assert.Equal(convertedValue.Numerator, valueToConvert); + Assert.Equal(convertedValue.Denominator, BigInteger.One); + } + + [Fact] + public void ImplicitConversionFromShort() + { + const short valueToConvert = 10; + QuantityValue convertedValue = valueToConvert; + Assert.Equal(convertedValue.Numerator, valueToConvert); + Assert.Equal(convertedValue.Denominator, BigInteger.One); + } + + [Fact] + public void ImplicitConversionFromUShort() + { + const ushort valueToConvert = 10; + QuantityValue convertedValue = valueToConvert; + Assert.Equal(convertedValue.Numerator, valueToConvert); + Assert.Equal(convertedValue.Denominator, BigInteger.One); + } + + [Fact] + public void ImplicitConversionFromInt() + { + const int valueToConvert = 10; + QuantityValue convertedValue = valueToConvert; + Assert.Equal(convertedValue.Numerator, valueToConvert); + Assert.Equal(convertedValue.Denominator, BigInteger.One); + } + + [Fact] + public void ImplicitConversionFromUInt() + { + const uint valueToConvert = 10; + QuantityValue convertedValue = valueToConvert; + Assert.Equal(convertedValue.Numerator, valueToConvert); + Assert.Equal(convertedValue.Denominator, BigInteger.One); + } + + [Fact] + public void ImplicitConversionFromLong() + { + const long valueToConvert = 10; + QuantityValue convertedValue = valueToConvert; + Assert.Equal(convertedValue.Numerator, valueToConvert); + Assert.Equal(convertedValue.Denominator, BigInteger.One); + } + + [Fact] + public void ImplicitConversionFromULong() + { + const ulong valueToConvert = 10; + QuantityValue convertedValue = valueToConvert; + Assert.Equal(convertedValue.Numerator, valueToConvert); + Assert.Equal(convertedValue.Denominator, BigInteger.One); + } + + [Theory] + [InlineData(2.5, 25, 10)] + [InlineData(-2.5, -25, 10)] + public void ImplicitConversionFromDecimal(decimal value, BigInteger numerator, BigInteger denominator) + { + QuantityValue convertedValue = value; + Assert.Equal(numerator, convertedValue.Numerator); + Assert.Equal(denominator, convertedValue.Denominator); + } + + [Fact] + public void ImplicitConversionFromFloat() + { + const float valueToConvert = 10.5f; + QuantityValue convertedValue = valueToConvert; + Assert.Equal(convertedValue.Numerator, 105); + Assert.Equal(convertedValue.Denominator, 10); + } + + [Theory] + [InlineData(0, 0, 1)] + [InlineData(double.NaN, 0, 0)] + [InlineData(double.PositiveInfinity, 1, 0)] + [InlineData(double.NegativeInfinity, -1, 0)] + [InlineData(2, 2, 1)] + [InlineData(2.5, 25, 10)] + [InlineData(-2.5, -25, 10)] + [InlineData(0.123, 123, 1000)] + public void ImplicitConversionFromDouble(double value, BigInteger numerator, BigInteger denominator) + { + QuantityValue convertedValue = value; + Assert.Equal(numerator, convertedValue.Numerator); + Assert.Equal(denominator, convertedValue.Denominator); + } + } + +#if NET + public class ConvertFromCheckedTests + { + private static TNumber CreateChecked(TOther value) + where TNumber : INumberBase + where TOther : INumberBase + { + return TNumber.CreateChecked(value); + } + + private static QuantityValue CreateChecked(TOther number) where TOther : INumberBase + { + return CreateChecked(number); + } + + [Fact] + public void CreateChecked_WithARealFiniteNumber_ShouldReturnTheConvertedValue() + { + Assert.Equal(new QuantityValue(1, 3), CreateChecked(new QuantityValue(1, 3))); + Assert.Equal(new QuantityValue(3, 2), CreateChecked(1.5)); + Assert.Equal(new QuantityValue(3, 2), CreateChecked(new Complex(1.5, 0))); + Assert.Equal(new QuantityValue(3, 2), CreateChecked(1.5m)); + Assert.Equal(new QuantityValue(3, 2), CreateChecked((Half)1.5)); + Assert.Equal(QuantityValue.One, CreateChecked(BigInteger.One)); + Assert.Equal(QuantityValue.One, CreateChecked(Int128.One)); + Assert.Equal(QuantityValue.One, CreateChecked(UInt128.One)); + Assert.Equal(QuantityValue.One, CreateChecked(1L)); + Assert.Equal(QuantityValue.One, CreateChecked(1UL)); + Assert.Equal(QuantityValue.One, CreateChecked(1)); + Assert.Equal(QuantityValue.One, CreateChecked(1U)); + Assert.Equal(QuantityValue.One, CreateChecked((nint)1)); + Assert.Equal(QuantityValue.One, CreateChecked((UIntPtr)1)); + Assert.Equal(QuantityValue.One, CreateChecked((short)1)); + Assert.Equal(QuantityValue.One, CreateChecked((ushort)1)); + Assert.Equal(QuantityValue.One, CreateChecked((byte)1)); + Assert.Equal(QuantityValue.One, CreateChecked((sbyte)1)); + Assert.Equal(new QuantityValue(97), CreateChecked('a')); + } + + [Fact] + public void CreateChecked_WithANaN_ShouldReturnNaN() + { + Assert.Equal(QuantityValue.NaN, CreateChecked(QuantityValue.NaN)); + Assert.Equal(QuantityValue.NaN, CreateChecked(double.NaN)); + Assert.Equal(QuantityValue.NaN, CreateChecked(float.NaN)); + Assert.Equal(QuantityValue.NaN, CreateChecked(Half.NaN)); + Assert.Equal(QuantityValue.NaN, CreateChecked(Complex.NaN)); + } + + [Fact] + public void CreateChecked_WithARealPositiveInfinity_ShouldReturnPositiveInfinity() + { + Assert.Equal(QuantityValue.PositiveInfinity, CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Equal(QuantityValue.PositiveInfinity, CreateChecked(double.PositiveInfinity)); + Assert.Equal(QuantityValue.PositiveInfinity, CreateChecked(float.PositiveInfinity)); + Assert.Equal(QuantityValue.PositiveInfinity, CreateChecked(Half.PositiveInfinity)); + Assert.Equal(QuantityValue.PositiveInfinity, CreateChecked(new Complex(double.PositiveInfinity, 0))); + } + + [Fact] + public void CreateChecked_WithARealNegativeInfinity_ShouldReturnNegativeInfinity() + { + Assert.Equal(QuantityValue.NegativeInfinity, CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Equal(QuantityValue.NegativeInfinity, CreateChecked(double.NegativeInfinity)); + Assert.Equal(QuantityValue.NegativeInfinity, CreateChecked(float.NegativeInfinity)); + Assert.Equal(QuantityValue.NegativeInfinity, CreateChecked(Half.NegativeInfinity)); + Assert.Equal(QuantityValue.NegativeInfinity, CreateChecked(new Complex(double.NegativeInfinity, 0))); + } + + [Fact] + public void CreateChecked_WithAComplexNumberHavingAnImaginaryPart_ShouldReturnNaN() + { + Assert.Equal(QuantityValue.NaN, CreateChecked(Complex.ImaginaryOne)); + Assert.Equal(QuantityValue.NaN, CreateChecked(Complex.Infinity)); + } + + [Fact] + public void CreateChecked_WithAnUnsupportedType_ThrowsNotSupportedException() + { + Assert.Throws(() => CreateChecked(FakeNumber.Zero)); + } + } + + public class ConvertFromSaturatingTests + { + private static TNumber CreateSaturating(TOther value) + where TNumber : INumberBase + where TOther : INumberBase + { + return TNumber.CreateSaturating(value); + } + + private static QuantityValue CreateSaturating(TOther number) where TOther : INumberBase + { + return CreateSaturating(number); + } + + [Fact] + public void CreateSaturating_WithARealFiniteNumber_ShouldReturnTheConvertedQuantityValue() + { + Assert.Equal(new QuantityValue(1, 3), CreateSaturating(new QuantityValue(1, 3))); + Assert.Equal(new QuantityValue(3, 2), CreateSaturating(1.5)); + Assert.Equal(new QuantityValue(3, 2), CreateSaturating(new Complex(1.5, 0))); + Assert.Equal(new QuantityValue(3, 2), CreateSaturating(1.5m)); + Assert.Equal(new QuantityValue(3, 2), CreateSaturating((Half)1.5)); + Assert.Equal(QuantityValue.One, CreateSaturating(BigInteger.One)); + Assert.Equal(QuantityValue.One, CreateSaturating(Int128.One)); + Assert.Equal(QuantityValue.One, CreateSaturating(UInt128.One)); + Assert.Equal(QuantityValue.One, CreateSaturating(1L)); + Assert.Equal(QuantityValue.One, CreateSaturating(1UL)); + Assert.Equal(QuantityValue.One, CreateSaturating(1)); + Assert.Equal(QuantityValue.One, CreateSaturating(1U)); + Assert.Equal(QuantityValue.One, CreateSaturating((nint)1)); + Assert.Equal(QuantityValue.One, CreateSaturating((UIntPtr)1)); + Assert.Equal(QuantityValue.One, CreateSaturating((short)1)); + Assert.Equal(QuantityValue.One, CreateSaturating((ushort)1)); + Assert.Equal(QuantityValue.One, CreateSaturating((byte)1)); + Assert.Equal(QuantityValue.One, CreateSaturating((sbyte)1)); + Assert.Equal(new QuantityValue(97), CreateSaturating('a')); + } + + [Fact] + public void CreateSaturating_WithANaN_ShouldReturnNaN() + { + Assert.Equal(QuantityValue.NaN, CreateSaturating(QuantityValue.NaN)); + Assert.Equal(QuantityValue.NaN, CreateSaturating(double.NaN)); + Assert.Equal(QuantityValue.NaN, CreateSaturating(float.NaN)); + Assert.Equal(QuantityValue.NaN, CreateSaturating(Half.NaN)); + Assert.Equal(QuantityValue.NaN, CreateSaturating(Complex.NaN)); + } + + [Fact] + public void CreateSaturating_WithARealPositiveInfinity_ShouldReturnPositiveInfinity() + { + Assert.Equal(QuantityValue.PositiveInfinity, CreateSaturating(QuantityValue.PositiveInfinity)); + Assert.Equal(QuantityValue.PositiveInfinity, CreateSaturating(double.PositiveInfinity)); + Assert.Equal(QuantityValue.PositiveInfinity, CreateSaturating(float.PositiveInfinity)); + Assert.Equal(QuantityValue.PositiveInfinity, CreateSaturating(Half.PositiveInfinity)); + Assert.Equal(QuantityValue.PositiveInfinity, CreateSaturating(new Complex(double.PositiveInfinity, 0))); + } + + [Fact] + public void CreateSaturating_WithARealNegativeInfinity_ShouldReturnNegativeInfinity() + { + Assert.Equal(QuantityValue.NegativeInfinity, CreateSaturating(QuantityValue.NegativeInfinity)); + Assert.Equal(QuantityValue.NegativeInfinity, CreateSaturating(double.NegativeInfinity)); + Assert.Equal(QuantityValue.NegativeInfinity, CreateSaturating(float.NegativeInfinity)); + Assert.Equal(QuantityValue.NegativeInfinity, CreateSaturating(Half.NegativeInfinity)); + Assert.Equal(QuantityValue.NegativeInfinity, CreateSaturating(new Complex(double.NegativeInfinity, 0))); + } + + [Fact] + public void CreateSaturating_WithAComplexNumberHavingAnImaginaryPart_ShouldReturnNaN() + { + Assert.Equal(0, CreateSaturating(Complex.ImaginaryOne)); + Assert.Equal(QuantityValue.Zero, CreateSaturating(Complex.ImaginaryOne)); + Assert.Equal(double.PositiveInfinity, CreateSaturating(Complex.Infinity)); + Assert.Equal(QuantityValue.PositiveInfinity, CreateSaturating(Complex.Infinity)); + } + + [Fact] + public void CreateSaturating_WithAnUnsupportedType_ThrowsNotSupportedException() + { + Assert.Throws(() => CreateSaturating(FakeNumber.Zero)); + } + } + + public class ConvertFromTruncatingTests + { + private static TNumber CreateTruncating(TOther value) + where TNumber : INumberBase + where TOther : INumberBase + { + return TNumber.CreateTruncating(value); + } + + private static QuantityValue CreateTruncating(TOther number) where TOther : INumberBase + { + return CreateTruncating(number); + } + + [Fact] + public void CreateTruncating_WithARealFiniteNumber_ShouldReturnTheConvertedQuantityValue() + { + Assert.Equal(new QuantityValue(1, 3), CreateTruncating(new QuantityValue(1, 3))); + Assert.Equal(new QuantityValue(3, 2), CreateTruncating(1.5)); + Assert.Equal(new QuantityValue(3, 2), CreateTruncating(new Complex(1.5, 0))); + Assert.Equal(new QuantityValue(3, 2), CreateTruncating(1.5m)); + Assert.Equal(new QuantityValue(3, 2), CreateTruncating((Half)1.5)); + Assert.Equal(QuantityValue.One, CreateTruncating(BigInteger.One)); + Assert.Equal(QuantityValue.One, CreateTruncating(Int128.One)); + Assert.Equal(QuantityValue.One, CreateTruncating(UInt128.One)); + Assert.Equal(QuantityValue.One, CreateTruncating(1L)); + Assert.Equal(QuantityValue.One, CreateTruncating(1UL)); + Assert.Equal(QuantityValue.One, CreateTruncating(1)); + Assert.Equal(QuantityValue.One, CreateTruncating(1U)); + Assert.Equal(QuantityValue.One, CreateTruncating((nint)1)); + Assert.Equal(QuantityValue.One, CreateTruncating((UIntPtr)1)); + Assert.Equal(QuantityValue.One, CreateTruncating((short)1)); + Assert.Equal(QuantityValue.One, CreateTruncating((ushort)1)); + Assert.Equal(QuantityValue.One, CreateTruncating((byte)1)); + Assert.Equal(QuantityValue.One, CreateTruncating((sbyte)1)); + Assert.Equal(new QuantityValue(97), CreateTruncating('a')); + } + + [Fact] + public void CreateTruncating_WithANaN_ShouldReturnNaN() + { + Assert.Equal(QuantityValue.NaN, CreateTruncating(QuantityValue.NaN)); + Assert.Equal(QuantityValue.NaN, CreateTruncating(double.NaN)); + Assert.Equal(QuantityValue.NaN, CreateTruncating(float.NaN)); + Assert.Equal(QuantityValue.NaN, CreateTruncating(Half.NaN)); + Assert.Equal(QuantityValue.NaN, CreateTruncating(Complex.NaN)); + } + + [Fact] + public void CreateTruncating_WithARealPositiveInfinity_ShouldReturnPositiveInfinity() + { + Assert.Equal(QuantityValue.PositiveInfinity, CreateTruncating(QuantityValue.PositiveInfinity)); + Assert.Equal(QuantityValue.PositiveInfinity, CreateTruncating(double.PositiveInfinity)); + Assert.Equal(QuantityValue.PositiveInfinity, CreateTruncating(float.PositiveInfinity)); + Assert.Equal(QuantityValue.PositiveInfinity, CreateTruncating(Half.PositiveInfinity)); + Assert.Equal(QuantityValue.PositiveInfinity, CreateTruncating(new Complex(double.PositiveInfinity, 0))); + } + + [Fact] + public void CreateTruncating_WithARealNegativeInfinity_ShouldReturnNegativeInfinity() + { + Assert.Equal(QuantityValue.NegativeInfinity, CreateTruncating(QuantityValue.NegativeInfinity)); + Assert.Equal(QuantityValue.NegativeInfinity, CreateTruncating(double.NegativeInfinity)); + Assert.Equal(QuantityValue.NegativeInfinity, CreateTruncating(float.NegativeInfinity)); + Assert.Equal(QuantityValue.NegativeInfinity, CreateTruncating(Half.NegativeInfinity)); + Assert.Equal(QuantityValue.NegativeInfinity, CreateTruncating(new Complex(double.NegativeInfinity, 0))); + } + + [Fact] + public void CreateTruncating_WithAComplexNumberHavingAnImaginaryPart_ShouldReturnNaN() + { + Assert.Equal(0, CreateTruncating(Complex.ImaginaryOne)); + Assert.Equal(QuantityValue.Zero, CreateTruncating(Complex.ImaginaryOne)); + Assert.Equal(double.PositiveInfinity, CreateTruncating(Complex.Infinity)); + Assert.Equal(QuantityValue.PositiveInfinity, CreateTruncating(Complex.Infinity)); + } + + [Fact] + public void CreateTruncating_WithAnUnsupportedType_ThrowsNotSupportedException() + { + Assert.Throws(() => CreateTruncating(FakeNumber.Zero)); + } + } + +#endif + } +} diff --git a/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ConvertFromString.cs b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ConvertFromString.cs new file mode 100644 index 0000000000..e819228a59 --- /dev/null +++ b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ConvertFromString.cs @@ -0,0 +1,750 @@ +using System.Globalization; +using System.Numerics; +using UnitsNet.Tests.Helpers; + +namespace UnitsNet.Tests; + +public partial class QuantityValueTests +{ + public static class ConversionFromStringTests + { + public class ParsingWithInvariantCulture + { + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData(" ")] + [InlineData(null)] + public void ShouldNotWorkWithNullOrEmptyString(string? valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse!, NumberStyles.Any, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData(" 1")] + [InlineData(" +1")] + [InlineData(" -1")] + [InlineData(" 1-")] + [InlineData(" (1)")] + public void ShouldNotWorkWithLeadingWhitespaceWhenItIsNotAllowed(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any & ~NumberStyles.AllowLeadingWhite, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData("1 ")] + [InlineData("+1 ")] + [InlineData("-1 ")] + [InlineData("1- ")] + [InlineData("(1) ")] + public void ShouldNotWorkWithTrailingWhitespaceWhenItIsNotAllowed(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any & ~NumberStyles.AllowTrailingWhite, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData("-123456789987654321.123456789987654321")] + [InlineData("+123456789987654321.123456789987654321")] + public void ShouldNotWorkWithLeadingSignWhenItIsNotAllowed(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any & ~NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData("123456789987654321.123456789987654321-")] + [InlineData("123456789987654321.123456789987654321+")] + public void ShouldNotWorkWithTrailingSignWhenItIsNotAllowed(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any & ~NumberStyles.AllowTrailingSign, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData("-123456789987654321.123456789987654321-")] + [InlineData("+123456789987654321.123456789987654321+")] + [InlineData("+123456789987654321.123456789987654321-")] + [InlineData("-123456789987654321.123456789987654321+")] + [InlineData("-3.5+")] + [InlineData("-(3.5)")] + [InlineData("(3.5)-")] + public void ShouldNotWorkWithSignsOnBothSides(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData("1.53")] + [InlineData("-1.53")] + public void ShouldNotWorkWithDecimalSymbolWhenItIsNotAllowed(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any & ~NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData("1 234")] + [InlineData("-1 234")] + [InlineData("1 234.5")] + [InlineData("-1 234.5")] + public void ShouldNotWorkWithGroupSeparatorWhenItIsNotAllowed(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any & ~NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData("123456789987654321.123456789,987654321")] + [InlineData("123456789987654321.,123456789987654321")] + public void ShouldNotWorkWithGroupsInTheMiddle(string valueToParse) + { + Assert.False(double.TryParse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out _), "The format isn't supposed to be recognized by double.TryParse"); + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData("123456789987654321.-123456789987654321")] + [InlineData("123456789987654321-.123456789987654321")] + [InlineData("123456789987654321.+123456789987654321")] + [InlineData("123456789987654321+.123456789987654321")] + public void ShouldNotWorkWithSignsInTheMiddle(string valueToParse) + { + Assert.False(double.TryParse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out _), "The format isn't supposed to be recognized by double.TryParse"); + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData("(1)")] + [InlineData(" (1) ")] + [InlineData("-(1)")] + [InlineData("(-1)")] + [InlineData("+(1)")] + [InlineData("(1)+")] + [InlineData("(1 234)")] + [InlineData("(1234.5)")] + public void ShouldNotWorkWithParenthesesWhenItIsNotAllowed(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any & ~NumberStyles.AllowParentheses, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData("(")] + [InlineData("1(")] + [InlineData("1)")] + [InlineData(")1")] + [InlineData("¤(")] + [InlineData("¤(.")] + [InlineData(")")] + [InlineData("(1")] + [InlineData(" 1) ")] + [InlineData("-1)")] + [InlineData("- 1)")] + [InlineData("+1)")] + [InlineData("-(1")] + [InlineData("(1-")] + [InlineData("+(1-")] + [InlineData("(1 234")] + [InlineData("(1234.5")] + public void ShouldNotWorkWithParenthesesOnOneSide(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData("(1(")] + [InlineData("((1")] + [InlineData(")1)")] + [InlineData("1))")] + [InlineData("((1))")] + [InlineData("(())")] + public void ShouldNotWorkWithMultipleParenthesesOnEitherSide(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData(" ")] + [InlineData(".")] + [InlineData(" .")] + [InlineData(". ")] + [InlineData("-")] + [InlineData("+")] + [InlineData(" .-")] + [InlineData("+.")] + [InlineData("+. ")] + [InlineData("()")] + [InlineData("(.)")] + [InlineData("-(.) ")] + [InlineData("+(.)")] + [InlineData("(.)-")] + [InlineData("¤()")] + public void ShouldNotWorkWithoutDigits(string valueToParse) + { + Assert.False(double.TryParse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out _), "The format isn't supposed to be recognized by double.TryParse"); + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData("1x2")] + [InlineData("1.x2")] + [InlineData("x1.2")] + [InlineData("1.2x")] + [InlineData("1.2x-")] + [InlineData("-1.2x")] + public void ShouldNotWorkWithInvalidCharactersInTheString(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out _)); + } + + [Fact] + public void Parsing_NaN_or_Infinity_ShouldReturnTheExpectedResult() + { + Assert.Equal(QuantityValue.NaN, QuantityValue.Parse("NaN", CultureInfo.InvariantCulture)); + Assert.Equal(QuantityValue.PositiveInfinity, QuantityValue.Parse("Infinity", CultureInfo.InvariantCulture)); + Assert.Equal(QuantityValue.NegativeInfinity, QuantityValue.Parse("-Infinity", CultureInfo.InvariantCulture)); + } + + [Theory] + [ClassData(typeof(ValidDecimalStringCases))] + public void ShouldReturnTheExpectedValueWhenTheStringIsValid(string valueToParse, QuantityValueData expectedResult) + { + Assert.True(double.TryParse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out _), "The format is also recognized by double.TryParse"); + var result = QuantityValue.Parse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture); + Assert.Equal(expectedResult.Value, result); + } + + public class ValidDecimalStringCases : TheoryData + { + public ValidDecimalStringCases() + { + // Zero + AddZeroCases(); + // +42 without a decimal separator + AddPositiveIntegerCases(); + // -5 without a decimal separator + AddNegativeIntegerCases(); + // Negative decimals + AddNegativeDecimalCases(); + // Negative integers that also contain a decimal point + AddNegativeIntegerWithDecimalSeparatorCases(); + // 0.1 written as "-.1" (and other sign variants) + AddPositiveDecimalWithoutLeadingZeroCases(); + // -0.1 written as "-.1" (and other sign variants) + AddNegativeDecimalWithoutLeadingZeroCases(); + } + + private void AddZeroCases() + { + QuantityValueData zero = QuantityValue.Zero; + Add("0", zero); + Add("0.", zero); + Add(".0", zero); + Add("000000000000000000.0000000000000000000", zero); + Add("-000000000000000000.0000000000000000000", zero); + } + + private void AddPositiveIntegerCases() + { + QuantityValueData quantityValueData = 42; + Add("42", quantityValueData); + Add(" 42 ", quantityValueData); + Add("+42", quantityValueData); + Add(" +42", quantityValueData); + Add("42+", quantityValueData); + Add("42+ ", quantityValueData); + Add(" 42+ ", quantityValueData); + Add(" 42 + ", quantityValueData); // any spaces before or after the trailing sign are ok + } + + private void AddNegativeIntegerCases() + { + QuantityValueData expectedValue = -5; + Add("-5", expectedValue); + Add("5-", expectedValue); + Add(" -5", expectedValue); + Add("5- ", expectedValue); + Add("5 - ", expectedValue); // any spaces before or after the trailing sign are ok + Add("(5)", expectedValue); + Add(" (5)", expectedValue); + Add(" (5) ", expectedValue); + } + + private void AddNegativeDecimalCases() + { + QuantityValueData expectedValue = new QuantityValue(BigInteger.Parse("-123456789987654321123456789987654321"), BigInteger.Pow(10, 18)); + Add("-123456789987654321.1234567899876543210", expectedValue); + Add("123456789987654321.1234567899876543210-", expectedValue); + Add("1234,56789987654321.1234567899876543210-", expectedValue); + Add("(1234,56789987654321.1234567899876543210)", expectedValue); + Add(" (1234,56789987654321.1234567899876543210)", expectedValue); + Add(" (1234,56789987654321.1234567899876543210) ", expectedValue); + Add(" (1234,56789987654321.1234567899876543210 ) ", expectedValue); + } + + private void AddNegativeIntegerWithDecimalSeparatorCases() + { + QuantityValueData expectedValue = new QuantityValue(BigInteger.Parse("-123456789987654321")); + Add("-123456789987654321.0", expectedValue); + Add("123456789987654321.0-", expectedValue); + Add("1234,56789987654321.0-", expectedValue); + Add("-123456789987654321.", expectedValue); + Add("123456789987654321.-", expectedValue); + Add("1234,56789987654321.-", expectedValue); + Add("(1234,56789987654321.)", expectedValue); + Add(" (1234,56789987654321.)", expectedValue); + Add(" (1234,56789987654321.) ", expectedValue); + Add(" (1234,56789987654321. ) ", expectedValue); + } + + private void AddPositiveDecimalWithoutLeadingZeroCases() + { + var expectedValue = new QuantityValue(1, 10); + Add(".10", expectedValue); + Add(" .10", expectedValue); + Add(".10 ", expectedValue); + Add("+.10", expectedValue); + Add(".10+", expectedValue); + Add(" +.10", expectedValue); + Add(".10+ ", expectedValue); + } + + private void AddNegativeDecimalWithoutLeadingZeroCases() + { + var expectedValue = new QuantityValue(-1, 10); + Add("-.10", expectedValue); + Add(".10-", expectedValue); + Add(" -.10", expectedValue); + Add(".10- ", expectedValue); + Add("(.10)", expectedValue); + Add(" (.10)", expectedValue); + Add(" (.10) ", expectedValue); + } + } + } + + public class ParsingWithScientificNotation + { + [Theory] + [InlineData("1.23456789987654321E+41.5")] + [InlineData("1.23456789987654321e+41.5")] + [InlineData("-1.23456789987654321E+41.5")] + [InlineData("-1.23456789987654321e+41.5")] + public void Parsing_StringWithDecimalExponent_ShouldThrow_FormatException(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData("1.2345+9876+E5")] + [InlineData("1.2345-9876+E5")] + [InlineData("1.2345+9876-E5")] + [InlineData("1.2345-9876-E5")] + public void Parsing_StringWithSignInTheMiddle_ShouldThrow_FormatException(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData("1.23456789,987654321E-24")] + [InlineData("1.23456789,987654321e-24")] + [InlineData("-1.23456789,987654321E-24")] + [InlineData("-1.23456789,987654321e-24")] + public void Parsing_StringWithGroupInTheMiddle_ShouldThrow_FormatException(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData("1.2345E")] + [InlineData("1.2345e")] + public void Parsing_StringWithNothingAfterTheExponent_ShouldThrow_FormatException(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData(".E1")] + [InlineData(".e1")] + public void Parsing_StringWithNothingBeforeTheExponent_ShouldThrow_FormatException(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData("1.5E3")] + [InlineData("1.5e3")] + public void Parsing_ExponentStringWithDecimalSeparator_With_NumberStyle_ExcludingDecimals_ShouldThrow_FormatException(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Any & ~NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out _)); + } + + [Fact] + public void Parsing_ExponentStringWithoutDecimalSeparator_With_NumberStyle_ExcludingDecimals_ShouldReturnTheExpectedResult() + { + var result = QuantityValue.Parse("1e3", NumberStyles.Any & ~ NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture); + Assert.Equal(1e3, result); + } + + [Theory] + [ClassData(typeof(ValidExponentialStringCases))] + public void Parsing_ExponentString_With_NumberStyle_Number_ShouldThrow_FormatException(string valueToParse, QuantityValueData _) + { + Assert.Throws(() => QuantityValue.Parse(valueToParse, NumberStyles.Number, CultureInfo.InvariantCulture)); + } + + [Theory] + [ClassData(typeof(ValidExponentialStringCases))] + public void Parsing_ValidExponentString_ShouldReturnTheExpectedResult(string valueToParse, QuantityValueData expectedResult) + { + Assert.True(double.TryParse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture, out _), "The format is also recognized by double.TryParse"); + var result = QuantityValue.Parse(valueToParse, NumberStyles.Any, CultureInfo.InvariantCulture); + Assert.Equal(expectedResult.Value, result); + } + + public class ValidExponentialStringCases : TheoryData + { + public ValidExponentialStringCases() + { + AddPositiveIntegerCases(); + AddNegativeIntegerCases(); + AddLargePositiveCases(); + AddLargeNegativeCases(); + AddSmallPositiveCases(); + AddSmallNegativeCases(); + } + + private void AddPositiveIntegerCases() + { + QuantityValueData expectedValue = new QuantityValue(new BigInteger(123456789987654321) * BigInteger.Pow(10, 5)); + Add("123456789987654321E+5", expectedValue); + Add("123456789987654321e+5", expectedValue); + } + + private void AddNegativeIntegerCases() + { + QuantityValueData expectedValue = new QuantityValue(new BigInteger(-123456789987654321) * BigInteger.Pow(10, 5)); + Add("-123456789987654321E+5", expectedValue); + Add("-123456789987654321e+5", expectedValue); + } + + private void AddLargePositiveCases() + { + QuantityValueData expectedValue = new QuantityValue(new BigInteger(123456789987654321) * BigInteger.Pow(10, 24)); + Add("1.23456789987654321E+41", expectedValue); + Add("1.23456789987654321e+41", expectedValue); + Add("1.234567899876543210E+41", expectedValue); + Add("1.234567899876543210e+41", expectedValue); + } + + private void AddLargeNegativeCases() + { + QuantityValueData expectedValue = new QuantityValue(new BigInteger(-123456789987654321) * BigInteger.Pow(10, 24)); + Add("-1.23456789987654321E+41", expectedValue); + Add("-1.23456789987654321e+41", expectedValue); + Add("-1.234567899876543210E+41", expectedValue); + Add("-1.234567899876543210e+41", expectedValue); + } + + private void AddSmallPositiveCases() + { + QuantityValueData expectedValue = new QuantityValue(new BigInteger(123456789987654321), BigInteger.Pow(10, 41)); + Add("1.23456789987654321E-24", expectedValue); + Add("1.23456789987654321e-24", expectedValue); + Add("1.234567899876543210E-24", expectedValue); + Add("1.234567899876543210e-24", expectedValue); + Add("1.23456789987654321E-24+", expectedValue); + Add("1.23456789987654321e-24+", expectedValue); + Add("1.234567899876543210E-24+", expectedValue); + Add("1.234567899876543210e-24+", expectedValue); + Add("12345.6789987654321E-28", expectedValue); + Add("12345.6789987654321e-28", expectedValue); + Add("12345.67899876543210E-28", expectedValue); + Add("12345.67899876543210e-28", expectedValue); + Add("12,345.6789987654321E-28", expectedValue); + Add("12,345.6789987654321e-28", expectedValue); + Add("12,345.67899876543210E-28", expectedValue); + Add("12,345.67899876543210e-28", expectedValue); + } + + private void AddSmallNegativeCases() + { + QuantityValueData expectedValue = new QuantityValue(new BigInteger(-123456789987654321), BigInteger.Pow(10, 41)); + Add("-1.23456789987654321E-24", expectedValue); + Add("-1.23456789987654321e-24", expectedValue); + Add("-1.234567899876543210E-24", expectedValue); + Add("-1.234567899876543210e-24", expectedValue); + } + } + } + + public class ParsingWithHexNotation + { + [Theory] + [InlineData("2A")] + public void ShouldNotWorkWhenParsingAsNumber(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.Number, CultureInfo.InvariantCulture, out _)); + } + + [Theory] + [InlineData("2A")] + [InlineData("2A ")] + [InlineData(" 2A")] + [InlineData(" 2A ")] + public void TheResultShouldBe42WhenParsingAsHex(string valueToParse) + { + var expectedValue = new QuantityValue(42); + var result = QuantityValue.Parse(valueToParse, NumberStyles.HexNumber, CultureInfo.InvariantCulture); + Assert.Equal(expectedValue, result); + } + + [Theory] + [InlineData("2 A")] + public void ShouldNotWorkWithSpacesInTheMiddle(string valueToParse) + { + Assert.False(QuantityValue.TryParse(valueToParse, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _)); + } + } + + public class ParsingWithCurrencySymbol + { + [Theory] + [InlineData("€3,5")] + [InlineData("€ 3,5")] + [InlineData("€3,5 ")] + [InlineData("€+3,5")] + [InlineData("€ +3,5")] + [InlineData("€+3,5 ")] + [InlineData("+€3,5")] + [InlineData("€3,5+")] + [InlineData("€3,5+ ")] + [InlineData("€3,5 + ")] + [InlineData(" €3,5 + ")] + [InlineData("€ 3,5+")] + [InlineData(" € 3,5+")] + [InlineData(" € 3,5 +")] + [InlineData(" € 3,5 + ")] + [InlineData("3,5€")] + [InlineData(" 3,5€")] + [InlineData("3,5 € ")] + [InlineData("+3,5€")] + [InlineData(" +3,5€")] + [InlineData("+3,5 €")] + [InlineData(" +3,5 €")] + [InlineData(" +3,5 € ")] + [InlineData("3,5€+")] + [InlineData(" 3,5€+")] + [InlineData("3,5 €+ ")] + [InlineData("3,5 € + ")] + [InlineData(" 3,5 € + ")] + [InlineData("3,5 €+")] + [InlineData(" 3,5€ +")] + [InlineData(" 3,5+ €")] + [InlineData(" 3,5 + € ")] + [InlineData("€+ 3,5")] + [InlineData("+€ 3,5")] + [InlineData(" € + 3,5")] + [InlineData(" +€ 3,5")] + public void Parsing_ValidCurrencyString_ShouldReturnTheExpectedResult(string value) + { + var germanCulture = CultureInfo.GetCultureInfo("de-DE"); + Assert.True(double.TryParse(value, NumberStyles.Any, germanCulture, out _), "making sure the format is also recognized by double.TryParse"); + var result = QuantityValue.Parse(value, NumberStyles.Any, germanCulture); + Assert.Equal(new QuantityValue(35, 10), result); + } + + [Theory] + [InlineData("-€3,5")] + [InlineData("€3,5-")] + [InlineData("€3,5- ")] + [InlineData("€3,5 - ")] + [InlineData(" €3,5 - ")] + [InlineData("€ 3,5-")] + [InlineData(" € 3,5-")] + [InlineData(" € 3,5 -")] + [InlineData(" € 3,5 - ")] + [InlineData("-3,5€")] + [InlineData(" -3,5€")] + [InlineData("-3,5 €")] + [InlineData(" -3,5 €")] + [InlineData(" -3,5 € ")] + [InlineData("3,5€-")] + [InlineData(" 3,5€-")] + [InlineData("3,5 €- ")] + [InlineData("3,5 € - ")] + [InlineData(" 3,5 € - ")] + [InlineData("3,5 €-")] + [InlineData(" 3,5€ -")] + [InlineData(" 3,5- €")] + [InlineData(" 3,5 - € ")] + [InlineData("€- 3,5")] + [InlineData("-€ 3,5")] + [InlineData(" € - 3,5")] + [InlineData(" -€ 3,5")] + [InlineData("€ (3,5)")] // any number of white-spaces are allowed following a leading currency symbol (but no other signs) + [InlineData("(€ 3,5)")] // any number of white-spaces are allowed following a leading currency symbol (but no other signs) + public void Parsing_NegativeCurrencyString_ShouldReturnTheExpectedResult(string value) + { + var germanCulture = CultureInfo.GetCultureInfo("de-DE"); + Assert.True(double.TryParse(value, NumberStyles.Any, germanCulture, out _), "making sure the format is also recognized by double.TryParse"); + var result = QuantityValue.Parse(value, NumberStyles.Any, germanCulture); + Assert.Equal(new QuantityValue(-35, 10), result); + } + + [Theory] + [InlineData("+ 3,5€")] + [InlineData("+ €3,5")] + [InlineData("+ € 3,5")] + [InlineData("- 3,5€")] + [InlineData("- €3,5")] + [InlineData("- € 3,5")] // this one is peculiar: any spaces after the leading sign are rejected (as long as there isn't a currency symbol preceding it) + public void Parsing_WithInvalidSpaces_ShouldNotWork(string value) + { + var germanCulture = CultureInfo.GetCultureInfo("de-DE"); + Assert.False(double.TryParse(value, NumberStyles.Any, germanCulture, out _), "the format isn't supposed to be recognized by double.TryParse"); + Assert.False(QuantityValue.TryParse(value, NumberStyles.Any, germanCulture, out _)); + } + + [Theory] + [InlineData("€3,5€")] + [InlineData("€+3,5€")] + [InlineData("+€3,5€")] + [InlineData("€3,5€+")] + [InlineData("€3,5+€")] + [InlineData("€-3,5€")] + [InlineData("-€3,5€")] + [InlineData("€3,5€-")] + [InlineData("€3,5-€")] + [InlineData("(€")] + public void Parsing_WithMultipleCurrencySymbols_ShouldNotWork(string value) + { + var germanCulture = CultureInfo.GetCultureInfo("de-DE"); + Assert.False(double.TryParse(value, NumberStyles.Any, germanCulture, out _), "the format isn't supposed to be recognized by double.TryParse"); + Assert.False(QuantityValue.TryParse(value, germanCulture, out _)); + } + + [Fact] + public void Parsing_CurrencyStringWithMultiCharacterSymbol_ShouldReturnTheExpectedResult() + { + var customCulture = (CultureInfo)CultureInfo.InvariantCulture.Clone(); + customCulture.NumberFormat.CurrencySymbol = "EUR"; + Assert.False(QuantityValue.TryParse("(1", NumberStyles.Any, customCulture, out _)); + } + + [Fact] + public void Parsing_WithCurrency_WhenTheCurrencyParsingIsDisabled_ShouldNotWork() + { + var germanCulture = CultureInfo.GetCultureInfo("de-DE"); + Assert.False(QuantityValue.TryParse("1€", NumberStyles.Any & ~NumberStyles.AllowCurrencySymbol, germanCulture, out _)); + } + + public class ParsingWithDefaultCulture + { + [Fact] + public void Parsing_NaN_or_InfinitySymbol_WithGermanCulture_ShouldReturnTheExpectedValue() + { + var formatProvider = CultureInfo.GetCultureInfo("de-DE"); + Assert.Equal(QuantityValue.NaN, QuantityValue.Parse("NaN", formatProvider)); + Assert.Equal(QuantityValue.PositiveInfinity, QuantityValue.Parse("∞", formatProvider)); + Assert.Equal(QuantityValue.NegativeInfinity, QuantityValue.Parse("-∞", formatProvider)); + } + + [Fact] + public void TryParse_WithValidString_ShouldReturnTheExpectedValue() + { + using var _ = new CultureScope("de-DE"); + Assert.True(QuantityValue.TryParse("123,45", null, out var result)); + Assert.Equal(new QuantityValue(12345, 100), result); + } + + [Fact] + public void TryParse_WithInvalidString_ShouldReturnFalse() + { + using var _ = new CultureScope("de-DE"); + Assert.False(QuantityValue.TryParse("12 345", null, out var _)); + } + +#if NET + [Fact] + public void Parse_ReadOnlySpan_WithValidString_ShouldReturnTheExpectedValue() + { + using var _ = new CultureScope("de-DE"); + ReadOnlySpan input = "123,45"; + var result = QuantityValue.Parse(input, null); + Assert.Equal(new QuantityValue(12345, 100), result); + } + + [Fact] + public void Parse_ReadOnlySpan_WithInvalidString_ShouldThrow_FormatException() + { + using var _ = new CultureScope("de-DE"); + Assert.Throws(() => QuantityValue.Parse("12 345".AsSpan(), null)); + } + + [Fact] + public void TryParse_ReadOnlySpan_WithValidString_ShouldReturnTheExpectedValue() + { + using var _ = new CultureScope("de-DE"); + ReadOnlySpan input = "123,45"; + Assert.True(QuantityValue.TryParse(input, null, out var result)); + Assert.Equal(new QuantityValue(12345, 100), result); + } + + [Fact] + public void TryParse_ReadOnlySpan_WithInvalidString_ShouldReturnFalse() + { + using var _ = new CultureScope("de-DE"); + Assert.False(QuantityValue.TryParse("12 345".AsSpan(), null, out var _)); + } +#endif + } + + public class ParsingWithCustomCulture + { + [Fact] + public void Parsing_WithCustomizedCulture_RespectsTheCultureFormat() + { + // Arrange + var customCulture = (CultureInfo)CultureInfo.InvariantCulture.Clone(); + customCulture.NumberFormat.NegativeSign = "_minus_"; + customCulture.NumberFormat.NumberGroupSeparator = "_group_"; + customCulture.NumberFormat.NumberDecimalSeparator = "_decimal_"; + var valueToParse = "_minus_1_group_234_decimal_56"; + QuantityValue expectedValue = -1234.56m; + + // Act + var parsedValue = QuantityValue.Parse(valueToParse, NumberStyles.Number, customCulture); + + // Assert + Assert.Equal(expectedValue, parsedValue); + } + + [Fact] + public void Parsing_NaN_or_InfinitySymbol_WithCustomCulture_ShouldReturnTheExpectedValue() + { + // Arrange + var customCulture = (CultureInfo)CultureInfo.InvariantCulture.Clone(); + customCulture.NumberFormat.NaNSymbol = "Q"; + customCulture.NumberFormat.PositiveInfinitySymbol = "P"; + customCulture.NumberFormat.NegativeInfinitySymbol = "N"; + Assert.Equal(QuantityValue.NaN, QuantityValue.Parse("Q", customCulture)); + Assert.Equal(QuantityValue.PositiveInfinity, QuantityValue.Parse("P", customCulture)); + Assert.Equal(QuantityValue.NegativeInfinity, QuantityValue.Parse("N", customCulture)); + } + + [Fact] + public void Parsing_CurrencyStringWithCustomCultureWithoutCurrencySymbol_ShouldNotWork() + { + // Arrange + var customCulture = (CultureInfo)CultureInfo.InvariantCulture.Clone(); + customCulture.NumberFormat.CurrencySymbol = string.Empty; + Assert.False(QuantityValue.TryParse("1.5€", NumberStyles.Any, customCulture, out _)); + } + + [Fact] + public void NumberFormat_WithEmptyDecimalSeparator_ThrowsArgumentException() + { + var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone(); + Assert.Throws(() => formatProvider.NumberFormat.NumberDecimalSeparator = string.Empty); + Assert.Equal("1", formatProvider.NumberFormat.NumberDecimalSeparator = "1"); + } + } + } + } +} diff --git a/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ConvertToNumber.cs b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ConvertToNumber.cs new file mode 100644 index 0000000000..d00c8cf95a --- /dev/null +++ b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ConvertToNumber.cs @@ -0,0 +1,920 @@ +using System.Numerics; + +namespace UnitsNet.Tests; + +public partial class QuantityValueTests +{ + public class ConvertToNumberTests + { + public class ToDecimalTests + { + [Fact] + public void ToDecimal_WithNaNOrInfinity_ThrowsOverflowException() + { + Assert.Throws(() => QuantityValue.NaN.ToDecimal()); + Assert.Throws(() => QuantityValue.PositiveInfinity.ToDecimal()); + Assert.Throws(() => QuantityValue.NegativeInfinity.ToDecimal()); + } + + [Fact] + public void ToDecimal_WithValueOutsideTheDecimalRange_ThrowsOverflowException() + { + var largeNumber = 2 * new BigInteger(decimal.MaxValue); + Assert.Throws(() => new QuantityValue(largeNumber).ToDecimal()); + Assert.Throws(() => new QuantityValue(-largeNumber).ToDecimal()); + Assert.Throws(() => new QuantityValue(1, largeNumber).ToDecimal()); + Assert.Throws(() => new QuantityValue(-1, largeNumber).ToDecimal()); + } + + [Theory] + [ClassData(typeof(ToDecimalTestData))] + public void ToDecimal_WithAValueWithinTheDecimalRange_ReturnsTheExpectedResult(BigInteger numerator, BigInteger denominator, decimal expected) + { + var quantityValue = new QuantityValue(numerator, denominator); + Assert.Equal(expected, quantityValue.ToDecimal()); + } + + public class ToDecimalTestData : TheoryData + { + public ToDecimalTestData() + { + var largeNumber = 2 * new BigInteger(decimal.MaxValue); + // Zero cases + Add(0, 1, 0.0m); // 0 / 1 + Add(0, 10, 0.0m); // 0 / 10 + Add(0, largeNumber, 0.0m); // 0 / largeNumber + // Positive cases + Add(2, 1, 2.0m); // 2 / 1 + Add(1, 2, 0.5m); // 1 / 2 + Add(1, 3, 1.0m / 3.0m); // 1 / 3 + Add(largeNumber, 4, decimal.MaxValue / 2); // 2 * maxValue / 4 + Add(4, largeNumber, 2 / decimal.MaxValue); // 4 / (maxValue * 2) + Add(3, largeNumber, 1.5m / decimal.MaxValue); // 3 / (maxValue * 2) + Add(largeNumber, largeNumber, 1.0m); // largeNumber / largeNumber + Add(2 * largeNumber, largeNumber, 2.0m); // 2 * largeNumber / largeNumber + Add(largeNumber, 2 * largeNumber, 0.5m); // largeNumber / 2 * largeNumber + Add(3 * largeNumber, 2 * largeNumber, 1.5m); // 3 * largeNumber / 2 * largeNumber + Add(2 * largeNumber, 3 * largeNumber, 2.0m / 3.0m); // 2 * largeNumber / 3 * largeNumber + // Negative cases + Add(-2, 1, -2.0m); // -2 / 1 + Add(-1, 2, -0.5m); // -1 / 2 + Add(-1, 3, -1.0m / 3.0m); // -1 / 3 + Add(-largeNumber, 4, decimal.MinValue / 2); // -2 * maxValue / 4 + Add(-4, largeNumber, -2 / decimal.MaxValue); // -4 / (maxValue * 2) + Add(-3, largeNumber, -1.5m / decimal.MaxValue); // -3 / (maxValue * 2) + Add(-largeNumber, largeNumber, -1.0m); // -largeNumber / largeNumber + Add(-2 * largeNumber, largeNumber, -2.0m); // -2 * largeNumber / largeNumber + Add(-largeNumber, 2 * largeNumber, -0.5m); // -largeNumber / 2 * largeNumber + Add(-3 * largeNumber, 2 * largeNumber, -1.5m); // -3 * largeNumber / 2 * largeNumber + Add(-2 * largeNumber, 3 * largeNumber, -2.0m / 3.0m); // -2 * largeNumber / 3 * largeNumber + } + } + } + + public class ToDecimalSaturatingTests + { + [Theory] + [ClassData(typeof(ToDecimalSaturatingTestData))] + public void ToDecimalSaturating_ConvertsTheValueToTheDecimalRange(BigInteger numerator, BigInteger denominator, decimal expected) + { + var quantityValue = new QuantityValue(numerator, denominator); + Assert.Equal(expected, quantityValue.ToDecimalSaturating()); + } + + public class ToDecimalSaturatingTestData : TheoryData + { + public ToDecimalSaturatingTestData() + { + var largeNumber = 2 * new BigInteger(decimal.MaxValue); + // Zero cases + Add(0, 1, 0.0m); // 0 / 1 + Add(0, 10, 0.0m); // 0 / 10 + Add(0, largeNumber, 0.0m); // 0 / largeNumber + // Positive cases + Add(2, 1, 2.0m); // 2 / 1 + Add(1, 2, 0.5m); // 1 / 2 + Add(1, 3, 1.0m / 3.0m); // 1 / 3 + Add(largeNumber, 4, decimal.MaxValue / 2); // 2 * maxValue / 4 + Add(4, largeNumber, 2 / decimal.MaxValue); // 4 / (maxValue * 2) + Add(3, largeNumber, 1.5m / decimal.MaxValue); // 3 / (maxValue * 2) + Add(largeNumber, largeNumber, 1.0m); // largeNumber / largeNumber + Add(2 * largeNumber, largeNumber, 2.0m); // 2 * largeNumber / largeNumber + Add(largeNumber, 2 * largeNumber, 0.5m); // largeNumber / 2 * largeNumber + Add(3 * largeNumber, 2 * largeNumber, 1.5m); // 3 * largeNumber / 2 * largeNumber + Add(2 * largeNumber, 3 * largeNumber, 2.0m / 3.0m); // 2 * largeNumber / 3 * largeNumber + // Negative cases + Add(-2, 1, -2.0m); // -2 / 1 + Add(-1, 2, -0.5m); // -1 / 2 + Add(-1, 3, -1.0m / 3.0m); // -1 / 3 + Add(-largeNumber, 4, decimal.MinValue / 2); // -2 * maxValue / 4 + Add(-4, largeNumber, -2 / decimal.MaxValue); // -4 / (maxValue * 2) + Add(-3, largeNumber, -1.5m / decimal.MaxValue); // -3 / (maxValue * 2) + Add(-largeNumber, largeNumber, -1.0m); // -largeNumber / largeNumber + Add(-2 * largeNumber, largeNumber, -2.0m); // -2 * largeNumber / largeNumber + Add(-largeNumber, 2 * largeNumber, -0.5m); // -largeNumber / 2 * largeNumber + Add(-3 * largeNumber, 2 * largeNumber, -1.5m); // -3 * largeNumber / 2 * largeNumber + Add(-2 * largeNumber, 3 * largeNumber, -2.0m / 3.0m); // -2 * largeNumber / 3 * largeNumber + // overflowing cases + Add(largeNumber, 1, decimal.MaxValue); + Add(-largeNumber, 1, decimal.MinValue); + Add(2 * largeNumber, 2, decimal.MaxValue); + Add(-2 * largeNumber, 2, decimal.MinValue); + Add(1, largeNumber, 0m); + Add(-1, largeNumber, 0m); + // special values + Add(0, 0, 0m); // NaN + Add(1, 0, decimal.MaxValue); // PositiveInfinity + Add(-1, 0, decimal.MinValue); // NegativeInfinity + } + } + } + + public class ToDoubleTests + { + [Theory] + [ClassData(typeof(ToDoubleTestData))] + public void ToDouble_ConvertsTheValueToTheDoubleRange(BigInteger numerator, BigInteger denominator, double expected) + { + var quantityValue = new QuantityValue(numerator, denominator); + Assert.Equal(expected, quantityValue.ToDouble()); + } + + public class ToDoubleTestData : TheoryData + { + public ToDoubleTestData() + { + var largeNumber = 2 * new BigInteger(double.MaxValue); + // Zero cases + Add(0, 1, 0.0); // 0 / 1 + Add(0, 10, 0.0); // 0 / 10 + Add(0, largeNumber, 0.0); // 0 / largeNumber + // Positive cases + Add(2, 1, 2.0); // 2 / 1 + Add(1, 2, 0.5); // 1 / 2 + Add(1, 3, 1.0 / 3.0); // 1 / 3 + Add(largeNumber, 4, double.MaxValue / 2); // 2 * maxValue / 4 + Add(4, largeNumber, 2 / double.MaxValue); // 4 / (maxValue * 2) + Add(3, largeNumber, 1.5 / double.MaxValue); // 3 / (maxValue * 2) + Add(largeNumber, largeNumber, 1.0); // largeNumber / largeNumber + Add(2 * largeNumber, largeNumber, 2.0); // 2 * largeNumber / largeNumber + Add(largeNumber, 2 * largeNumber, 0.5); // largeNumber / 2 * largeNumber + Add(3 * largeNumber, 2 * largeNumber, 1.5); // 3 * largeNumber / 2 * largeNumber + Add(2 * largeNumber, 3 * largeNumber, 2.0 / 3.0); // 2 * largeNumber / 3 * largeNumber + // Negative cases + Add(-2, 1, -2.0); // -2 / 1 + Add(-1, 2, -0.5); // -1 / 2 + Add(-1, 3, -1.0 / 3.0); // -1 / 3 + Add(-largeNumber, 4, double.MinValue / 2); // -2 * maxValue / 4 + Add(-4, largeNumber, -2 / double.MaxValue); // -4 / (maxValue * 2) + Add(-3, largeNumber, -1.5 / double.MaxValue); // -3 / (maxValue * 2) + Add(-largeNumber, largeNumber, -1.0); // -largeNumber / largeNumber + Add(-2 * largeNumber, largeNumber, -2.0); // -2 * largeNumber / largeNumber + Add(-largeNumber, 2 * largeNumber, -0.5); // -largeNumber / 2 * largeNumber + Add(-3 * largeNumber, 2 * largeNumber, -1.5); // -3 * largeNumber / 2 * largeNumber + Add(-2 * largeNumber, 3 * largeNumber, -2.0 / 3.0); // -2 * largeNumber / 3 * largeNumber + // overflowing cases + Add(largeNumber, 1, double.PositiveInfinity); + Add(-largeNumber, 1, double.NegativeInfinity); + Add(2 * largeNumber, 2, double.PositiveInfinity); + Add(-2 * largeNumber, 2, double.NegativeInfinity); + Add(1, largeNumber, 0); + Add(-1, largeNumber, 0); + // special values + Add(0, 0, double.NaN); // NaN + Add(1, 0, double.PositiveInfinity); // PositiveInfinity + Add(-1, 0, double.NegativeInfinity); // NegativeInfinity + } + } + } + + public class ExplicitConversionTests + { + [Fact] + public void ExplicitConversionToDecimal() + { + var quantityValue = new QuantityValue(42, 10); + Assert.Equal(quantityValue.ToDecimal(), (decimal)quantityValue); + } + + [Fact] + public void ExplicitConversionToDouble() + { + var quantityValue = new QuantityValue(42, 10); + Assert.Equal(4.2, (double)quantityValue); + } + + [Fact] + public void ExplicitConversionToFloat() + { + var quantityValue = new QuantityValue(42, 10); + Assert.Equal(4.2, (float)quantityValue, 2); + } + + [Fact] + public void ExplicitConversionToBigInteger() + { + var quantityValue = new QuantityValue(42, 10); + Assert.Equal(4, (BigInteger)quantityValue); + } + + [Fact] + public void ExplicitConversionToLong() + { + var quantityValue = new QuantityValue(42, 10); + Assert.Equal(4, (long)quantityValue); + } + + [Fact] + public void ExplicitConversionToULong() + { + var quantityValue = new QuantityValue(42, 10); + Assert.Equal(4ul, (ulong)quantityValue); + } + + [Fact] + public void ExplicitConversionToInteger() + { + var quantityValue = new QuantityValue(42, 10); + Assert.Equal(4, (int)quantityValue); + } + + [Fact] + public void ExplicitConversionToUInt() + { + var quantityValue = new QuantityValue(42, 10); + Assert.Equal(4u, (uint)quantityValue); + } + + [Fact] + public void ExplicitConversionToShort() + { + var quantityValue = new QuantityValue(42, 10); + Assert.Equal(4, (short)quantityValue); + } + + [Fact] + public void ExplicitConversionToUShort() + { + var quantityValue = new QuantityValue(42, 10); + Assert.Equal((ushort)4, (ushort)quantityValue); + } + + [Fact] + public void ExplicitConversionToByte() + { + var quantityValue = new QuantityValue(42, 10); + Assert.Equal((byte)4, (byte)quantityValue); + } + +#if NET + [Fact] + public void ExplicitConversionToHalf() + { + var quantityValue = new QuantityValue(42, 10); + Assert.Equal((Half)4.2, (Half)quantityValue); + } + + [Fact] + public void ExplicitConversionToInt128() + { + var quantityValue = new QuantityValue(42, 10); + Assert.Equal(4, (Int128)quantityValue); + } + + [Fact] + public void ExplicitConversionToUInt128() + { + var quantityValue = new QuantityValue(42, 10); + Assert.Equal((UInt128)4, (UInt128)quantityValue); + } +#endif + } + + public class ConvertibleTests + { + [Fact] + public void ToDecimal_ConvertsChecked() + { + IConvertible quantityValue = new QuantityValue(42, 10); + Assert.Equal(4.2m, quantityValue.ToDecimal(null)); + } + + [Fact] + public void ToDouble_ConvertsSaturating() + { + IConvertible quantityValue = new QuantityValue(42, 10); + Assert.Equal(4.2, quantityValue.ToDouble(null)); + } + + [Fact] + public void ToSingle_ConvertsSaturating() + { + IConvertible quantityValue = new QuantityValue(42, 10); + Assert.Equal(4.2f, quantityValue.ToSingle(null), 2); + } + + [Fact] + public void ToInt64_ConvertsChecked() + { + IConvertible quantityValue = new QuantityValue(42, 10); + Assert.Equal(4L, quantityValue.ToInt64(null)); + } + + [Fact] + public void ToUInt64_ConvertsChecked() + { + IConvertible quantityValue = new QuantityValue(42, 10); + Assert.Equal(4ul, quantityValue.ToUInt64(null)); + } + + [Fact] + public void ToInt32_ConvertsChecked() + { + IConvertible quantityValue = new QuantityValue(42, 10); + Assert.Equal(4, quantityValue.ToInt32(null)); + } + + [Fact] + public void ToUInt32_ConvertsChecked() + { + IConvertible quantityValue = new QuantityValue(42, 10); + Assert.Equal(4u, quantityValue.ToUInt32(null)); + } + + [Fact] + public void ToUInt16_ConvertsChecked() + { + IConvertible quantityValue = new QuantityValue(42, 10); + Assert.Equal((ushort)4, quantityValue.ToUInt16(null)); + } + + [Fact] + public void ToInt16_ConvertsChecked() + { + IConvertible quantityValue = new QuantityValue(42, 10); + Assert.Equal((short)4, quantityValue.ToInt16(null)); + } + + [Fact] + public void ToByte_ConvertsChecked() + { + IConvertible quantityValue = new QuantityValue(42, 10); + Assert.Equal((byte)4, quantityValue.ToByte(null)); + } + + [Fact] + public void ToSByte_ConvertsChecked() + { + IConvertible quantityValue = new QuantityValue(42, 10); + Assert.Equal((sbyte)4, quantityValue.ToSByte(null)); + } + + [Fact] + public void ToChar_ThrowsInvalidCastException() + { + IConvertible quantityValue = new QuantityValue(42, 10); + Assert.Throws(() => quantityValue.ToChar(null)); + } + + [Fact] + public void ToBoolean_ThrowsInvalidCastException() + { + IConvertible quantityValue = new QuantityValue(42, 10); + Assert.Throws(() => quantityValue.ToBoolean(null)); + } + + [Fact] + public void ToDateTime_ThrowsInvalidCastException() + { + IConvertible quantityValue = new QuantityValue(42, 10); + Assert.Throws(() => quantityValue.ToDateTime(null)); + } + + [Fact] + public void ToString_ReturnsTheValueAsString() + { + var valueToConvert = new QuantityValue(42, 10); + IFormatProvider? formatProvider = null; + var expectedFormat = valueToConvert.ToString(null, formatProvider); + IConvertible quantityValue = valueToConvert; + Assert.Equal(expectedFormat, quantityValue.ToString(formatProvider)); + } + + [Fact] + public void GetTypeCode_ReturnsObject() + { + IConvertible quantityValue = QuantityValue.One; + Assert.Equal(TypeCode.Object, quantityValue.GetTypeCode()); + } + + [Fact] + public void ToType_WithNumericType_ReturnsTheExpectedResult() + { + IConvertible quantityValue = new QuantityValue(42, 10); + Assert.Equal(4.2, quantityValue.ToType(typeof(double), null)); + Assert.Equal(4.2m, quantityValue.ToType(typeof(decimal), null)); + Assert.Equal(4.2, (float)quantityValue.ToType(typeof(float), null), 2); + Assert.Equal(4L, quantityValue.ToType(typeof(long), null)); + Assert.Equal(4ul, quantityValue.ToType(typeof(ulong), null)); + Assert.Equal(4, quantityValue.ToType(typeof(int), null)); + Assert.Equal(4u, quantityValue.ToType(typeof(uint), null)); + Assert.Equal((short)4, quantityValue.ToType(typeof(short), null)); + Assert.Equal((ushort)4, quantityValue.ToType(typeof(ushort), null)); + Assert.Equal((byte)4, quantityValue.ToType(typeof(byte), null)); + Assert.Equal((sbyte)4, quantityValue.ToType(typeof(sbyte), null)); + } + + [Fact] + public void ToType_WithTypeOfString_ReturnsTheValueAsString() + { + var valueToConvert = new QuantityValue(42, 10); + IFormatProvider? formatProvider = null; + var expectedFormat = valueToConvert.ToString(null, formatProvider); + IConvertible quantityValue = valueToConvert; + Assert.Equal(expectedFormat, quantityValue.ToType(typeof(string), formatProvider)); + } + + [Fact] + public void ToType_WithUnsupportedType_ThrowsInvalidCastException() + { + IConvertible valueToConvert = QuantityValue.One; + Assert.Throws(() => valueToConvert.ToType(typeof(bool), null)); + } + + [Fact] + public void ToType_WithNullType_ThrowsArgumentNullException() + { + IConvertible valueToConvert = QuantityValue.One; + Assert.Throws(() => valueToConvert.ToType(null!, null)); + } + } +#if NET7_0_OR_GREATER + + public class ConvertToCheckedTests + { + private static TNumber CreateChecked(TOther value) + where TNumber : INumberBase + where TOther : INumberBase + { + return TNumber.CreateChecked(value); + } + + [Fact] + public void CreateChecked_FromFinitePositiveValue_ShouldReturnTheExpectedValue() + { + var quantityValue = new QuantityValue(3, 2); + Assert.Equal(1.5, double.CreateChecked(quantityValue)); + Assert.Equal(new Complex(1.5, 0), Complex.CreateChecked(quantityValue)); + Assert.Equal(1.5m, decimal.CreateChecked(quantityValue)); + Assert.Equal(1.5f, float.CreateChecked(quantityValue)); + Assert.Equal((Half)1.5, Half.CreateChecked(quantityValue)); + Assert.Equal(1, BigInteger.CreateChecked(quantityValue)); + Assert.Equal(1, Int128.CreateChecked(quantityValue)); + Assert.Equal(1u, UInt128.CreateChecked(quantityValue)); + Assert.Equal(1, long.CreateChecked(quantityValue)); + Assert.Equal((ulong)1, ulong.CreateChecked(quantityValue)); + Assert.Equal(1, int.CreateChecked(quantityValue)); + Assert.Equal((uint)1, uint.CreateChecked(quantityValue)); + Assert.Equal(1, nint.CreateChecked(quantityValue)); + Assert.Equal((UIntPtr)1, UIntPtr.CreateChecked(quantityValue)); + Assert.Equal((short)1, short.CreateChecked(quantityValue)); + Assert.Equal((ushort)1, ushort.CreateChecked(quantityValue)); + Assert.Equal((byte)1, byte.CreateChecked(quantityValue)); + Assert.Equal((sbyte)1, sbyte.CreateChecked(quantityValue)); + // although there isn't any char.CreateChecked(..) method, all numeric types support this conversion as well + Assert.Equal('a', CreateChecked(97.9)); + Assert.Equal('a', CreateChecked(new QuantityValue(979, 10))); + } + + [Fact] + public void CreateChecked_FromFiniteNegativeValue_ShouldReturnTheExpectedValue() + { + var fraction = new QuantityValue(-3, 2); + Assert.Equal(-1.5, double.CreateChecked(fraction)); + Assert.Equal(new Complex(-1.5, 0), Complex.CreateChecked(fraction)); + Assert.Equal(-1.5m, decimal.CreateChecked(fraction)); + Assert.Equal(-1.5f, float.CreateChecked(fraction)); + Assert.Equal((Half)(-1.5), Half.CreateChecked(fraction)); + Assert.Equal(-1, BigInteger.CreateChecked(fraction)); + Assert.Equal(-1, Int128.CreateChecked(fraction)); + Assert.Throws(() => UInt128.CreateChecked(fraction)); + Assert.Equal(-1, long.CreateChecked(fraction)); + Assert.Throws(() => ulong.CreateChecked(fraction)); + Assert.Equal(-1, int.CreateChecked(fraction)); + Assert.Throws(() => uint.CreateChecked(fraction)); + Assert.Equal(-1, nint.CreateChecked(fraction)); + Assert.Throws(() => UIntPtr.CreateChecked(fraction)); + Assert.Equal((short)-1, short.CreateChecked(fraction)); + Assert.Throws(() => ushort.CreateChecked(fraction)); + Assert.Throws(() => byte.CreateChecked(fraction)); + Assert.Equal((sbyte)-1, sbyte.CreateChecked(fraction)); + // although there isn't any char.CreateChecked(..) method, all numeric types support this conversion as well + Assert.Throws(() => CreateChecked(-1.5)); + Assert.Throws(() => CreateChecked(fraction)); + } + + [Fact] + public void CreateChecked_FromNaN_ShouldReturnNaNOrThrowAnException() + { + Assert.Equal(double.NaN, double.CreateChecked(QuantityValue.NaN)); + Assert.Equal(new Complex(double.NaN, 0), Complex.CreateChecked(QuantityValue.NaN)); + Assert.Throws(() => decimal.CreateChecked(QuantityValue.NaN)); + Assert.Equal(float.NaN, float.CreateChecked(QuantityValue.NaN)); + Assert.Equal(Half.NaN, Half.CreateChecked(QuantityValue.NaN)); + Assert.Throws(() => BigInteger.CreateChecked(QuantityValue.NaN)); + Assert.Throws(() => Int128.CreateChecked(QuantityValue.NaN)); + Assert.Throws(() => UInt128.CreateChecked(QuantityValue.NaN)); + Assert.Throws(() => long.CreateChecked(QuantityValue.NaN)); + Assert.Throws(() => ulong.CreateChecked(QuantityValue.NaN)); + Assert.Throws(() => int.CreateChecked(QuantityValue.NaN)); + Assert.Throws(() => uint.CreateChecked(QuantityValue.NaN)); + Assert.Throws(() => nint.CreateChecked(QuantityValue.NaN)); + Assert.Throws(() => UIntPtr.CreateChecked(QuantityValue.NaN)); + Assert.Throws(() => short.CreateChecked(QuantityValue.NaN)); + Assert.Throws(() => ushort.CreateChecked(QuantityValue.NaN)); + Assert.Throws(() => byte.CreateChecked(QuantityValue.NaN)); + Assert.Throws(() => sbyte.CreateChecked(QuantityValue.NaN)); + // although there isn't any char.CreateChecked(..) method, all numeric types support this conversion as well + Assert.Throws(() => CreateChecked(double.NaN)); + Assert.Throws(() => CreateChecked(QuantityValue.NaN)); + } + + [Fact] + public void CreateChecked_FromPositiveInfinity_ShouldReturnPositiveInfinityOrThrowOverflowException() + { + Assert.Equal(double.PositiveInfinity, double.CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Equal(new Complex(double.PositiveInfinity, 0), Complex.CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Throws(() => decimal.CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Equal(float.PositiveInfinity, float.CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Equal(Half.PositiveInfinity, Half.CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Throws(() => BigInteger.CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Throws(() => Int128.CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Throws(() => UInt128.CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Throws(() => long.CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Throws(() => ulong.CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Throws(() => int.CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Throws(() => uint.CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Throws(() => nint.CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Throws(() => UIntPtr.CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Throws(() => short.CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Throws(() => ushort.CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Throws(() => byte.CreateChecked(QuantityValue.PositiveInfinity)); + Assert.Throws(() => sbyte.CreateChecked(QuantityValue.PositiveInfinity)); + // although there isn't any char.CreateChecked(..) method, all numeric types support this conversion as well + Assert.Throws(() => CreateChecked(double.PositiveInfinity)); + Assert.Throws(() => CreateChecked(QuantityValue.PositiveInfinity)); + } + + [Fact] + public void CreateChecked_FromNegativeInfinity_ShouldReturnNegativeInfinityOrThrowOverflowException() + { + Assert.Equal(double.NegativeInfinity, double.CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Equal(new Complex(double.NegativeInfinity, 0), Complex.CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Throws(() => decimal.CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Equal(float.NegativeInfinity, float.CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Equal(Half.NegativeInfinity, Half.CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Throws(() => BigInteger.CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Throws(() => Int128.CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Throws(() => UInt128.CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Throws(() => long.CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Throws(() => ulong.CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Throws(() => int.CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Throws(() => uint.CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Throws(() => nint.CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Throws(() => UIntPtr.CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Throws(() => short.CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Throws(() => ushort.CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Throws(() => byte.CreateChecked(QuantityValue.NegativeInfinity)); + Assert.Throws(() => sbyte.CreateChecked(QuantityValue.NegativeInfinity)); + // although there isn't any char.CreateChecked(..) method, all numeric types support this conversion as well + Assert.Throws(() => CreateChecked(double.NegativeInfinity)); + Assert.Throws(() => CreateChecked(QuantityValue.NegativeInfinity)); + } + + [Fact] + public void CreateChecked_WithUnsupportedType_ThrowsNotSupportedException() + { + Assert.Throws(() => CreateChecked(QuantityValue.One)); + } + } + + public class ConvertToSaturatingTests + { + private static TNumber CreateSaturating(TOther value) + where TNumber : INumberBase + where TOther : INumberBase + { + return TNumber.CreateSaturating(value); + } + + [Fact] + public void CreateSaturating_FromFinitePositiveValue_ShouldReturnTheExpectedValue() + { + var quantityValue = new QuantityValue(3, 2); + Assert.Equal(1.5, double.CreateSaturating(quantityValue)); + Assert.Equal(new Complex(1.5, 0), Complex.CreateSaturating(quantityValue)); + Assert.Equal(1.5m, decimal.CreateSaturating(quantityValue)); + Assert.Equal(1.5f, float.CreateSaturating(quantityValue)); + Assert.Equal((Half)1.5, Half.CreateSaturating(quantityValue)); + Assert.Equal(1, BigInteger.CreateSaturating(quantityValue)); + Assert.Equal(1, Int128.CreateSaturating(quantityValue)); + Assert.Equal(1u, UInt128.CreateSaturating(quantityValue)); + Assert.Equal(1, long.CreateSaturating(quantityValue)); + Assert.Equal((ulong)1, ulong.CreateSaturating(quantityValue)); + Assert.Equal(1, int.CreateSaturating(quantityValue)); + Assert.Equal((uint)1, uint.CreateSaturating(quantityValue)); + Assert.Equal(1, nint.CreateSaturating(quantityValue)); + Assert.Equal((UIntPtr)1, UIntPtr.CreateSaturating(quantityValue)); + Assert.Equal((short)1, short.CreateSaturating(quantityValue)); + Assert.Equal((ushort)1, ushort.CreateSaturating(quantityValue)); + Assert.Equal((byte)1, byte.CreateSaturating(quantityValue)); + Assert.Equal((sbyte)1, sbyte.CreateSaturating(quantityValue)); + // although there isn't any char.CreateSaturating(..) method, all numeric types support this conversion as well + Assert.Equal('a', CreateSaturating(97.9)); + Assert.Equal('a', CreateSaturating(new QuantityValue(979, 10))); + } + + [Fact] + public void CreateSaturating_FromFiniteNegativeValue_ShouldReturnTheExpectedValue() + { + var fraction = new QuantityValue(-3, 2); + Assert.Equal(-1.5, double.CreateSaturating(fraction)); + Assert.Equal(new Complex(-1.5, 0), Complex.CreateSaturating(fraction)); + Assert.Equal(-1.5m, decimal.CreateSaturating(fraction)); + Assert.Equal(-1.5f, float.CreateSaturating(fraction)); + Assert.Equal((Half)(-1.5), Half.CreateSaturating(fraction)); + Assert.Equal(-1, BigInteger.CreateSaturating(fraction)); + Assert.Equal(-1, Int128.CreateSaturating(fraction)); + Assert.Equal(0u, UInt128.CreateSaturating(fraction)); + Assert.Equal(-1, long.CreateSaturating(fraction)); + Assert.Equal(0UL, ulong.CreateSaturating(fraction)); + Assert.Equal(-1, int.CreateSaturating(fraction)); + Assert.Equal(0U, uint.CreateSaturating(fraction)); + Assert.Equal(-1, nint.CreateSaturating(fraction)); + Assert.Equal((UIntPtr)0, UIntPtr.CreateSaturating(fraction)); + Assert.Equal((short)-1, short.CreateSaturating(fraction)); + Assert.Equal((ushort)0, ushort.CreateSaturating(fraction)); + Assert.Equal((byte)0, byte.CreateSaturating(fraction)); + Assert.Equal((sbyte)-1, sbyte.CreateSaturating(fraction)); + // although there isn't any char.CreateSaturating(..) method, all numeric types support this conversion as well + Assert.Equal(char.MinValue, CreateSaturating(-1.5)); + Assert.Equal(char.MinValue, CreateSaturating(fraction)); + } + + [Fact] + public void CreateSaturating_FromNaN_ShouldReturnZeroOrNaN() + { + Assert.Equal(double.NaN, double.CreateSaturating(QuantityValue.NaN)); + Assert.Equal(new Complex(double.NaN, 0), Complex.CreateSaturating(QuantityValue.NaN)); + Assert.Equal(decimal.Zero, decimal.CreateSaturating(QuantityValue.NaN)); + Assert.Equal(float.NaN, float.CreateSaturating(QuantityValue.NaN)); + Assert.Equal(Half.NaN, Half.CreateSaturating(QuantityValue.NaN)); + Assert.Equal(BigInteger.Zero, BigInteger.CreateSaturating(QuantityValue.NaN)); + Assert.Equal(Int128.Zero, Int128.CreateSaturating(QuantityValue.NaN)); + Assert.Equal(UInt128.Zero, UInt128.CreateSaturating(QuantityValue.NaN)); + Assert.Equal(0, long.CreateSaturating(QuantityValue.NaN)); + Assert.Equal(0UL, ulong.CreateSaturating(QuantityValue.NaN)); + Assert.Equal(0, int.CreateSaturating(QuantityValue.NaN)); + Assert.Equal(0U, uint.CreateSaturating(QuantityValue.NaN)); + Assert.Equal(nint.Zero, nint.CreateSaturating(QuantityValue.NaN)); + Assert.Equal(UIntPtr.Zero, UIntPtr.CreateSaturating(QuantityValue.NaN)); + Assert.Equal(default, short.CreateSaturating(QuantityValue.NaN)); + Assert.Equal(default, ushort.CreateSaturating(QuantityValue.NaN)); + Assert.Equal(default, byte.CreateSaturating(QuantityValue.NaN)); + Assert.Equal(default, sbyte.CreateSaturating(QuantityValue.NaN)); + // although there isn't any char.CreateChecked(..) method, all numeric types support this conversion as well + Assert.Equal('\0', CreateSaturating(double.NaN)); + Assert.Equal('\0', CreateSaturating(QuantityValue.NaN)); + } + + [Fact] + public void CreateSaturating_BigInteger_FromPositiveInfinity_ShouldThrowOverflowException() + { + Assert.Throws(() => BigInteger.CreateSaturating(QuantityValue.PositiveInfinity)); + } + + [Fact] + public void CreateSaturating_FromPositiveInfinity_ShouldReturnMaxValueOrPositiveInfinity() + { + Assert.Equal(double.PositiveInfinity, double.CreateSaturating(QuantityValue.PositiveInfinity)); + Assert.Equal(new Complex(double.PositiveInfinity, 0), Complex.CreateSaturating(QuantityValue.PositiveInfinity)); + Assert.Equal(decimal.MaxValue, decimal.CreateSaturating(QuantityValue.PositiveInfinity)); + Assert.Equal(float.PositiveInfinity, float.CreateSaturating(QuantityValue.PositiveInfinity)); + Assert.Equal(Half.PositiveInfinity, Half.CreateSaturating(QuantityValue.PositiveInfinity)); + Assert.Equal(Int128.MaxValue, Int128.CreateSaturating(QuantityValue.PositiveInfinity)); + Assert.Equal(UInt128.MaxValue, UInt128.CreateSaturating(QuantityValue.PositiveInfinity)); + Assert.Equal(long.MaxValue, long.CreateSaturating(QuantityValue.PositiveInfinity)); + Assert.Equal(ulong.MaxValue, ulong.CreateSaturating(QuantityValue.PositiveInfinity)); + Assert.Equal(int.MaxValue, int.CreateSaturating(QuantityValue.PositiveInfinity)); + Assert.Equal(uint.MaxValue, uint.CreateSaturating(QuantityValue.PositiveInfinity)); + Assert.Equal(nint.MaxValue, nint.CreateSaturating(QuantityValue.PositiveInfinity)); + Assert.Equal(UIntPtr.MaxValue, UIntPtr.CreateSaturating(QuantityValue.PositiveInfinity)); + Assert.Equal(short.MaxValue, short.CreateSaturating(QuantityValue.PositiveInfinity)); + Assert.Equal(ushort.MaxValue, ushort.CreateSaturating(QuantityValue.PositiveInfinity)); + Assert.Equal(byte.MaxValue, byte.CreateSaturating(QuantityValue.PositiveInfinity)); + Assert.Equal(sbyte.MaxValue, sbyte.CreateSaturating(QuantityValue.PositiveInfinity)); + // although there isn't any char.CreateSaturating(..) method, all numeric types support this conversion as well + Assert.Equal(char.MaxValue, CreateSaturating(double.PositiveInfinity)); + Assert.Equal(char.MaxValue, CreateSaturating(QuantityValue.PositiveInfinity)); + } + + [Fact] + public void CreateSaturating_BigInteger_FromNegativeInfinity_ShouldThrowOverflowException() + { + Assert.Throws(() => BigInteger.CreateSaturating(QuantityValue.NegativeInfinity)); + } + + [Fact] + public void CreateSaturating_FromNegativeInfinity_ShouldReturnMinValueOrNegativeInfinity() + { + Assert.Equal(double.NegativeInfinity, double.CreateSaturating(QuantityValue.NegativeInfinity)); + Assert.Equal(new Complex(double.NegativeInfinity, 0), Complex.CreateSaturating(QuantityValue.NegativeInfinity)); + Assert.Equal(decimal.MinValue, decimal.CreateSaturating(QuantityValue.NegativeInfinity)); + Assert.Equal(float.NegativeInfinity, float.CreateSaturating(QuantityValue.NegativeInfinity)); + Assert.Equal(Half.NegativeInfinity, Half.CreateSaturating(QuantityValue.NegativeInfinity)); + Assert.Equal(Int128.MinValue, Int128.CreateSaturating(QuantityValue.NegativeInfinity)); + Assert.Equal(UInt128.MinValue, UInt128.CreateSaturating(QuantityValue.NegativeInfinity)); + Assert.Equal(long.MinValue, long.CreateSaturating(QuantityValue.NegativeInfinity)); + Assert.Equal(ulong.MinValue, ulong.CreateSaturating(QuantityValue.NegativeInfinity)); + Assert.Equal(int.MinValue, int.CreateSaturating(QuantityValue.NegativeInfinity)); + Assert.Equal(uint.MinValue, uint.CreateSaturating(QuantityValue.NegativeInfinity)); + Assert.Equal(nint.MinValue, nint.CreateSaturating(QuantityValue.NegativeInfinity)); + Assert.Equal(UIntPtr.MinValue, UIntPtr.CreateSaturating(QuantityValue.NegativeInfinity)); + Assert.Equal(short.MinValue, short.CreateSaturating(QuantityValue.NegativeInfinity)); + Assert.Equal(ushort.MinValue, ushort.CreateSaturating(QuantityValue.NegativeInfinity)); + Assert.Equal(byte.MinValue, byte.CreateSaturating(QuantityValue.NegativeInfinity)); + Assert.Equal(sbyte.MinValue, sbyte.CreateSaturating(QuantityValue.NegativeInfinity)); + // although there isn't any char.CreateSaturating(..) method, all numeric types support this conversion as well + Assert.Equal(char.MinValue, CreateSaturating(double.NegativeInfinity)); + Assert.Equal(char.MinValue, CreateSaturating(QuantityValue.NegativeInfinity)); + } + + [Fact] + public void CreateSaturating_WithUnsupportedType_ThrowsNotSupportedException() + { + Assert.Throws(() => CreateSaturating(QuantityValue.One)); + } + } + + public class ConvertToTruncatingTests + { + private static TNumber CreateTruncating(TOther value) + where TNumber : INumberBase + where TOther : INumberBase + { + return TNumber.CreateTruncating(value); + } + + [Fact] + public void CreateTruncating_FromFinitePositiveValue_ShouldReturnTheExpectedValue() + { + var quantityValue = new QuantityValue(3, 2); + Assert.Equal(1.5, double.CreateTruncating(quantityValue)); + Assert.Equal(new Complex(1.5, 0), Complex.CreateTruncating(quantityValue)); + Assert.Equal(1.5m, decimal.CreateTruncating(quantityValue)); + Assert.Equal(1.5f, float.CreateTruncating(quantityValue)); + Assert.Equal((Half)1.5, Half.CreateTruncating(quantityValue)); + Assert.Equal(1, BigInteger.CreateTruncating(quantityValue)); + Assert.Equal(1, Int128.CreateTruncating(quantityValue)); + Assert.Equal(1u, UInt128.CreateTruncating(quantityValue)); + Assert.Equal(1, long.CreateTruncating(quantityValue)); + Assert.Equal((ulong)1, ulong.CreateTruncating(quantityValue)); + Assert.Equal(1, int.CreateTruncating(quantityValue)); + Assert.Equal((uint)1, uint.CreateTruncating(quantityValue)); + Assert.Equal(1, nint.CreateTruncating(quantityValue)); + Assert.Equal((UIntPtr)1, UIntPtr.CreateTruncating(quantityValue)); + Assert.Equal((short)1, short.CreateTruncating(quantityValue)); + Assert.Equal((ushort)1, ushort.CreateTruncating(quantityValue)); + Assert.Equal((byte)1, byte.CreateTruncating(quantityValue)); + Assert.Equal((sbyte)1, sbyte.CreateTruncating(quantityValue)); + // although there isn't any char.CreateTruncating(..) method, all numeric types support this conversion as well + Assert.Equal('a', CreateTruncating(97.9)); + Assert.Equal('a', CreateTruncating(new QuantityValue(979, 10))); + } + + [Fact] + public void CreateTruncating_FromFiniteNegativeValue_ShouldReturnTheExpectedValue() + { + var fraction = new QuantityValue(-3, 2); + Assert.Equal(-1.5, double.CreateTruncating(fraction)); + Assert.Equal(new Complex(-1.5, 0), Complex.CreateTruncating(fraction)); + Assert.Equal(-1.5m, decimal.CreateTruncating(fraction)); + Assert.Equal(-1.5f, float.CreateTruncating(fraction)); + Assert.Equal((Half)(-1.5), Half.CreateTruncating(fraction)); + Assert.Equal(-1, BigInteger.CreateTruncating(fraction)); + Assert.Equal(-1, Int128.CreateTruncating(fraction)); + Assert.Equal(new UInt128(18446744073709551615, 18446744073709551615), UInt128.CreateTruncating(fraction)); + Assert.Equal(-1, long.CreateTruncating(fraction)); + Assert.Equal(ulong.MaxValue, ulong.CreateTruncating(fraction)); + Assert.Equal(-1, int.CreateTruncating(fraction)); + Assert.Equal(uint.MaxValue, uint.CreateTruncating(fraction)); + Assert.Equal(-1, nint.CreateTruncating(fraction)); + Assert.Equal(new UIntPtr(18446744073709551615), UIntPtr.CreateTruncating(fraction)); + Assert.Equal((short)-1, short.CreateTruncating(fraction)); + Assert.Equal(ushort.MaxValue, ushort.CreateTruncating(fraction)); + Assert.Equal(byte.MaxValue, byte.CreateTruncating(fraction)); + Assert.Equal((sbyte)-1, sbyte.CreateTruncating(fraction)); + // although there isn't any char.CreateTruncating(..) method, all numeric types support this conversion as well + // note: for some reason the floating point types don't care implement an independent truncating method, instead they return the saturated result + Assert.Equal(char.MinValue, CreateTruncating(-1.5)); + Assert.Equal(char.MaxValue, CreateTruncating(-1)); + Assert.Equal(char.MaxValue, CreateTruncating(fraction)); + } + + [Fact] + public void CreateTruncating_FromNaN_ShouldReturnZeroOrNaN() + { + Assert.Equal(double.NaN, double.CreateTruncating(QuantityValue.NaN)); + Assert.Equal(new Complex(double.NaN, 0), Complex.CreateTruncating(QuantityValue.NaN)); + Assert.Equal(decimal.Zero, decimal.CreateTruncating(QuantityValue.NaN)); + Assert.Equal(float.NaN, float.CreateTruncating(QuantityValue.NaN)); + Assert.Equal(Half.NaN, Half.CreateTruncating(QuantityValue.NaN)); + Assert.Equal(BigInteger.Zero, BigInteger.CreateTruncating(QuantityValue.NaN)); + Assert.Equal(Int128.Zero, Int128.CreateTruncating(QuantityValue.NaN)); + Assert.Equal(UInt128.Zero, UInt128.CreateTruncating(QuantityValue.NaN)); + Assert.Equal(0, long.CreateTruncating(QuantityValue.NaN)); + Assert.Equal(0UL, ulong.CreateTruncating(QuantityValue.NaN)); + Assert.Equal(0, int.CreateTruncating(QuantityValue.NaN)); + Assert.Equal(0U, uint.CreateTruncating(QuantityValue.NaN)); + Assert.Equal(nint.Zero, nint.CreateTruncating(QuantityValue.NaN)); + Assert.Equal(UIntPtr.Zero, UIntPtr.CreateTruncating(QuantityValue.NaN)); + Assert.Equal(default, short.CreateTruncating(QuantityValue.NaN)); + Assert.Equal(default, ushort.CreateTruncating(QuantityValue.NaN)); + Assert.Equal(default, byte.CreateTruncating(QuantityValue.NaN)); + Assert.Equal(default, sbyte.CreateTruncating(QuantityValue.NaN)); + // although there isn't any char.CreateTruncating(..) method, all numeric types support this conversion as well + Assert.Equal('\0', CreateTruncating(double.NaN)); + Assert.Equal('\0', CreateTruncating(QuantityValue.NaN)); + } + + [Fact] + public void CreateTruncating_BigInteger_FromPositiveInfinity_ShouldThrowOverflowException() + { + Assert.Throws(() => BigInteger.CreateTruncating(QuantityValue.PositiveInfinity)); + } + + [Fact] + public void CreateTruncating_FromPositiveInfinity_ShouldReturnMaxValueOrPositiveInfinity() + { + Assert.Equal(double.PositiveInfinity, double.CreateTruncating(QuantityValue.PositiveInfinity)); + Assert.Equal(new Complex(double.PositiveInfinity, 0), Complex.CreateTruncating(QuantityValue.PositiveInfinity)); + Assert.Equal(decimal.MaxValue, decimal.CreateTruncating(QuantityValue.PositiveInfinity)); + Assert.Equal(float.PositiveInfinity, float.CreateTruncating(QuantityValue.PositiveInfinity)); + Assert.Equal(Half.PositiveInfinity, Half.CreateTruncating(QuantityValue.PositiveInfinity)); + Assert.Equal(Int128.MaxValue, Int128.CreateTruncating(QuantityValue.PositiveInfinity)); + Assert.Equal(UInt128.MaxValue, UInt128.CreateTruncating(QuantityValue.PositiveInfinity)); + Assert.Equal(long.MaxValue, long.CreateTruncating(QuantityValue.PositiveInfinity)); + Assert.Equal(ulong.MaxValue, ulong.CreateTruncating(QuantityValue.PositiveInfinity)); + Assert.Equal(int.MaxValue, int.CreateTruncating(QuantityValue.PositiveInfinity)); + Assert.Equal(uint.MaxValue, uint.CreateTruncating(QuantityValue.PositiveInfinity)); + Assert.Equal(nint.MaxValue, nint.CreateTruncating(QuantityValue.PositiveInfinity)); + Assert.Equal(UIntPtr.MaxValue, UIntPtr.CreateTruncating(QuantityValue.PositiveInfinity)); + Assert.Equal(short.MaxValue, short.CreateTruncating(QuantityValue.PositiveInfinity)); + Assert.Equal(ushort.MaxValue, ushort.CreateTruncating(QuantityValue.PositiveInfinity)); + Assert.Equal(byte.MaxValue, byte.CreateTruncating(QuantityValue.PositiveInfinity)); + Assert.Equal(sbyte.MaxValue, sbyte.CreateTruncating(QuantityValue.PositiveInfinity)); + // although there isn't any char.CreateTruncating(..) method, all numeric types support this conversion as well + Assert.Equal(char.MaxValue, CreateTruncating(double.PositiveInfinity)); + Assert.Equal(char.MaxValue, CreateTruncating(QuantityValue.PositiveInfinity)); + } + + [Fact] + public void CreateTruncating_FromNegativeInfinity_BigInteger_ShouldThrowOverflowException() + { + Assert.Throws(() => BigInteger.CreateTruncating(QuantityValue.NegativeInfinity)); + } + + [Fact] + public void CreateTruncating_FromNegativeInfinity_ShouldReturnMinValueOrNegativeInfinity() + { + Assert.Equal(double.NegativeInfinity, double.CreateTruncating(QuantityValue.NegativeInfinity)); + Assert.Equal(new Complex(double.NegativeInfinity, 0), Complex.CreateTruncating(QuantityValue.NegativeInfinity)); + Assert.Equal(decimal.MinValue, decimal.CreateTruncating(QuantityValue.NegativeInfinity)); + Assert.Equal(float.NegativeInfinity, float.CreateTruncating(QuantityValue.NegativeInfinity)); + Assert.Equal(Half.NegativeInfinity, Half.CreateTruncating(QuantityValue.NegativeInfinity)); + Assert.Equal(Int128.MinValue, Int128.CreateTruncating(QuantityValue.NegativeInfinity)); + Assert.Equal(UInt128.MinValue, UInt128.CreateTruncating(QuantityValue.NegativeInfinity)); + Assert.Equal(long.MinValue, long.CreateTruncating(QuantityValue.NegativeInfinity)); + Assert.Equal(ulong.MinValue, ulong.CreateTruncating(QuantityValue.NegativeInfinity)); + Assert.Equal(int.MinValue, int.CreateTruncating(QuantityValue.NegativeInfinity)); + Assert.Equal(uint.MinValue, uint.CreateTruncating(QuantityValue.NegativeInfinity)); + Assert.Equal(nint.MinValue, nint.CreateTruncating(QuantityValue.NegativeInfinity)); + Assert.Equal(UIntPtr.MinValue, UIntPtr.CreateTruncating(QuantityValue.NegativeInfinity)); + Assert.Equal(short.MinValue, short.CreateTruncating(QuantityValue.NegativeInfinity)); + Assert.Equal(ushort.MinValue, ushort.CreateTruncating(QuantityValue.NegativeInfinity)); + Assert.Equal(byte.MinValue, byte.CreateTruncating(QuantityValue.NegativeInfinity)); + Assert.Equal(sbyte.MinValue, sbyte.CreateTruncating(QuantityValue.NegativeInfinity)); + // although there isn't any char.CreateTruncating(..) method, all numeric types support this conversion as well + Assert.Equal(char.MinValue, CreateTruncating(double.NegativeInfinity)); + Assert.Equal(char.MinValue, CreateTruncating(QuantityValue.NegativeInfinity)); + } + + [Fact] + public void CreateTruncating_WithUnsupportedType_ThrowsNotSupportedException() + { + Assert.Throws(() => CreateTruncating(QuantityValue.One)); + } + } +#endif + } +} diff --git a/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ConvertToString.cs b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ConvertToString.cs new file mode 100644 index 0000000000..238fe023d8 --- /dev/null +++ b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.ConvertToString.cs @@ -0,0 +1,1516 @@ +using System.Globalization; +using System.Linq; +using System.Numerics; +using Xunit.Abstractions; + +namespace UnitsNet.Tests; + +public partial class QuantityValueTests +{ + public class ConvertToStringTests + { + internal static readonly QuantityValueData[] TerminatingFractions = + [ + 0, 1, -1, 10, -10, 100, -100, 1000, -1000, 10000, -10000, 100000, -100000, + 0.1m, -0.1m, 0.2m, -0.2m, 0.5m, -0.5m, 1.2m, -1.2m, 1.5m, -1.5m, 1.95m, -1.95m, 2.5m, -2.5m, + 2.001234m, -2.001234m, // rounds to 2 + 0.000015545665434654m, -0.000015545665434654m, + 0.00015545665434654m, -0.00015545665434654m, + 0.0015545665434654m, -0.0015545665434654m, + 0.015545665434654m, -0.015545665434654m, + 0.15545665434654m, -0.15545665434654m, + 1.5545665434654m, -1.5545665434654m, + 15.545665434654m, -15.545665434654m, + 155.45665434654m, -155.45665434654m, + 1554.5665434654m, -1554.5665434654m, + 15545.665434654m, -15545.665434654m, + 155456.65434654m, -155456.65434654m, + 1554566.5434654m, -1554566.5434654m, + new QuantityValue(10, 20), new QuantityValue(-10, 20), + // 128 in binary is 10000000, so its bit length is 8. 1400 is between 2^10 (1024) and 2^11 (2048), so its bit length is 11. + new QuantityValue(128, 1400), new QuantityValue(-128, 1400), + ]; + + internal static readonly QuantityValueData[] NonTerminatingFractions = + [ + new QuantityValue(1, 3), new QuantityValue(-1, 3), + new QuantityValue(2, 3), new QuantityValue(-2, 3), + new QuantityValue(19999991, 3), + new QuantityValue(-19999991, 3), // note: for all but the percent (P) format we could be using two more digits ('99') + new QuantityValue(20000001, 3), + new QuantityValue(-20000001, 3), // note: for all but the percent (P) format we could be using two more digits ('00') + new QuantityValue(4, 3), new QuantityValue(-4, 3), + new QuantityValue(5, 3), new QuantityValue(-5, 3), + new QuantityValue(7, 3), new QuantityValue(-7, 3) + ]; + + /// + /// Represents a pair consisting of a and its associated format string. + /// + /// + /// This class is primarily used in unit tests to validate the behavior of + /// when formatted as a string using specific format strings. + /// It also implements to facilitate serialization and deserialization + /// of test data for xUnit test cases. + /// + public class ValueFormatPair : IXunitSerializable + { + private QuantityValueData _value; + + public ValueFormatPair(QuantityValueData value, string format) + { + _value = value; + Format = format; + } + + public QuantityValue Value + { + get => _value; + private set => _value = value; + } + + public string Format { get; private set; } + + public void Deconstruct(out QuantityValue value, out string format) + { + value = Value; + format = Format; + } + + public override string ToString() + { + var fraction = Value; + return $"{fraction.Numerator}/{fraction.Denominator} : {Format}"; + } + + #region Implementation of IXunitSerializable + + public ValueFormatPair() + { + _value = null!; + Format = null!; + } + + public void Serialize(IXunitSerializationInfo info) + { + info.AddValue("v1", _value); + info.AddValue("v2", Format); + } + + public void Deserialize(IXunitSerializationInfo info) + { + Value = info.GetValue("v1"); + Format = info.GetValue("v2"); + } + + #endregion + } + + /// + /// The general ("G") format specifier converts a number to the more compact of either fixed-point or scientific + /// notation, depending on the type of the number and whether a precision specifier is present. The precision specifier + /// defines the maximum number of significant digits that can appear in the result string. If the precision specifier + /// is omitted or zero, the type of the number determines the default precision. + /// + public class GeneralFormatTests + { + private static readonly string[] GeneralFormats = ["G1", "G2", "G3", "G4", "G5", "G6", "g1", "g6", "G27"]; + + [Theory] + [ClassData(typeof(TerminatingFractionCases))] + public void ToString_WithTerminatingFraction(ValueFormatPair testCase, string expected) + { + var (value, format) = testCase; + var result = value.ToString(format); + Assert.Equal(expected, result); + } + + [Theory] + [ClassData(typeof(NonTerminatingFractionCases))] + public void ToString_WithNonTerminatingFraction(ValueFormatPair testCase, string expected) + { + var (value, format) = testCase; + var result = value.ToString(format); + Assert.Equal(expected, result); + } + + [Fact] + public void ToString_WithoutFormatSpecifier() + { + var value = new QuantityValue(1, 3); +#if NET + Assert.Equal(value.ToString("G16", CultureInfo.CurrentCulture), value.ToString("G")); +#else + Assert.Equal(value.ToString("G15", CultureInfo.CurrentCulture), value.ToString("G")); +#endif + Assert.Equal(value.ToString("G", CultureInfo.CurrentCulture), value.ToString("G0", null)); + } + + #if NET + + [Fact] + public void TryFormat_Zero_WithValidSpanLength_ReturnsTrue() + { + QuantityValue value = 0; + var destination = new Span(new char[1]); + var result = value.TryFormat(destination, out var charsWritten, "G", CultureInfo.InvariantCulture); + Assert.True(result); + Assert.Equal(1, charsWritten); + Assert.Equal("0", destination[Range.EndAt(charsWritten)]); + } + + [Fact] + public void TryFormat_WithG0AndValidSpanLength_ReturnsTrue() + { + QuantityValue value = 123.456m; + var destination = new Span(new char[10]); + var result = value.TryFormat(destination, out var charsWritten, "G0", CultureInfo.InvariantCulture); + Assert.True(result); + Assert.Equal(7, charsWritten); + Assert.Equal("123.456", destination[Range.EndAt(charsWritten)]); + } + + [Fact] + public void TryFormat_WithValidSpanLength_ReturnsTrue() + { + QuantityValue value = 123.456m; + var destination = new Span(new char[10]); + var result = value.TryFormat(destination, out var charsWritten, "G", CultureInfo.InvariantCulture); + Assert.True(result); + Assert.Equal(7, charsWritten); + Assert.Equal("123.456", destination[Range.EndAt(charsWritten)]); + } + + [Theory] + [InlineData(123400, "G6", 5)] + [InlineData(123400, "G1", 0)] + [InlineData(123400, "G2", 0)] + [InlineData(123400, "G2", 1)] + [InlineData(123400, "G2", 3)] + [InlineData(123.456, "G2", 4)] + [InlineData(123.456, "G2", 5)] + [InlineData(0.000123, "G5", 5)] + public void TryFormat_WithInvalidSpanLength_ReturnsFalse(decimal decimalValue, string format, int testLength) + { + QuantityValue value = decimalValue; + var destination = new Span(new char[testLength]); + var result = value.TryFormat(destination, out var charsWritten, format, CultureInfo.InvariantCulture); + Assert.False(result); + // Assert.Equal(0, charsWritten); // TODO should we make sure that nothing was written? + } + + [Theory] + [InlineData(-1234, -10, "G1", 0)] + [InlineData(-1234, -10, "G2", 3)] + [InlineData(-1234, -10, "G2", 4)] + [InlineData(-1234, -10, "G2", 5)] + [InlineData(-1234, -10, "G20", 1)] + [InlineData(-1234, -10, "G20", 2)] + [InlineData(-1234, -10, "G20", 5)] + [InlineData(1, -1000, "G1", 2)] + public void TryFormat_FromPowerOfTen_WithInvalidSpanLength_ReturnsFalse(int number, int powerOfTen, string format, int testLength) + { + var value = QuantityValue.FromPowerOfTen(number, powerOfTen); + var destination = new Span(new char[testLength]); + var result = value.TryFormat(destination, out var charsWritten, format, CultureInfo.InvariantCulture); + Assert.False(result); + // Assert.Equal(0, charsWritten); // TODO should we make sure that nothing was written? + } + + #endif + + public sealed class TerminatingFractionCases : TheoryData + { + public TerminatingFractionCases() + { + foreach (var value in TerminatingFractions) + { + foreach (var format in GeneralFormats) + { + Add(new ValueFormatPair(value, format), value.Value.ToDecimal().ToString(format)); + } + } + } + } + + public sealed class NonTerminatingFractionCases : TheoryData + { + public NonTerminatingFractionCases() + { + foreach (var value in NonTerminatingFractions) + { + foreach (var format in GeneralFormats) + { + Add(new ValueFormatPair(value, format), value.Value.ToDecimal().ToString(format)); + } + } + } + } + } + + /// + /// The fixed-point ("F") format specifier converts a number to a string of the form "-ddd.ddd…" where each "d" + /// indicates a digit (0-9). The string starts with a minus sign if the number is negative. + /// The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the + /// current NumberFormatInfo.NumberDecimalDigits property supplies the numeric precision. + /// + public class FixedPointFormatTests + { + private static readonly string[] FixedPointFormats = ["F", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F27"]; + + [Theory] + [ClassData(typeof(TerminatingFractionCases))] + public void ToString_WithTerminatingFraction(ValueFormatPair testCase, string expected) + { + var (value, format) = testCase; + var result = value.ToString(format); + Assert.Equal(expected, result); + } + + public sealed class TerminatingFractionCases : TheoryData + { + public TerminatingFractionCases() + { + foreach (var value in TerminatingFractions) + { + foreach (var format in FixedPointFormats) + { + Add(new ValueFormatPair(value, format), value.Value.ToDecimal().ToString(format)); + } + } + } + } + + [Fact] + public void ToString_F250_ReturnsTheExpectedResult() + { + QuantityValue value = 4.2; + var expected = "4.2" + new string(Enumerable.Repeat('0', 249).ToArray()); + + var result = value.ToString("F250", CultureInfo.InvariantCulture); + + Assert.Equal(expected, result); + } + +#if NET + [Fact] + public void TryFormat_Zero_WithValidSpanLength_ReturnsTrue() + { + QuantityValue value = 0; + var destination = new Span(new char[4]); + var result = value.TryFormat(destination, out var charsWritten, "F2", CultureInfo.InvariantCulture); + Assert.True(result); + Assert.Equal(4, charsWritten); + Assert.Equal("0.00", destination[Range.EndAt(charsWritten)]); + } + + [Fact] + public void TryFormat_NegativeInteger_WithValidSpanLength_ReturnsTrue() + { + QuantityValue value = -42; + var destination = new Span(new char[6]); + var result = value.TryFormat(destination, out var charsWritten, "F2", CultureInfo.InvariantCulture); + Assert.True(result); + Assert.Equal(6, charsWritten); + Assert.Equal("-42.00", destination[Range.EndAt(charsWritten)]); + } + + [Fact] + public void TryFormat_NegativeDecimal_WithValidSpanLength_ReturnsTrue() + { + QuantityValue value = -4.2; + var destination = new Span(new char[5]); + var result = value.TryFormat(destination, out var charsWritten, "F2", CultureInfo.InvariantCulture); + Assert.True(result); + Assert.Equal(5, charsWritten); + Assert.Equal("-4.20", destination[Range.EndAt(charsWritten)]); + } + + [Theory] + [InlineData(-123.4, "F1", 0)] + [InlineData(-123.4, "F1", 4)] + [InlineData(-123.4, "F1", 5)] + [InlineData(-123.4, "F20", 3)] + [InlineData(-123.4, "F20", 4)] + [InlineData(-123.4, "F20", 5)] + public void TryFormat_Decimal_WithInvalidSpanLength_ReturnsFalse(decimal decimalValue, string format, int testLength) + { + QuantityValue value = decimalValue; + var destination = new Span(new char[testLength]); + var result = value.TryFormat(destination, out var charsWritten, format, CultureInfo.InvariantCulture); + Assert.False(result); + // Assert.Equal(0, charsWritten); // TODO should we make sure that nothing was written? + } + + [Fact] + public void TryFormat_PreciseDecimal_WithInvalidSpanLength_ReturnsFalse() + { + // 1e-20: should return 22 characters: "0.000..1" + var value = QuantityValue.FromPowerOfTen(1, 1, -20); + var destination = new Span(new char[21]); + var result = value.TryFormat(destination, out var charsWritten, "F20", CultureInfo.InvariantCulture); + Assert.False(result); + // Assert.Equal(0, charsWritten); // TODO should we make sure that nothing was written? + + } +#endif + } + + /// + /// The numeric ("N") format specifier converts a number to a string of the form "-d,ddd,ddd.ddd…", where "-" indicates + /// a negative number symbol if required, "d" indicates a digit (0-9), "," indicates a group separator, and "." + /// indicates a decimal point symbol. The precision specifier indicates the desired number of digits after the decimal + /// point. If the precision specifier is omitted, the number of decimal places is defined by the current + /// NumberFormatInfo.NumberDecimalDigits property. + /// + public class NumericFormatTests + { + private static readonly string[] NumberFormats = ["N", "N0", "N1", "N2", "N3", "N4", "N5", "N6"]; + + private static readonly int[] NumberNegativePatterns = + [ + 0, // (n) + 1, // -n + 2, // - n + 3, // n- + 4 // n - + ]; + + [Fact] + public void NumberFormat_WithInvalidNumberNegativePatterns_ThrowsArgumentOutOfRangeException() + { + var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone(); + var numberFormat = formatProvider.NumberFormat; + Assert.Throws(() => numberFormat.NumberNegativePattern = -1); + Assert.Throws(() => numberFormat.NumberNegativePattern = 5); + } + + [Fact] + public void NumberFormat_WithInvalidNumberDecimalDigits_ThrowsArgumentOutOfRangeException() + { + var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone(); + var numberFormat = formatProvider.NumberFormat; + Assert.Throws(() => numberFormat.NumberDecimalDigits = -1); + Assert.Throws(() => numberFormat.NumberDecimalDigits = 100); + } + + [Theory] + [ClassData(typeof(TerminatingFractionCases))] + public void ToString_WithTerminatingFraction(ValueFormatPair testCase, string expected) + { + var (value, format) = testCase; + var result = value.ToString(format); + Assert.Equal(expected, result); + } + + [Theory] + [ClassData(typeof(NonTerminatingFractionCases))] + public void ToString_WithNonTerminatingFraction(ValueFormatPair testCase, string expected) + { + var (value, format) = testCase; + var result = value.ToString(format); + Assert.Equal(expected, result); + } + + [Theory] + [ClassData(typeof(NegativePatternCases))] + public void ToString_WithCustomNegativePattern(ValueFormatPair testCase, int pattern, string expected) + { + // Arrange + var (value, format) = testCase; + var formatProvider = (CultureInfo)CultureInfo.CurrentCulture.Clone(); + formatProvider.NumberFormat.NumberNegativePattern = pattern; + // Act + var result = value.ToString(format, formatProvider); + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void ToString_N250_ReturnsTheExpectedResult() + { + // Arrange + QuantityValue value = 4.2; + var expected = "4.2" + new string(Enumerable.Repeat('0', 249).ToArray()); + // Act + var result = value.ToString("N250", CultureInfo.InvariantCulture); + // Assert + Assert.Equal(expected, result); + } + +#if NET + [Fact] + public void TryFormat_Zero_WithValidSpanLength_ReturnsTrue() + { + // Arrange + QuantityValue value = 0; + var destination = new Span(new char[4]); + // Act + var result = value.TryFormat(destination, out var charsWritten, "N", CultureInfo.InvariantCulture); + // Assert + Assert.True(result); + Assert.Equal(4, charsWritten); + Assert.Equal("0.00", destination[Range.EndAt(charsWritten)]); + } + + [Fact] + public void TryFormat_NegativeInteger_WithValidSpanLength_ReturnsTrue() + { + // Arrange + QuantityValue value = -4200; + var destination = new Span(new char[9]); + // Act + var result = value.TryFormat(destination, out var charsWritten, "N", CultureInfo.InvariantCulture); + // Assert + Assert.True(result); + Assert.Equal(9, charsWritten); + Assert.Equal("-4,200.00", destination[Range.EndAt(charsWritten)]); + } + + [Fact] + public void TryFormat_NegativeDecimal_WithValidSpanLength_ReturnsTrue() + { + // Arrange + QuantityValue value = -4.2; + var destination = new Span(new char[5]); + // Act + var result = value.TryFormat(destination, out var charsWritten, "N", CultureInfo.InvariantCulture); + // Assert + Assert.True(result); + Assert.Equal(5, charsWritten); + Assert.Equal("-4.20", destination[Range.EndAt(charsWritten)]); + } + + [Theory] + [InlineData(-0.1, "N1", 0, 0)] // (n) + [InlineData(-0.1, "N1", 0, 1)] // (n) + [InlineData(-0.1, "N1", 0, 4)] // (n) + [InlineData(-0.1, "N1", 1, 0)] // -n + [InlineData(-0.1, "N1", 2, 0)] // - n + [InlineData(-0.1, "N1", 2, 1)] // - n + [InlineData(-0.1, "N1", 3, 3)] // n- + [InlineData(-0.1, "N1", 4, 3)] // n - + [InlineData(-0.1, "N1", 4, 4)] // n - + public void TryFormat_NegativeNumber_WithInvalidSpanLength_ReturnsFalse(decimal decimalValue, string format, int pattern, int testLength) + { + // Arrange + var formatProvider = (CultureInfo)CultureInfo.CurrentCulture.Clone(); + formatProvider.NumberFormat.NumberNegativePattern = pattern; + QuantityValue value = decimalValue; + var destination = new Span(new char[testLength]); + // Act + var result = value.TryFormat(destination, out var charsWritten, format, formatProvider); + // Assert + Assert.False(result); + // Assert.Equal(0, charsWritten); // TODO should we make sure that nothing was written? + } +#endif + + public sealed class TerminatingFractionCases : TheoryData + { + public TerminatingFractionCases() + { + foreach (var value in TerminatingFractions) + { + foreach (var format in NumberFormats) + { + Add(new ValueFormatPair(value, format), value.Value.ToDecimal().ToString(format)); + } + } + } + } + + public sealed class NonTerminatingFractionCases : TheoryData + { + public NonTerminatingFractionCases() + { + foreach (var value in NonTerminatingFractions) + { + foreach (var format in NumberFormats) + { + Add(new ValueFormatPair(value, format), value.Value.ToDecimal().ToString(format)); + } + } + } + } + + public sealed class NegativePatternCases : TheoryData + { + public NegativePatternCases() + { + QuantityValue[] valuesToTest = [1, 0, -0.1m, -1, -1.23456789m]; + foreach (var pattern in NumberNegativePatterns) + { + var formatProvider = (CultureInfo)CultureInfo.CurrentCulture.Clone(); + formatProvider.NumberFormat.NumberNegativePattern = pattern; + foreach (var format in NumberFormats) + { + foreach (var value in valuesToTest) + { + Add(new ValueFormatPair(value, format), pattern, value.ToDecimal().ToString(format, formatProvider)); + } + } + } + } + } + } + + /// + /// Exponential format specifier (E) + /// The exponential ("E") format specifier converts a number to a string of the form "-d.ddd…E+ddd" or "-d.ddd…e+ddd", + /// where each "d" indicates a digit (0-9). The string starts with a minus sign if the number is negative. Exactly one + /// digit always precedes the decimal point. + /// The precision specifier indicates the desired number of digits after the decimal point. If the precision specifier + /// is omitted, a default of six digits after the decimal point is used. + /// The case of the format specifier indicates whether to prefix the exponent with an "E" or an "e". The exponent + /// always consists of a plus or minus sign and a minimum of three digits. The exponent is padded with zeros to meet + /// this minimum, if required. + /// + public class ExponentialFormatTests + { + private static readonly string[] ScientificFormats = ["E", "E0", "E1", "E2", "E3", "E4", "E5", "E6", "e1", "e6"]; + + [Theory] + [ClassData(typeof(TerminatingFractionCases))] + public void ToString_WithTerminatingFraction(ValueFormatPair testCase, string expected) + { + var (value, format) = testCase; + var result = value.ToString(format); + Assert.Equal(expected, result); + } + + public sealed class TerminatingFractionCases : TheoryData + { + public TerminatingFractionCases() + { + foreach (var value in TerminatingFractions) + { + foreach (var format in ScientificFormats) + { + Add(new ValueFormatPair(value, format), value.Value.ToDecimal().ToString(format)); + } + } + } + } + +#if NET + [Fact] + public void TryFormat_Zero_WithValidSpanLength_ReturnsTrue() + { + QuantityValue value = 0; + var destination = new Span(new char[13]); + var result = value.TryFormat(destination, out var charsWritten, "E", CultureInfo.InvariantCulture); + Assert.True(result); + Assert.Equal(13, charsWritten); + Assert.Equal("0.000000E+000", destination[Range.EndAt(charsWritten)]); + } + + [Fact] + public void TryFormat_NegativeNumber_WithValidSpanLength_ReturnsTrue() + { + QuantityValue value = -42; + var destination = new Span(new char[14]); + var result = value.TryFormat(destination, out var charsWritten, "E", CultureInfo.InvariantCulture); + Assert.True(result); + Assert.Equal(14, charsWritten); + Assert.Equal("-4.200000E+001", destination[Range.EndAt(charsWritten)]); + } + + [Fact] + public void TryFormat_SmallNegativeNumber_WithValidSpanLength_ReturnsTrue() + { + QuantityValue value = -0.00042; + var destination = new Span(new char[14]); + var result = value.TryFormat(destination, out var charsWritten, "E", CultureInfo.InvariantCulture); + Assert.True(result); + Assert.Equal(14, charsWritten); + Assert.Equal("-4.200000E-004", destination[Range.EndAt(charsWritten)]); + } + + [Theory] + [InlineData(-1.5, "E0", 0)] + [InlineData(1.5, "E0", 0)] + [InlineData(123.456, "E2", 3)] // 1.2[3E+002] + [InlineData(123.456, "E2", 4)] // 1.23[E+002] + [InlineData(123.456, "E2", 5)] // 1.23E[+002] + [InlineData(123.456, "E2", 8)] // 1.23E+00[2] + public void TryFormat_WithInvalidSpanLength_ReturnsFalse(decimal decimalValue, string format, int testLength) + { + QuantityValue value= decimalValue; + var destination = new Span(new char[testLength]); + var result = value.TryFormat(destination, out var charsWritten, format, CultureInfo.InvariantCulture); + Assert.False(result); + // Assert.Equal(0, charsWritten); // TODO should we make sure that nothing was written? + } +#endif + } + + /// + /// The "C" (or currency) format specifier converts a number to a string that represents a currency amount. The + /// precision specifier indicates the desired number of decimal places in the result string. If the precision specifier + /// is omitted, the default precision is defined by the NumberFormatInfo.CurrencyDecimalDigits property. + /// If the value to be formatted has more than the specified or default number of decimal places, the fractional value + /// is rounded in the result string. If the value to the right of the number of specified decimal places is 5 or + /// greater, the last digit in the result string is rounded away from zero. + /// + public class CurrencyFormatTests + { + private static readonly string[] CurrencyFormats = ["C", "C0", "C1", "C2", "C3", "C4", "C5", "C6"]; + + public static readonly int[] CurrencyPositivePatterns = + [ + 00, // $n + 01, // n$ + 02, // $ n + 03 // n $ + ]; + + public static readonly int[] CurrencyNegativePatterns = + [ + 00, // ($n) + 01, // -$n + 02, // $-n + 03, // $n- + 04, // (n$) + 05, // -n$ + 06, // n-$ + 07, // n$- + 08, // -n $ + 09, // -$ n + 10, // n $- + 11, // $ n- + 12, // $ -n + 13, // n- $ + 14, // ($ n) + 15, // (n $) +#if NET + 16, // $- n +#endif + ]; + + [Fact] + public void CurrencyPositivePattern_WithInvalidValue_ThrowsArgumentOutOfRangeException() + { + var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone(); + var numberFormat = formatProvider.NumberFormat; + Assert.Throws(() => numberFormat.CurrencyPositivePattern = -1); + Assert.Throws(() => numberFormat.CurrencyPositivePattern = 4); + } + + [Fact] + public void CurrencyNegativePattern_WithInvalidValue_ThrowsArgumentOutOfRangeException() + { + var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone(); + var numberFormat = formatProvider.NumberFormat; + Assert.Throws(() => numberFormat.CurrencyNegativePattern = -1); +#if NET + Assert.Throws(() => numberFormat.CurrencyNegativePattern = 17); +#else + Assert.Throws(() => numberFormat.CurrencyNegativePattern = 16); +#endif + } + + [Theory] + [ClassData(typeof(TerminatingFractionCases))] + public void ToString_WithTerminatingFraction(ValueFormatPair testCase, string expected) + { + var (value, format) = testCase; + var result = value.ToString(format); + Assert.Equal(expected, result); + } + + [Fact] + public void ToString_C250_ReturnsTheExpectedResult() + { + QuantityValue value = 4.2; + var expected = "$4.2" + new string(Enumerable.Repeat('0', 249).ToArray()); + + var result = value.ToString("C250", CultureInfo.GetCultureInfo("en-US")); + + Assert.Equal(expected, result); + } + +#if NET + [Fact] + public void TryFormat_Zero_WithValidSpanLength_ReturnsTrue() + { + QuantityValue value = 0; + var destination = new Span(new char[5]); + var result = value.TryFormat(destination, out var charsWritten, "C", CultureInfo.GetCultureInfo("en-US")); + Assert.True(result); + Assert.Equal(5, charsWritten); + Assert.Equal("$0.00", destination[Range.EndAt(charsWritten)]); + } + + [Fact] + public void TryFormat_NegativeInteger_WithValidSpanLength_ReturnsTrue() + { + QuantityValue value = -42; + var destination = new Span(new char[7]); + var result = value.TryFormat(destination, out var charsWritten, "C", CultureInfo.GetCultureInfo("en-US")); + Assert.True(result); + Assert.Equal(7, charsWritten); + Assert.Equal("-$42.00", destination[Range.EndAt(charsWritten)]); + } + + [Fact] + public void TryFormat_NegativeDecimal_WithValidSpanLength_ReturnsTrue() + { + QuantityValue value = -4.2; + var destination = new Span(new char[6]); + var result = value.TryFormat(destination, out var charsWritten, "C", CultureInfo.GetCultureInfo("en-US")); + Assert.True(result); + Assert.Equal(6, charsWritten); + Assert.Equal("-$4.20", destination[Range.EndAt(charsWritten)]); + } + + [Theory] + [InlineData(0.1, "C1", 0, 0)] // $n + [InlineData(0.1, "C1", 0, 3)] // $n + [InlineData(0.1, "C1", 1, 3)] // n$ + [InlineData(0.1, "C1", 2, 1)] // $ n + [InlineData(0.1, "C1", 3, 4)] // n $ + // [InlineData(0.1, "C0", 2, 1)] // $ n + // [InlineData(0.1, "C1", 3, 0)] // n $ + // [InlineData(0.1, "C1", 3, 1)] // n $ + public void TryFormat_PositiveNumber_WithInvalidSpanLength_ReturnsFalse(decimal decimalValue, string format, int pattern, int testLength) + { + // Arrange + var formatProvider = (CultureInfo)CultureInfo.GetCultureInfo("en-US").Clone(); + formatProvider.NumberFormat.CurrencyPositivePattern = pattern; + QuantityValue value = decimalValue; + var destination = new Span(new char[testLength]); + // Act + var result = value.TryFormat(destination, out var charsWritten, format, formatProvider); + // Assert + Assert.False(result); + // Assert.Equal(0, charsWritten); // TODO should we make sure that nothing was written? + } + + [Theory] + [InlineData(-0.1, "C1", 0, 3)] // ($n) + [InlineData(-0.1, "C1", 0, 4)] // ($n) + [InlineData(-0.1, "C1", 0, 5)] // ($n) + [InlineData(-0.1, "C1", 1, 2)] // -$n + [InlineData(-0.1, "C1", 2, 2)] // $-n + [InlineData(-0.1, "C1", 3, 2)] // $n- + [InlineData(-0.1, "C1", 3, 4)] // $n- + [InlineData(-0.1, "C1", 4, 3)] // (n$) + [InlineData(-0.1, "C1", 4, 5)] // (n$) + [InlineData(-0.1, "C1", 5, 2)] // -n$ + [InlineData(-0.1, "C1", 5, 4)] // -n$ + [InlineData(-0.1, "C1", 6, 4)] // n-$ + [InlineData(-0.1, "C1", 7, 4)] // n$- + [InlineData(-0.1, "C1", 8, 3)] // -n $ + [InlineData(-0.1, "C1", 8, 5)] // -n $ + [InlineData(-0.1, "C1", 9, 3)] // -$ n + [InlineData(-0.1, "C1", 10, 5)] // n $- + [InlineData(-0.1, "C1", 11, 3)] // $ n- + [InlineData(-0.1, "C1", 11, 5)] // $ n- + [InlineData(-0.1, "C1", 12, 3)] // $ -n + [InlineData(-0.1, "C1", 13, 5)] // n- $ + [InlineData(-0.1, "C1", 14, 4)] // ($ n) + [InlineData(-0.1, "C1", 14, 6)] // ($ n) + [InlineData(-0.1, "C1", 15, 4)] // (n $) + [InlineData(-0.1, "C1", 15, 6)] // (n $) + [InlineData(-0.1, "C1", 16, 3)] // $- n + public void TryFormat_NegativeNumber_WithInvalidSpanLength_ReturnsFalse(decimal decimalValue, string format, int pattern, int testLength) + { + // Arrange + var formatProvider = (CultureInfo)CultureInfo.GetCultureInfo("en-US").Clone(); + formatProvider.NumberFormat.CurrencyNegativePattern = pattern; + QuantityValue value = decimalValue; + var destination = new Span(new char[testLength]); + // Act + var result = value.TryFormat(destination, out var charsWritten, format, formatProvider); + // Assert + Assert.False(result); + // Assert.Equal(0, charsWritten); // TODO should we make sure that nothing was written? + } +#endif + + [Theory] + [ClassData(typeof(NegativePatternCases))] + public void ToString_WithCustomNegativePattern(ValueFormatPair testCase, int pattern, string expected) + { + // Arrange + var (value, format) = testCase; + var formatProvider = (CultureInfo)CultureInfo.CurrentCulture.Clone(); + formatProvider.NumberFormat.CurrencyNegativePattern = pattern; + // Act + var result = value.ToString(format, formatProvider); + // Assert + Assert.Equal(expected, result); + } + + [Theory] + [ClassData(typeof(PositivePatternCases))] + public void ToString_WithCustomPositivePattern(ValueFormatPair testCase, int pattern, string expected) + { + // Arrange + var (value, format) = testCase; + var formatProvider = (CultureInfo)CultureInfo.CurrentCulture.Clone(); + formatProvider.NumberFormat.CurrencyPositivePattern = pattern; + // Act + var result = value.ToString(format, formatProvider); + // Assert + Assert.Equal(expected, result); + } + + public sealed class TerminatingFractionCases : TheoryData + { + public TerminatingFractionCases() + { + foreach (var value in TerminatingFractions) + { + foreach (var format in CurrencyFormats) + { + Add(new ValueFormatPair(value, format), value.Value.ToDecimal().ToString(format)); + } + } + } + } + + public sealed class NegativePatternCases : TheoryData + { + public NegativePatternCases() + { + QuantityValue[] valuesToTest = [1, 0, -0.1m, -1, -1.23456789m]; + foreach (var pattern in CurrencyNegativePatterns) + { + var formatProvider = (CultureInfo)CultureInfo.CurrentCulture.Clone(); + formatProvider.NumberFormat.CurrencyNegativePattern = pattern; + foreach (var format in CurrencyFormats) + { + foreach (var value in valuesToTest) + { + Add(new ValueFormatPair(value, format), pattern, value.ToDecimal().ToString(format, formatProvider)); + } + } + } + } + } + + public sealed class PositivePatternCases : TheoryData + { + public PositivePatternCases() + { + QuantityValue[] valuesToTest = [-1, 0, 0.1m, 1, 1.2345789m]; + foreach (var pattern in CurrencyPositivePatterns) + { + var formatProvider = (CultureInfo)CultureInfo.CurrentCulture.Clone(); + formatProvider.NumberFormat.CurrencyPositivePattern = pattern; + foreach (var format in CurrencyFormats) + { + foreach (var value in valuesToTest) + { + Add(new ValueFormatPair(value, format), pattern, value.ToDecimal().ToString(format, formatProvider)); + } + } + } + } + } + } + + /// + /// The percent ("P") format specifier multiplies a number by 100 and converts it to a string that represents a + /// percentage. The precision specifier indicates the desired number of decimal places. If the precision specifier is + /// omitted, the default numeric precision supplied by the current PercentDecimalDigits property is used. + /// + public class PercentageFormatTests + { + private static readonly string[] PercentFormats = ["P", "P0", "P1", "P2", "P3", "P4", "P5", "P6"]; + + public static readonly int[] PercentPositivePatterns = + [ + 00, // n % + 01, // n% + 02, // %n + 03 // % n + ]; + + public static readonly int[] PercentNegativePatterns = + [ + 00, // -n % + 01, // -n% + 02, // -%n + 03, // %-n + 04, // n- % + 05, // n-% + 06, // %n- + 07, // n %- + 08, // -% n + 09, // %- n + 10, // n %- + 11 // % n- + ]; + + [Fact] + public void PercentPositivePattern_WithInvalidValue_ThrowsArgumentOutOfRangeException() + { + var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone(); + var numberFormat = formatProvider.NumberFormat; + Assert.Throws(() => numberFormat.PercentPositivePattern = -1); + Assert.Throws(() => numberFormat.PercentPositivePattern = 4); + } + + [Fact] + public void PercentNegativePattern_WithInvalidValue_ThrowsArgumentOutOfRangeException() + { + var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone(); + var numberFormat = formatProvider.NumberFormat; + Assert.Throws(() => numberFormat.PercentNegativePattern = -1); + Assert.Throws(() => numberFormat.PercentNegativePattern = 12); + } + + [Theory] + [ClassData(typeof(TerminatingFractionCases))] + public void ToString_WithTerminatingFraction(ValueFormatPair testCase, string expected) + { + var (value, format) = testCase; + var result = value.ToString(format); + Assert.Equal(expected, result); + } + + [Theory] + [ClassData(typeof(NegativePatternCases))] + public void ToString_WithCustomNegativePattern(ValueFormatPair testCase, int pattern, string expected) + { + // Arrange + var (value, format) = testCase; + var formatProvider = (CultureInfo)CultureInfo.CurrentCulture.Clone(); + formatProvider.NumberFormat.PercentNegativePattern = pattern; + // Act + var result = value.ToString(format, formatProvider); + // Assert + Assert.Equal(expected, result); + } + + [Theory] + [ClassData(typeof(PositivePatternCases))] + public void ToString_WithCustomPositivePattern(ValueFormatPair testCase, int pattern, string expected) + { + // Arrange + var (value, format) = testCase; + var formatProvider = (CultureInfo)CultureInfo.CurrentCulture.Clone(); + formatProvider.NumberFormat.PercentPositivePattern = pattern; + // Act + var result = value.ToString(format, formatProvider); + // Assert + Assert.Equal(expected, result); + } + + [Fact] + public void ToString_P250_ReturnsTheExpectedResult() + { + QuantityValue value = 0.042; + var expected = "4.2" + new string(Enumerable.Repeat('0', 249).Append(' ').Append('%').ToArray()); + + var result = value.ToString("P250", CultureInfo.InvariantCulture); + + Assert.Equal(expected, result); + } + +#if NET + [Fact] + public void TryFormat_Zero_WithValidSpanLength_ReturnsTrue() + { + QuantityValue value = 0; + var destination = new Span(new char[6]); + var result = value.TryFormat(destination, out var charsWritten, "P", CultureInfo.InvariantCulture); + Assert.True(result); + Assert.Equal(6, charsWritten); + Assert.Equal("0.00 %", destination[Range.EndAt(charsWritten)]); + } + + [Fact] + public void TryFormat_NegativeInteger_WithValidSpanLength_ReturnsTrue() + { + QuantityValue value = -2; + var destination = new Span(new char[9]); + var result = value.TryFormat(destination, out var charsWritten, "P", CultureInfo.InvariantCulture); + Assert.True(result); + Assert.Equal(9, charsWritten); + Assert.Equal("-200.00 %", destination[Range.EndAt(charsWritten)]); + } + + [Fact] + public void TryFormat_NegativeDecimal_WithValidSpanLength_ReturnsTrue() + { + QuantityValue value = -0.042; + var destination = new Span(new char[7]); + var result = value.TryFormat(destination, out var charsWritten, "P", CultureInfo.InvariantCulture); + Assert.True(result); + Assert.Equal(7, charsWritten); + Assert.Equal("-4.20 %", destination[Range.EndAt(charsWritten)]); + } + + [Theory] + [InlineData(0.1, "P1", 0, 0)] // n % + [InlineData(0.1, "P1", 0, 4)] // n % + [InlineData(0.1, "P1", 0, 5)] // n % + [InlineData(0.1, "P0", 1, 2)] // n% + [InlineData(0.1, "P0", 2, 0)] // %n + [InlineData(0.1, "P0", 2, 1)] // %n + [InlineData(0.1, "P1", 3, 0)] // % n + [InlineData(0.1, "P1", 3, 1)] // % n + public void TryFormat_PositiveNumber_WithInvalidSpanLength_ReturnsFalse(decimal decimalValue, string format, int pattern, int testLength) + { + // Arrange + var formatProvider = (CultureInfo)CultureInfo.CurrentCulture.Clone(); + formatProvider.NumberFormat.PercentPositivePattern = pattern; + QuantityValue value = decimalValue; + var destination = new Span(new char[testLength]); + // Act + var result = value.TryFormat(destination, out var charsWritten, format, formatProvider); + // Assert + Assert.False(result); + // Assert.Equal(0, charsWritten); // TODO should we make sure that nothing was written? + } + + [Theory] + [InlineData(-0.1, "P1", 0, 0)] // -n % + [InlineData(-0.1, "P1", 0, 4)] // -n % + [InlineData(-0.1, "P1", 0, 5)] // -n % + [InlineData(-0.1, "P1", 0, 6)] // -n % + [InlineData(-0.1, "P1", 1, 0)] // -n% + [InlineData(-0.1, "P1", 1, 5)] // -n% + [InlineData(-0.1, "P0", 2, 0)] // -%n + [InlineData(-0.1, "P0", 2, 1)] // -%n + [InlineData(-0.1, "P0", 2, 3)] // -%n + [InlineData(-0.1, "P0", 3, 0)] // %-n + [InlineData(-0.1, "P0", 3, 1)] // %-n + [InlineData(-0.1, "P0", 4, 0)] // %n- + [InlineData(-0.1, "P0", 4, 3)] // %n- + [InlineData(-0.1, "P0", 5, 2)] // n-% + [InlineData(-0.1, "P0", 5, 3)] // n-% + [InlineData(-0.1, "P0", 6, 2)] // n%- + [InlineData(-0.1, "P0", 6, 3)] // n%- + [InlineData(-0.1, "P0", 7, 0)] // -% n + [InlineData(-0.1, "P0", 7, 1)] // -% n + [InlineData(-0.1, "P0", 7, 2)] // -% n + [InlineData(-0.1, "P0", 8, 4)] // n %- + [InlineData(-0.1, "P0", 9, 0)] // % n + [InlineData(-0.1, "P0", 9, 1)] // % n + [InlineData(-0.1, "P0", 9, 4)] // % n + [InlineData(-0.1, "P0", 10, 0)] // % -n + [InlineData(-0.1, "P0", 10, 1)] // % -n + [InlineData(-0.1, "P0", 10, 2)] // % -n + [InlineData(-0.1, "P0", 11, 2)] // n- % + [InlineData(-0.1, "P0", 11, 3)] // n- % + [InlineData(-0.1, "P0", 11, 4)] // n- % + public void TryFormat_NegativeNumber_WithInvalidSpanLength_ReturnsFalse(decimal decimalValue, string format, int pattern, int testLength) + { + // Arrange + var formatProvider = (CultureInfo)CultureInfo.CurrentCulture.Clone(); + formatProvider.NumberFormat.PercentNegativePattern = pattern; + QuantityValue value = decimalValue; + var destination = new Span(new char[testLength]); + // Act + var result = value.TryFormat(destination, out var charsWritten, format, formatProvider); + // Assert + Assert.False(result); + // Assert.Equal(0, charsWritten); // TODO should we make sure that nothing was written? + } +#endif + + public sealed class TerminatingFractionCases : TheoryData + { + public TerminatingFractionCases() + { + foreach (var value in TerminatingFractions) + { + foreach (var format in PercentFormats) + { + Add(new ValueFormatPair(value, format), value.Value.ToDecimal().ToString(format)); + // Add(new ValueFormatPair(value, format), value.Value.ToDouble().ToString(format)); + } + } + } + } + + public sealed class PositivePatternCases : TheoryData + { + public PositivePatternCases() + { + QuantityValue[] valuesToTest = [-1, 0, 0.1m, 1, 1.2345789m]; + foreach (var pattern in PercentPositivePatterns) + { + var formatProvider = (CultureInfo)CultureInfo.CurrentCulture.Clone(); + formatProvider.NumberFormat.PercentPositivePattern = pattern; + foreach (var format in PercentFormats) + { + foreach (var value in valuesToTest) + { + Add(new ValueFormatPair(value, format), pattern, value.ToDecimal().ToString(format, formatProvider)); + } + } + } + } + } + + public sealed class NegativePatternCases : TheoryData + { + public NegativePatternCases() + { + QuantityValue[] valuesToTest = [1, 0, -0.1m, -1, -1.23456789m]; + foreach (var pattern in PercentNegativePatterns) + { + var formatProvider = (CultureInfo)CultureInfo.CurrentCulture.Clone(); + formatProvider.NumberFormat.PercentNegativePattern = pattern; + foreach (var format in PercentFormats) + { + foreach (var value in valuesToTest) + { + Add(new ValueFormatPair(value, format), pattern, value.ToDecimal().ToString(format, formatProvider)); + } + } + } + } + } + } + + + /// + /// The significant digits after radix ("S") format specifier converts a number to a string that preserves the + /// precision of the Fraction object with a variable number of digits after the radix point. + /// + public class SignificantDigitsAfterTheRadixFormatTests + { + [Theory] + [ClassData(typeof(NormalValueCases))] + public void ToString_WithNormalValues(ValueFormatPair testCase, string expected) + { + var (value, format) = testCase; + var result = value.ToString(format, CultureInfo.InvariantCulture); + Assert.Equal(expected, result); + } + + [Theory] + [ClassData(typeof(SmallAbsoluteValueCases))] + public void ToString_WithSmallAbsoluteValue(ValueFormatPair testCase, string expected) + { + var (value, format) = testCase; + var result = value.ToString(format, CultureInfo.InvariantCulture); + Assert.Equal(expected, result); + } + + [Theory] + [ClassData(typeof(LargePositiveValueCases))] + public void ToString_WithLargePositiveValue(ValueFormatPair testCase, string expected) + { + var (value, format) = testCase; + var result = value.ToString(format, CultureInfo.InvariantCulture); + Assert.Equal(expected, result); + } + + [Theory] + [ClassData(typeof(LargeNegativeValueCases))] + public void ToString_LargeNegativeValue(ValueFormatPair testCase, string expected) + { + var (value, format) = testCase; + var result = value.ToString(format, CultureInfo.InvariantCulture); + Assert.Equal(expected, result); + } + + [Fact] + public void ToString_WithVeryLargePositiveNumber() + { + var value = new QuantityValue(1234 * BigInteger.Pow(10, 1000)); + + var actualValue = value.ToString("s", CultureInfo.InvariantCulture); + + Assert.Equal("1.23e+1003", actualValue); + } + + [Fact] + public void ToString_WithVerySmallPositiveNumber() + { + var value = new QuantityValue(1234, BigInteger.Pow(10, 1004)); + + var actualValue = value.ToString("s", CultureInfo.InvariantCulture); + + Assert.Equal("1.23e-1001", actualValue); + } + +#if NET + [Fact] + public void TryFormat_Zero_WithValidSpanLength_ReturnsTrue() + { + QuantityValue value = 0; + var destination = new Span(new char[1]); + var result = value.TryFormat(destination, out var charsWritten, "S", CultureInfo.InvariantCulture); + Assert.True(result); + Assert.Equal(1, charsWritten); + Assert.Equal("0", destination[Range.EndAt(charsWritten)]); + } + + [Fact] + public void TryFormat_NegativeNumber_WithValidSpanLength_ReturnsTrue() + { + QuantityValue value = -4.2; + var destination = new Span(new char[4]); + var result = value.TryFormat(destination, out var charsWritten, "S", CultureInfo.InvariantCulture); + Assert.True(result); + Assert.Equal(4, charsWritten); + Assert.Equal("-4.2", destination[Range.EndAt(charsWritten)]); + } + + [Theory] + [InlineData(-1, "S0", 0)] + [InlineData(1, "S0", 0)] + [InlineData(0.1, "S1", 2)] + [InlineData(0.0001, "S4", 0)] // "1E-04" + [InlineData(0.0001, "S4", 4)] // "1E-04" + [InlineData(1e6, "S4", 0)] // "1E+06" + [InlineData(1e6, "S4", 4)] // "1E+06" + public void TryFormat_WithInvalidSpanLength_ReturnsFalse(decimal decimalValue, string format, int testLength) + { + QuantityValue value= decimalValue; + var destination = new Span(new char[testLength]); + var result = value.TryFormat(destination, out var charsWritten, format, CultureInfo.InvariantCulture); + Assert.False(result); + // Assert.Equal(0, charsWritten); // TODO should we make sure that nothing was written? + } +#endif + + /// + /// Values with exponent in the interval [-3 ≤ e ≤ 5] are formatted using the decimal point notation (no extra digits). + /// + public sealed class NormalValueCases : TheoryData + { + public NormalValueCases() + { + foreach (var format in new[] { "S2", "s2" }) + { + // from -1000000 to -1 + Add(new ValueFormatPair(-999999.99m, format), "-999,999.99"); + Add(new ValueFormatPair(-111000, format), "-111,000"); + Add(new ValueFormatPair(-11000, format), "-11,000"); + Add(new ValueFormatPair(-1000, format), "-1,000"); + Add(new ValueFormatPair(-999.99m, format), "-999.99"); + Add(new ValueFormatPair(-2.001234m, format), "-2"); + Add(new ValueFormatPair(-1.1m, format), "-1.1"); + Add(new ValueFormatPair(-1, format), "-1"); + // from -1 to 0 + Add(new ValueFormatPair(-0.1m, format), "-0.1"); + Add(new ValueFormatPair(-0.01m, format), "-0.01"); + Add(new ValueFormatPair(-0.001m, format), "-0.001"); + // from 0 to 1 + Add(new ValueFormatPair(0, format), "0"); + Add(new ValueFormatPair(0.001m, format), "0.001"); + Add(new ValueFormatPair(0.01m, format), "0.01"); + Add(new ValueFormatPair(0.1m, format), "0.1"); + // from 1 to 1000000 + Add(new ValueFormatPair(1, format), "1"); + Add(new ValueFormatPair(1.1m, format), "1.1"); + Add(new ValueFormatPair(2.001234m, format), "2"); + Add(new ValueFormatPair(999.99m, format), "999.99"); + Add(new ValueFormatPair(1000, format), "1,000"); + Add(new ValueFormatPair(11000, format), "11,000"); + Add(new ValueFormatPair(111000, format), "111,000"); + Add(new ValueFormatPair(999999.99m, format), "999,999.99"); + } + } + } + + /// + /// Values with exponent in the interval [-inf ≤ e ≤ -4] are formatted in scientific notation. + /// + public sealed class SmallAbsoluteValueCases : TheoryData + { + public SmallAbsoluteValueCases() + { + // uppercase letter + Add(new ValueFormatPair(1.99e-4m, "S2"), "1.99E-04"); + Add(new ValueFormatPair(-1.99e-4m, "S2"), "-1.99E-04"); + Add(new ValueFormatPair(0.0000111m, "S2"), "1.11E-05"); + Add(new ValueFormatPair(-0.0000111m, "S2"), "-1.11E-05"); + Add(new ValueFormatPair(1.23e-120, "S2"), "1.23E-120"); + Add(new ValueFormatPair(-1.23e-120, "S2"), "-1.23E-120"); + // lowercase letter + Add(new ValueFormatPair(1.99e-4m, "s2"), "1.99e-04"); + Add(new ValueFormatPair(-1.99e-4m, "s2"), "-1.99e-04"); + Add(new ValueFormatPair(0.0000111m, "s2"), "1.11e-05"); + Add(new ValueFormatPair(-0.0000111m, "s2"), "-1.11e-05"); + Add(new ValueFormatPair(1.23e-120, "s2"), "1.23e-120"); + Add(new ValueFormatPair(-1.23e-120, "s2"), "-1.23e-120"); + } + } + + /// + /// Any value in the interval [1e+06 ≤ x ≤ +inf] is formatted in scientific notation. + /// + public sealed class LargePositiveValueCases : TheoryData + { + public LargePositiveValueCases() + { + // from 1E+6 to +inf (uppercase) + Add(new ValueFormatPair(1000000, "S2"), "1E+06"); + Add(new ValueFormatPair(11100000, "S2"), "1.11E+07"); + Add(new ValueFormatPair(double.MaxValue, "S2"), "1.8E+308"); + // from 1e+6 to +inf (lowercase) + Add(new ValueFormatPair(1000000, "s2"), "1e+06"); + Add(new ValueFormatPair(11100000, "s2"), "1.11e+07"); + Add(new ValueFormatPair(double.MaxValue, "s2"), "1.8e+308"); + } + } + + /// + /// Any value in the interval [-inf ≤ x ≤ 1e-04] is formatted in scientific notation. + /// + public sealed class LargeNegativeValueCases : TheoryData + { + public LargeNegativeValueCases() + { + // from -inf up to -1E+6 (uppercase) + Add(new ValueFormatPair(double.MinValue, "S2"), "-1.8E+308"); + Add(new ValueFormatPair(-11100000, "S2"), "-1.11E+07"); + Add(new ValueFormatPair(-1000000, "S2"), "-1E+06"); + // from -inf up to -1e+6 (lowercase) + Add(new ValueFormatPair(double.MinValue, "s2"), "-1.8e+308"); + Add(new ValueFormatPair(-11100000, "s2"), "-1.11e+07"); + Add(new ValueFormatPair(-1000000, "s2"), "-1e+06"); + } + } + } + + public class CustomFormatTests + { + [Theory] + [ClassData(typeof(CustomFormatCases))] + public void ToString_WithCustomFormat(ValueFormatPair pair, string expected) + { + var (value, format) = pair; + var actual = value.ToString(format, CultureInfo.InvariantCulture); + Assert.Equal(expected, actual); + } + +#if NET + [Theory] + [ClassData(typeof(CustomFormatCases))] + public void TryFormat_WithCustomFormat(ValueFormatPair pair, string expected) + { + var (value, format) = pair; + var destination = new Span(new char[100]); + var result = value.TryFormat(destination, out var charsWritten, format, CultureInfo.InvariantCulture); + Assert.True(result); + Assert.Equal(expected, destination[Range.EndAt(charsWritten)]); + } +#endif + + [Fact] + public void NumberFormat_WithEmptySign_DoesNotThrow() + { + var formatProvider = (CultureInfo)CultureInfo.InvariantCulture.Clone(); + var numberFormat = formatProvider.NumberFormat; + Assert.Equal("", numberFormat.NegativeSign = ""); + Assert.Equal(" ", numberFormat.NegativeSign = " "); + Assert.Equal("1", numberFormat.NegativeSign = "1"); + } + + public sealed class CustomFormatCases : TheoryData + { + public CustomFormatCases() + { + var oneHalf = new QuantityValue(1, 2); + Add(new ValueFormatPair(oneHalf, "Test: 0.00"), "Test: 0.50"); + Add(new ValueFormatPair(oneHalf, "Guess: 0.00"), "Guess: 0.50"); + Add(new ValueFormatPair(oneHalf, "Feet: 0.00"), "Feet: 0.50"); + Add(new ValueFormatPair(oneHalf, "Number: 0.00"), "Number: 0.50"); + Add(new ValueFormatPair(oneHalf, "Eons: 0.00"), "Eons: 0.50"); + Add(new ValueFormatPair(oneHalf, "Cans: 0.00"), "Cans: 0.50"); + Add(new ValueFormatPair(oneHalf, "Parsecs: 0.00"), "Parsecs: 0.50"); + Add(new ValueFormatPair(oneHalf, "Some: 0.00"), "Some: 0.50"); + } + } + } + + [Fact] + public void ToString_DefaultsToTheGeneralFormat_WithCurrentCulture() + { + var value = new QuantityValue(1, 3); + // ReSharper disable once SpecifyACultureInStringConversionExplicitly + Assert.Equal(value.ToString("G", CultureInfo.CurrentCulture), value.ToString()); + Assert.Equal(value.ToString("G", CultureInfo.CurrentCulture), value.ToString(string.Empty)); + Assert.Equal(value.ToString("G", CultureInfo.CurrentCulture), value.ToString(null, null)); + } + + [Fact] + public void ToString_WithTheRoundTrippingFormat_ReturnsTheDoubleRepresentation() + { + QuantityValue value = 123.456m; + var expectedValue = value.ToDouble().ToString("R"); + var result = value.ToString("R"); + Assert.Equal(expectedValue, result); + } + + [Fact] + public void ToString_WithNaNOrInfinity_ReturnsTheCorrespondingSymbol() + { + Assert.Multiple( + () => Assert.Equal(double.NaN.ToString(null, null), QuantityValue.NaN.ToString(null, null)), + () => Assert.Equal(double.PositiveInfinity.ToString(null, null), QuantityValue.PositiveInfinity.ToString(null, null)), + () => Assert.Equal(double.NegativeInfinity.ToString(null, null), QuantityValue.NegativeInfinity.ToString(null, null)) + ); + } + +#if NET + [Fact] + public void TryFormat_DefaultsToTheGeneralFormat_WithCurrentCulture() + { + var value = new QuantityValue(1, 3); + Span buffer = stackalloc char[32]; + Assert.True(value.TryFormat(buffer, out var charsWritten, default, null)); + Assert.Equal(value.ToString("G", CultureInfo.CurrentCulture), buffer[..charsWritten]); + } + + [Fact] + public void TryFormat_NaNOrInfinity_ReturnsTheCorrespondingSymbol() + { + Assert.Multiple( + () => + { + Span buffer = stackalloc char[32]; + Assert.True(QuantityValue.NaN.TryFormat(buffer, out var charsWritten, null, null)); + Assert.Equal(double.NaN.ToString(null, null), new string(buffer[..charsWritten])); + }, + () => + { + Span buffer = stackalloc char[32]; + Assert.True(QuantityValue.PositiveInfinity.TryFormat(buffer, out var charsWritten, null, null)); + Assert.Equal(double.PositiveInfinity.ToString(null, null), new string(buffer[..charsWritten])); + }, + () => + { + Span buffer = stackalloc char[32]; + Assert.True(QuantityValue.NegativeInfinity.TryFormat(buffer, out var charsWritten, null, null)); + Assert.Equal(double.NegativeInfinity.ToString(null, null), new string(buffer[..charsWritten])); + } + ); + } + + [Fact] + public void TryFormat_NaNOrInfinity_WithInvalidSpanLength_ReturnsFalse() + { + Assert.Multiple( + () => + { + Assert.False(QuantityValue.NaN.TryFormat(Span.Empty, out var charsWritten, null, null)); + Assert.Equal(0, charsWritten); + }, + () => + { + Assert.False(QuantityValue.PositiveInfinity.TryFormat(Span.Empty, out var charsWritten, null, null)); + Assert.Equal(0, charsWritten); + }, + () => + { + Assert.False(QuantityValue.NegativeInfinity.TryFormat(Span.Empty, out var charsWritten, null, null)); + Assert.Equal(0, charsWritten); + } + ); + } +#endif + } +} diff --git a/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.DebugView.cs b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.DebugView.cs new file mode 100644 index 0000000000..5363e2d1d0 --- /dev/null +++ b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.DebugView.cs @@ -0,0 +1,89 @@ +using System.Numerics; +using JetBrains.Annotations; + +namespace UnitsNet.Tests; + +public partial class QuantityValueTests +{ + [TestSubject(typeof(QuantityValue.QuantityValueDebugView))] + public class DebugViewTests + { + [Theory] + [InlineData(1, 1, true, 2)] + [InlineData(2, 4, false, 5)] + [InlineData(0, 1, true, 1)] + [InlineData(1, 0, true, 1)] // Corner case: Denominator is zero + [InlineData(-200, 1, true, 9)] // Negative numerator + [InlineData(0, 0, true, 0)] // Both numerator and denominator are zero + public void QuantityValueDebugView_Properties_ShouldReturnExpectedValues( + int numerator, int denominator, bool expectedIsReduced, long expectedNbBits) + { + var value = new QuantityValue(new BigInteger(numerator), new BigInteger(denominator)); + var debugView = new QuantityValue.QuantityValueDebugView(value); + + Assert.Equal(expectedIsReduced, debugView.IsReduced); + Assert.Equal(expectedNbBits, debugView.NbBits); + } + + [Theory] + [InlineData(1, 1, "1/1")] + [InlineData(2, 4, "1/2")] + [InlineData(0, 1, "0/1")] + [InlineData(1, 0, "1/0")] // Corner case: Denominator is zero + [InlineData(-1, 1, "-1/1")] // Negative numerator + [InlineData(0, 0, "0/0")] // Both numerator and denominator are zero + public void StringFormatsView_SimplifiedFraction_ShouldReturnExpectedString( + int numerator, int denominator, string expectedSimplifiedFraction) + { + var value = new QuantityValue(new BigInteger(numerator), new BigInteger(denominator)); + var debugView = new QuantityValue.QuantityValueDebugView(value); + + Assert.Equal(expectedSimplifiedFraction, debugView.StringFormats.SimplifiedFraction); + } + + [Theory] + [InlineData(1.23)] + [InlineData(-1.23)] + [InlineData(100000)] + [InlineData(0.00001)] + public void StringFormatsView_GeneralFormat_ShouldReturnExpectedString(double decimalValue) + { + QuantityValue value = decimalValue; + var debugView = new QuantityValue.QuantityValueDebugView(value); + + Assert.Equal(value.ToString("G"), debugView.StringFormats.GeneralFormat); + } + + [Theory] + [InlineData(1.23)] + [InlineData(-1.23)] + [InlineData(100000)] + [InlineData(0.00001)] + public void StringFormatsView_ShortFormat_ShouldReturnExpectedString(double decimalValue) + { + QuantityValue value = decimalValue; + var debugView = new QuantityValue.QuantityValueDebugView(value); + + Assert.Equal(value.ToString("S"), debugView.StringFormats.ShortFormat); + } + + [Theory] + [InlineData(1, 1, 1, 1.0, 1.0)] + [InlineData(2, 1, 2, 2.0, 2.0)] + [InlineData(1, 2, 0, 0.5, 0.5)] + [InlineData(0, 1, 0, 0.0, 0.0)] + [InlineData(-1, 1, -1, -1.0, -1.0)] // Negative numerator + [InlineData(1, -1, -1, -1.0, -1.0)] // Negative denominator + public void NumericFormatsView_Properties_ShouldReturnExpectedValues( + int numerator, int denominator, int expectedInteger, double expectedDouble, decimal expectedDecimal) + { + var value = new QuantityValue(new BigInteger(numerator), new BigInteger(denominator)); + var debugView = new QuantityValue.QuantityValueDebugView(value); + + Assert.Equal(expectedInteger, debugView.ValueFormats.Integer); + Assert.Equal(expectedInteger, debugView.ValueFormats.Long); + Assert.Equal(expectedDouble, debugView.ValueFormats.Double); + Assert.Equal(expectedDecimal, debugView.ValueFormats.Decimal); + } + } +} \ No newline at end of file diff --git a/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.Extensions.cs b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.Extensions.cs new file mode 100644 index 0000000000..139cb42478 --- /dev/null +++ b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.Extensions.cs @@ -0,0 +1,219 @@ +using JetBrains.Annotations; + +namespace UnitsNet.Tests; + +public partial class QuantityValueTests +{ + [TestSubject(typeof(QuantityValueExtensions))] + public class ExtensionTests + { + [Fact] + public void Sum_WithQuantityValues_ReturnsCorrectSum() + { + IEnumerable values = [1.0m, 2.0m, 3.0m]; + QuantityValue result = values.Sum(); + Assert.Equal(6.0m, result); + } + + [Fact] + public void Sum_WithEmptyCollection_ReturnsZero() + { + QuantityValue result = Array.Empty().Sum(); + Assert.Equal(QuantityValue.Zero, result); + } + + [Fact] + public void Sum_WithEmptySelector_ReturnsZero() + { + IEnumerable empty = Array.Empty(); + Assert.Equal(QuantityValue.Zero, empty.Select(value => value).Sum()); + } + + [Fact] + public void Average_WithASingleValues_ReturnsTheSameValue() + { + IEnumerable values = [42]; + QuantityValue result = values.Average(); + Assert.Equal(42, result); + } + + [Fact] + public void Average_WithQuantityValues_ReturnsCorrectAverage() + { + IEnumerable values = [1.0m, 2.0m, 3.0m]; + QuantityValue result = values.Average(); + Assert.Equal(2.0m, result); + } + + [Fact] + public void Average_WithSelector_ReturnsCorrectAverage() + { + IEnumerable values = [1.0m, 2.0m, 3.0m]; + QuantityValue result = values.Select(v => v).Average(); + Assert.Equal(2.0m, result); + } + + [Fact] + public void Average_WithEmptyCollection_ThrowsInvalidOperationException() + { + Assert.Throws(() => Array.Empty().Average()); + } + + [Fact] + public void Average_WithEmptySelector_ThrowsInvalidOperationException() + { + IEnumerable empty = Array.Empty(); + Assert.Throws(() => empty.Select(v => v).Average()); + } + + [Theory] + [InlineData(-1, 1, 0.1)] + [InlineData(0, 1, 1)] + [InlineData(1.0, 1, 10.0)] + [InlineData(2.0, 1, 100.0)] + [InlineData(3.0, 1, 1000.0)] + [InlineData(4.2, 1, 15848.93192)] + [InlineData(-10, 10, 0.1)] + [InlineData(0, 10, 1)] + [InlineData(10, 10, 10.0)] + [InlineData(20, 10, 100.0)] + [InlineData(30, 10, 1000.0)] + public void ToLinearSpace_ReturnsCorrectLinearValue(decimal logValue, decimal scalingFactor, double expected) + { + var result = ((QuantityValue)logValue).ToLinearSpace(scalingFactor); + Assert.Equal(expected, result, 5); + } + + [Theory] + [InlineData(-1, 1, 15, 0.1)] + [InlineData(0, 1, 15, 1)] + [InlineData(1.0, 1, 15, 10.0)] + [InlineData(2.0, 1, 15, 100.0)] + [InlineData(3.0, 1, 15, 1000.0)] + [InlineData(4.2, 1, 8, 15848.932)] + [InlineData(-10, 10, 15, 0.1)] + [InlineData(0, 10, 15, 1)] + [InlineData(10, 10, 5, 10.0)] + [InlineData(20, 10, 5, 100.0)] + [InlineData(30, 10, 5, 1000.0)] + public void ToLinearSpace_WithSignificantDigits_ReturnsCorrectLinearValue(decimal logValue, decimal scalingFactor, byte significantDigits, decimal expected) + { + QuantityValue result = ((QuantityValue)logValue).ToLinearSpace(scalingFactor, significantDigits); + Assert.Equal(expected, result); + } + + [Theory] + [InlineData(1, 1, 15, 0)] + [InlineData(10.0, 1, 15, 1.0)] + [InlineData(100.0, 1, 15, 2.0)] + [InlineData(1000.0, 1, 15, 3.0)] + [InlineData(100.0, 10, 15, 20)] + [InlineData(1000.0, 10, 15, 30)] + [InlineData(10000.0, 10, 15, 40)] + public void ToLogSpace_ReturnsCorrectLogValue(decimal value, decimal scalingFactor, byte significantDigits, decimal expected) + { + QuantityValue result = ((QuantityValue)value).ToLogSpace(scalingFactor, significantDigits); + Assert.Equal(expected, result); + } + + [Theory] + [InlineData(10.0, 1, 5, 1.0)] + [InlineData(100.0, 1, 5, 2.0)] + [InlineData(1000.0, 1, 5, 3.0)] + [InlineData(100.0, 10, 15, 20)] + [InlineData(1000.0, 10, 15, 30)] + [InlineData(10000.0, 10, 15, 40)] + public void ToLogSpace_WithQuantityValue_ReturnsCorrectLogValue(decimal value, decimal scalingFactor, byte significantDigits, decimal expected) + { + QuantityValue result = ((QuantityValue)value).ToLogSpace(scalingFactor, significantDigits); + Assert.Equal(expected, result); + } + + [Theory] + [InlineData(1)] + [InlineData(10)] + public void ToLogSpace_WithZero_ReturnsNegativeInfinity(decimal scalingFactor) + { + QuantityValue result = QuantityValue.Zero.ToLogSpace(scalingFactor); + Assert.True(QuantityValue.IsNegativeInfinity(result)); + } + + [Theory] + [InlineData(-0.1, 1)] + [InlineData(-1.0, 1)] + [InlineData(-10, 1)] + [InlineData(-0.1, 10)] + [InlineData(-1, 10)] + [InlineData(-10, 10)] + public void ToLogSpace_WithNegativeValues_ReturnsNaN(decimal logValue, decimal scalingFactor) + { + QuantityValue result = ((QuantityValue)logValue).ToLogSpace(scalingFactor); + Assert.True(QuantityValue.IsNaN(result)); + } + + [Theory] + [InlineData(1.0, 1.0, 1, 2, 1.30)] + [InlineData(1.0, 1.0, 1, 5, 1.3010)] + [InlineData(2.0, 2.0, 1, 5, 2.301)] + [InlineData(3.0, 3.0, 1, 5, 3.301)] + [InlineData(1.0, -1.0, 1, 5, 1.0043)] + [InlineData(1.0, -2.0, 1, 5, 1.0004)] + [InlineData(0, -2.0, 1, 5, 0.0043214)] + [InlineData(-1.0, -2.0, 1, 5, -0.95861)] + [InlineData(1.0, 1.0, 10, 5, 4.0103)] + [InlineData(2.0, 2.0, 10, 5, 5.0103)] + [InlineData(3.0, 3.0, 10, 5, 6.0103)] + [InlineData(10, 30, 20, 5, 30.828)] + [InlineData(20, 30, 20, 5, 32.386)] + [InlineData(30, 30, 20, 5, 36.020)] + public void AddWithLogScaling_ReturnsCorrectLogSum(decimal leftValue, decimal rightValue, decimal scalingFactor, byte significantDigits, decimal expected) + { + QuantityValue result = QuantityValueExtensions.AddWithLogScaling(leftValue, rightValue, scalingFactor, significantDigits); + Assert.Equal(expected, result); + } + + [Theory] + [InlineData(2.0, 1.0, 1, 5, 1.9542)] + [InlineData(3.0, 1.0, 1, 5, 2.9956)] + [InlineData(20, 10, 1, 12, 20)] + [InlineData(30, 10, 1, 15, 30)] + [InlineData(40, 10, 1, 15, 40)] + [InlineData(2.0, 1.0, 10, 5, -4.8683)] + [InlineData(3.0, 1.0, 10, 5, -1.3292)] + [InlineData(20, 10, 10, 5, 19.542)] + [InlineData(30, 10, 10, 5, 29.956)] + [InlineData(40, 10, 10, 5, 39.996)] + [InlineData(200, 100, 10, 12, 200)] + [InlineData(300, 100, 10, 15, 300)] + [InlineData(400, 100, 10, 15, 400)] + public void SubtractWithLogScaling_ReturnsCorrectLogDifference(decimal leftValue, decimal rightValue, decimal scalingFactor, byte significantDigits, + decimal expected) + { + QuantityValue result = QuantityValueExtensions.SubtractWithLogScaling(leftValue, rightValue, scalingFactor, significantDigits); + Assert.Equal(expected, result); + } + + [Theory] + [InlineData(1.0, 1.0, 1, 5)] + [InlineData(-1.0, -1.0, 1, 5)] + [InlineData(1.0, 1.0, 10, 5)] + [InlineData(-1.0, -1.0, 10, 5)] + public void SubtractWithLogScaling_WithSameValues_ReturnsNegativeInfinity(decimal leftValue, decimal rightValue, decimal scalingFactor, + byte significantDigits) + { + QuantityValue result = QuantityValueExtensions.SubtractWithLogScaling(leftValue, rightValue, scalingFactor, significantDigits); + Assert.True(QuantityValue.IsNegativeInfinity(result)); + } + + [Theory] + [InlineData(-20.0, 1, 1, 5)] + [InlineData(-20.0, 1, 10, 5)] + [InlineData(-1.0, 20, 1, 5)] + [InlineData(-1.0, 20, 10, 5)] + public void SubtractWithLogScaling_WithNegativeValues_ReturnsNaN(decimal leftValue, decimal rightValue, decimal scalingFactor, byte significantDigits) + { + QuantityValue result = QuantityValueExtensions.SubtractWithLogScaling(leftValue, rightValue, scalingFactor, significantDigits); + Assert.True(QuantityValue.IsNaN(result)); + } + } +} \ No newline at end of file diff --git a/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.Fraction.cs b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.Fraction.cs new file mode 100644 index 0000000000..082be7e9da --- /dev/null +++ b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.Fraction.cs @@ -0,0 +1,37 @@ +using System.Numerics; + +namespace UnitsNet.Tests; + +public partial class QuantityValueTests +{ + public class FractionTests + { + [Theory] + [InlineData(1, 1, 1, 1)] + [InlineData(2, 1, 1, 2)] + public void InverseTests(BigInteger num, BigInteger den, BigInteger expectedNum, BigInteger expectedDen) + { + var value = new QuantityValue(num, den); + var expected = new QuantityValue(expectedNum, expectedDen); + Assert.Equal(expected, QuantityValue.Inverse(value)); + } + + [Theory] + [InlineData(0, 0, 0, 0)] // NaN + [InlineData(1, 0, 1, 0)] // PositiveInfinity + [InlineData(-1, 0, -1, 0)] // NegativeInfinity + [InlineData(0, 1, 0, 1)] // Zero + [InlineData(1, 1, 1, 1)] // One + [InlineData(-1, 1, -1, 1)] // MinusOne + [InlineData(2, 1, 2, 1)] // Two (whole number) + [InlineData(2, 4, 1, 2)] // 2/4 -> 1/2 + [InlineData(2, 5, 2, 5)] // 2/5 -> 2/5 (unchanged) + public void ReduceTests(BigInteger num, BigInteger den, BigInteger expectedNum, BigInteger expectedDen) + { + var value = new QuantityValue(num, den); + var (numerator, denominator) = QuantityValue.Reduce(value); + Assert.Equal(expectedNum, numerator); + Assert.Equal(expectedDen, denominator); + } + } +} \ No newline at end of file diff --git a/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.Number.cs b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.Number.cs new file mode 100644 index 0000000000..cf706ed11b --- /dev/null +++ b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.Number.cs @@ -0,0 +1,477 @@ +using System.Numerics; + +namespace UnitsNet.Tests; + +public partial class QuantityValueTests +{ + public class NumberTests + { +#if NET7_0_OR_GREATER + [Fact] + public void Radix_Returns_Ten() + { + Assert.Equal(10, GetRadix()); + return; + + static int GetRadix() + where T : INumber + { + return T.Radix; + } + } + + [Fact] + public void AdditiveIdentity_Returns_Zero() + { + Assert.Equal(0, GetAdditiveIdentity()); + return; + + static T GetAdditiveIdentity() + where T : IAdditiveIdentity + { + return T.AdditiveIdentity; + } + } + + [Fact] + public void MultiplicativeIdentity_Returns_One() + { + Assert.Equal(1, GetMultiplicativeIdentity()); + return; + + static T GetMultiplicativeIdentity() + where T : IMultiplicativeIdentity + { + return T.MultiplicativeIdentity; + } + } + + [Fact] + public void NegativeOne__Returns_MinusOne() + { + Assert.Equal(-1, QuantityValue.MinusOne); + Assert.Equal(-1, GetNegativeOne()); + return; + + static T GetNegativeOne() + where T : ISignedNumber + { + return T.NegativeOne; + } + } + + [Fact] + public void IsNormal_WithFiniteValue_ReturnsTrue() + { + Assert.True(IsNormal(new QuantityValue(1, 3))); + return; + + static bool IsNormal(T value) + where T : INumberBase + { + return T.IsNormal(value); + } + } + + [Fact] + public void IsNormal_WithNonFiniteValue_ReturnsFalse() + { + Assert.Multiple(() => + { + Assert.False(IsNormal(QuantityValue.NaN)); + Assert.False(IsNormal(QuantityValue.PositiveInfinity)); + Assert.False(IsNormal(QuantityValue.NegativeInfinity)); + }, () => + { + // same as the behavior of double + Assert.False(IsNormal(double.NaN)); + Assert.False(IsNormal(double.PositiveInfinity)); + Assert.False(IsNormal(double.NegativeInfinity)); + }); + return; + + static bool IsNormal(T value) + where T : INumberBase + { + return T.IsNormal(value); + } + } + + [Fact] + public void IsRealNumber_WithInfinity_ReturnsTrue() + { + Assert.Multiple(() => + { + Assert.True(IsRealNumber(QuantityValue.PositiveInfinity)); + Assert.True(IsRealNumber(QuantityValue.NegativeInfinity)); + }, () => + { + // same as the behavior of double + Assert.True(IsRealNumber(double.PositiveInfinity)); + Assert.True(IsRealNumber(double.NegativeInfinity)); + }); + return; + + static bool IsRealNumber(T value) + where T : INumberBase + { + return T.IsRealNumber(value); + } + } + + [Fact] + public void IsRealNumber_WithNaN_ReturnsFalse() + { + Assert.Multiple(() => + { + Assert.False(IsRealNumber(QuantityValue.NaN)); + }, () => + { + // same as the behavior of double + Assert.False(IsRealNumber(double.NaN)); + }); + return; + + static bool IsRealNumber(T value) + where T : INumberBase + { + return T.IsRealNumber(value); + } + } + + [Fact] + public void IsComplexNumber_ReturnsFalse() + { + Assert.Multiple(() => + { + Assert.False(IsComplexNumber(QuantityValue.One)); + Assert.False(IsComplexNumber(QuantityValue.NaN)); + Assert.False(IsComplexNumber(QuantityValue.PositiveInfinity)); + Assert.False(IsComplexNumber(QuantityValue.NegativeInfinity)); + }, () => + { + // same as the behavior of double + Assert.False(IsComplexNumber(1.0)); + Assert.False(IsComplexNumber(double.NaN)); + Assert.False(IsComplexNumber(double.PositiveInfinity)); + Assert.False(IsComplexNumber(double.NegativeInfinity)); + }); + return; + + static bool IsComplexNumber(T value) + where T : INumberBase + { + return T.IsComplexNumber(value); + } + } + + [Fact] + public void IsImaginaryNumber_ReturnsFalse() + { + Assert.Multiple(() => + { + Assert.False(IsImaginaryNumber(QuantityValue.One)); + Assert.False(IsImaginaryNumber(QuantityValue.NaN)); + Assert.False(IsImaginaryNumber(QuantityValue.PositiveInfinity)); + Assert.False(IsImaginaryNumber(QuantityValue.NegativeInfinity)); + }, () => + { + // same as the behavior of double + Assert.False(IsImaginaryNumber(1.0)); + Assert.False(IsImaginaryNumber(double.NaN)); + Assert.False(IsImaginaryNumber(double.PositiveInfinity)); + Assert.False(IsImaginaryNumber(double.NegativeInfinity)); + }); + return; + + static bool IsImaginaryNumber(T value) + where T : INumberBase + { + return T.IsImaginaryNumber(value); + } + } + + [Fact] + public void IsSubnormal_ReturnsFalse() + { + Assert.Multiple(() => + { + Assert.False(IsSubnormal(QuantityValue.One)); + Assert.False(IsSubnormal(QuantityValue.NaN)); + Assert.False(IsSubnormal(QuantityValue.PositiveInfinity)); + Assert.False(IsSubnormal(QuantityValue.NegativeInfinity)); + }, () => + { + // same as the behavior of double + Assert.False(IsSubnormal(1.0)); + Assert.False(IsSubnormal(double.NaN)); + Assert.False(IsSubnormal(double.PositiveInfinity)); + Assert.False(IsSubnormal(double.NegativeInfinity)); + }); + return; + + static bool IsSubnormal(T value) + where T : INumberBase + { + return T.IsSubnormal(value); + } + } + +#endif + + [Theory] + [InlineData(0, 1, true)] + [InlineData(1, 1, true)] + [InlineData(-1, 1, true)] + [InlineData(-1, -1, true)] + [InlineData(2, 1, true)] + [InlineData(1, 2, true)] + [InlineData(1, 0, true)] + [InlineData(-1, 0, true)] + [InlineData(0, 0, true)] + [InlineData(2, 2, false)] + [InlineData(-2, 2, false)] + [InlineData(-2, -2, false)] + public void IsCanonicalTests(BigInteger numerator, BigInteger denominator, bool expected) + { + var value = new QuantityValue(numerator, denominator); + Assert.Equal(expected, QuantityValue.IsCanonical(value)); + } + + [Theory] + [InlineData(0, 1, true)] + [InlineData(1, 0, false)] + [InlineData(1, 2, true)] + [InlineData(1, 3, false)] + [InlineData(1, 4, true)] + [InlineData(1, 10, true)] + [InlineData(1, 50, true)] + [InlineData(1, 350, false)] + public void HasFiniteDecimalExpansion(BigInteger numerator, BigInteger denominator, bool expected) + { + var value = new QuantityValue(numerator, denominator); + Assert.Equal(expected, QuantityValue.HasFiniteDecimalExpansion(value)); + } + + [Theory] + [InlineData(2, 1, true)] + [InlineData(3, 1, false)] + [InlineData(1, 0, false)] + [InlineData(4, 2, true)] + [InlineData(6, 2, false)] + [InlineData(3, 2, false)] + public void IsEvenIntegerTests(BigInteger numerator, BigInteger denominator, bool expected) + { + var value = new QuantityValue(numerator, denominator); + Assert.Equal(expected, QuantityValue.IsEvenInteger(value)); + } + + [Theory] + [InlineData(1, 1, true)] + [InlineData(0, 1, true)] + [InlineData(1, 0, false)] + public void IsFiniteTests(BigInteger numerator, BigInteger denominator, bool expected) + { + var value = new QuantityValue(numerator, denominator); + Assert.Equal(expected, QuantityValue.IsFinite(value)); + } + + [Theory] + [InlineData(1, 0, true)] + [InlineData(0, 1, false)] + public void IsInfinityTests(BigInteger numerator, BigInteger denominator, bool expected) + { + var value = new QuantityValue(numerator, denominator); + Assert.Equal(expected, QuantityValue.IsInfinity(value)); + } + + [Theory] + [InlineData(0, 1, true)] + [InlineData(0, 2, true)] + [InlineData(1, 1, true)] + [InlineData(2, 1, true)] + [InlineData(-6, 3, true)] + [InlineData(1, 2, false)] + [InlineData(3, 2, false)] + [InlineData(1, 0, false)] + public void IsIntegerTests(BigInteger numerator, BigInteger denominator, bool expected) + { + var value = new QuantityValue(numerator, denominator); + Assert.Equal(expected, QuantityValue.IsInteger(value)); + } + + [Theory] + [InlineData(0, 0, true)] + [InlineData(1, 1, false)] + public void IsNaNTests(BigInteger numerator, BigInteger denominator, bool expected) + { + var value = new QuantityValue(numerator, denominator); + Assert.Equal(expected, QuantityValue.IsNaN(value)); + } + + [Theory] + [InlineData(-1, 1, true)] + [InlineData(1, 1, false)] + public void IsNegativeTests(BigInteger numerator, BigInteger denominator, bool expected) + { + var value = new QuantityValue(numerator, denominator); + Assert.Equal(expected, QuantityValue.IsNegative(value)); + } + + [Theory] + [InlineData(-1, 0, true)] + [InlineData(1, 0, false)] + public void IsNegativeInfinityTests(BigInteger numerator, BigInteger denominator, bool expected) + { + var value = new QuantityValue(numerator, denominator); + Assert.Equal(expected, QuantityValue.IsNegativeInfinity(value)); + } + + [Theory] + [InlineData(2, 1, false)] + [InlineData(3, 1, true)] + [InlineData(1, 0, false)] + [InlineData(1, 2, false)] + [InlineData(6, 2, true)] + [InlineData(6, 3, false)] + public void IsOddIntegerTests(BigInteger numerator, BigInteger denominator, bool expected) + { + var value = new QuantityValue(numerator, denominator); + Assert.Equal(expected, QuantityValue.IsOddInteger(value)); + } + + [Theory] + [InlineData(1, 1, true)] + [InlineData(0, 1, false)] + [InlineData(1, 0, true)] + [InlineData(-1, 1, false)] + [InlineData(-1, 0, false)] + [InlineData(0, 0, false)] + public void IsPositiveTests(BigInteger numerator, BigInteger denominator, bool expected) + { + var value = new QuantityValue(numerator, denominator); + Assert.Equal(expected, QuantityValue.IsPositive(value)); + } + + [Theory] + [InlineData(1, 0, true)] + [InlineData(-1, 0, false)] + public void IsPositiveInfinityTests(BigInteger numerator, BigInteger denominator, bool expected) + { + var value = new QuantityValue(numerator, denominator); + Assert.Equal(expected, QuantityValue.IsPositiveInfinity(value)); + } + + [Theory] + [InlineData(0, 1, true)] + [InlineData(1, 1, false)] + public void IsZeroTests(BigInteger numerator, BigInteger denominator, bool expected) + { + var value = new QuantityValue(numerator, denominator); + Assert.Equal(expected, QuantityValue.IsZero(value)); + } + + [Theory] + [InlineData(1, 2, 1, 3, 1, 2)] + [InlineData(-1, 2, 1, 3, -1, 2)] + [InlineData(0, 1, 1, 3, 1, 3)] + [InlineData(0, 0, 1, 3, 0, 0)] // NaN + [InlineData(1, 3, 0, 0, 0, 0)] // NaN + [InlineData(0, 0, 1, 0, 0, 0)] // NaN + [InlineData(1, 0, 0, 0, 0, 0)] // NaN + [InlineData(0, 0, -1, 0, 0, 0)] // NaN + [InlineData(-1, 0, 0, 0, 0, 0)] // NaN + [InlineData(1, 0, -1, 0, 1, 0)] // PositiveInfinity + [InlineData(-1, 0, 1, 0, 1, 0)] // PositiveInfinity + public void MaxMagnitudeTests(BigInteger num1, BigInteger den1, BigInteger num2, BigInteger den2, BigInteger expectedNum, BigInteger expectedDen) + { + var value1 = new QuantityValue(num1, den1); + var value2 = new QuantityValue(num2, den2); + var expected = new QuantityValue(expectedNum, expectedDen); +#if NET + Assert.Equal(double.MaxMagnitude(value1.ToDouble(), value2.ToDouble()), expected.ToDouble()); // making sure the expectation is correct +#endif + Assert.Equal(expected, QuantityValue.MaxMagnitude(value1, value2)); + } + + [Theory] + [InlineData(1, 2, 1, 3, 1, 2)] + [InlineData(-1, 2, 1, 3, -1, 2)] + [InlineData(1, 3, -1, 2, -1, 2)] + [InlineData(0, 0, 1, 3, 1, 3)] // NaN + [InlineData(1, 2, 0, 0, 1, 2)] // NaN + [InlineData(0, 0, 1, 0, 1, 0)] // NaN and PositiveInfinity + [InlineData(1, 0, 0, 0, 1, 0)] // PositiveInfinity and NaN + [InlineData(0, 0, -1, 0, -1, 0)] // NaN and NegativeInfinity + [InlineData(-1, 0, 0, 0, -1, 0)] // NegativeInfinity and NaN + [InlineData(1, 0, -1, 0, 1, 0)] // PositiveInfinity and NegativeInfinity + [InlineData(-1, 0, 1, 0, 1, 0)] // NegativeInfinity and PositiveInfinity + [InlineData(0, 0, 0, 0, 0, 0)] // NaN and NaN + public void MaxMagnitudeNumberTests(BigInteger num1, BigInteger den1, BigInteger num2, BigInteger den2, BigInteger expectedNum, BigInteger expectedDen) + { + var value1 = new QuantityValue(num1, den1); + var value2 = new QuantityValue(num2, den2); + var expected = new QuantityValue(expectedNum, expectedDen); +#if NET + Assert.Equal(double.MaxMagnitudeNumber(value1.ToDouble(), value2.ToDouble()), expected.ToDouble()); // making sure the expectation is correct +#endif + Assert.Equal(expected, QuantityValue.MaxMagnitudeNumber(value1, value2)); + } + + [Theory] + [InlineData(1, 2, 1, 3, 1, 3)] + [InlineData(-1, 2, 1, 3, 1, 3)] + [InlineData(0, 1, 1, 3, 0, 1)] + [InlineData(0, 0, 1, 3, 0, 0)] // NaN + [InlineData(1, 3, 0, 0, 0, 0)] // NaN + [InlineData(0, 0, 1, 0, 0, 0)] // NaN + [InlineData(1, 0, 0, 0, 0, 0)] // NaN + [InlineData(0, 0, -1, 0, 0, 0)] // NaN + [InlineData(-1, 0, 0, 0, 0, 0)] // NaN + [InlineData(1, 0, -1, 0, -1, 0)] // PositiveInfinity and NegativeInfinity + [InlineData(-1, 0, 1, 0, -1, 0)] // NegativeInfinity and PositiveInfinity + public void MinMagnitudeTests(BigInteger num1, BigInteger den1, BigInteger num2, BigInteger den2, BigInteger expectedNum, BigInteger expectedDen) + { + var value1 = new QuantityValue(num1, den1); + var value2 = new QuantityValue(num2, den2); + var expected = new QuantityValue(expectedNum, expectedDen); +#if NET + Assert.Equal(double.MinMagnitude(value1.ToDouble(), value2.ToDouble()), expected.ToDouble()); // making sure the expectation is correct +#endif + Assert.Equal(expected, QuantityValue.MinMagnitude(value1, value2)); + } + + [Theory] + [InlineData(1, 2, 1, 3, 1, 3)] + [InlineData(-1, 2, 1, 3, 1, 3)] + [InlineData(0, 0, 1, 3, 1, 3)] // NaN + [InlineData(1, 2, 0, 0, 1, 2)] // NaN + [InlineData(0, 0, 1, 0, 1, 0)] // NaN and PositiveInfinity + [InlineData(1, 0, 0, 0, 1, 0)] // PositiveInfinity and NaN + [InlineData(0, 0, -1, 0, -1, 0)] // NaN and NegativeInfinity + [InlineData(-1, 0, 0, 0, -1, 0)] // NegativeInfinity and NaN + [InlineData(1, 0, -1, 0, -1, 0)] // PositiveInfinity and NegativeInfinity + [InlineData(-1, 0, 1, 0, -1, 0)] // NegativeInfinity and PositiveInfinity + [InlineData(0, 0, 0, 0, 0, 0)] // NaN and NaN + public void MinMagnitudeNumberTests(BigInteger num1, BigInteger den1, BigInteger num2, BigInteger den2, BigInteger expectedNum, BigInteger expectedDen) + { + var value1 = new QuantityValue(num1, den1); + var value2 = new QuantityValue(num2, den2); + var expected = new QuantityValue(expectedNum, expectedDen); +#if NET + Assert.Equal(double.MinMagnitudeNumber(value1.ToDouble(), value2.ToDouble()), expected.ToDouble()); // making sure the expectation is correct +#endif + Assert.Equal(expected, QuantityValue.MinMagnitudeNumber(value1, value2)); + } + + [Theory] + [InlineData(1, 1, 1, 1)] + [InlineData(-1, 1, 1, 1)] + public void AbsTests(BigInteger num, BigInteger den, BigInteger expectedNum, BigInteger expectedDen) + { + var value = new QuantityValue(num, den); + var expected = new QuantityValue(expectedNum, expectedDen); + Assert.Equal(expected, QuantityValue.Abs(value)); + } + } +} diff --git a/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.PowerMath.cs b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.PowerMath.cs new file mode 100644 index 0000000000..c4c93b7c10 --- /dev/null +++ b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.PowerMath.cs @@ -0,0 +1,430 @@ +using System.Globalization; +using System.Numerics; + +namespace UnitsNet.Tests; + +public partial class QuantityValueTests +{ + public class PowerMathTests + { + [Theory] + [InlineData(18)] + [InlineData(19)] + [InlineData(36)] + [InlineData(37)] + [InlineData(54)] + [InlineData(55)] + public void PowerOfTen_Equals_BigIntegerPow(int power) + { + BigInteger powerOfTen = QuantityValue.PowerOfTen(power); + var bigIntegerPower = BigInteger.Pow(10, power); + Assert.Equal(bigIntegerPower, powerOfTen); + } + + [Theory] + [InlineData(0, 1, 1, 0, 1)] // 0^1 == 0 + [InlineData(2, 1, 0, 1, 1)] // 2^0 == 1 + [InlineData(2, 1, -1, 1, 2)] // 2^-1 == 1/2 + [InlineData(2, 1, -2, 1, 4)] // 2^-2 == 1/4 + [InlineData(-2, 1, -1, -1, 2)] // 2^-1 == -1/2 + [InlineData(-2, 1, -2, 1, 4)] // -2^-2 == 1/4 + [InlineData(0, 1, -2, 1, 0)] // 0^-2 == PositiveInfinity + [InlineData(2, 1, 1, 2, 1)] + [InlineData(1, 1, 2, 1, 1)] + [InlineData(2, 1, 2, 4, 1)] + [InlineData(3, 1, 2, 9, 1)] + [InlineData(1, 2, 2, 1, 4)] + public void PowTests(BigInteger num, BigInteger den, int power, BigInteger expectedNum, BigInteger expectedDen) + { + var value = new QuantityValue(num, den); + var expected = new QuantityValue(expectedNum, expectedDen); + + var result = QuantityValue.Pow(value, power); + +#if NET + Assert.Equal(double.Pow(value.ToDouble(), power), result.ToDouble(), 15); +#endif + Assert.Equal(expected, result); + } + + [Theory] + [InlineData(double.NaN, -2, double.NaN)] + [InlineData(double.NaN, -1, double.NaN)] + [InlineData(double.NaN, 0, 1)] + [InlineData(double.NaN, 1, double.NaN)] + [InlineData(double.NaN, 2, double.NaN)] + [InlineData(double.PositiveInfinity, -2, 0)] + [InlineData(double.PositiveInfinity, -1, 0)] + [InlineData(double.PositiveInfinity, 0, 1)] + [InlineData(double.PositiveInfinity, 1, double.PositiveInfinity)] + [InlineData(double.PositiveInfinity, 2, double.PositiveInfinity)] + [InlineData(double.NegativeInfinity, -2, 0)] + [InlineData(double.NegativeInfinity, -1, 0)] + [InlineData(double.NegativeInfinity, 0, 1)] + [InlineData(double.NegativeInfinity, 1, double.NegativeInfinity)] + [InlineData(double.NegativeInfinity, 2, double.PositiveInfinity)] + public void PowWithNaNOrInfinityTests(double number, int power, double expectedResult) + { + var result = QuantityValue.Pow(number, power); +#if NET + Assert.Equal(double.Pow(number, power), result.ToDouble()); +#endif + Assert.Equal(expectedResult, result); + } + + [Theory] + [InlineData(2, 1, 1, 1, 2, 1)] + [InlineData(1, 1, 2, 1, 1, 1)] + [InlineData(2, 1, 2, 2, 2, 1)] + [InlineData(2, 1, 4, 2, 4, 1)] + [InlineData(81, 1, 1, 2, 9, 1)] + [InlineData(81, 1, 1, 4, 3, 1)] + [InlineData(81, 1, 1, 10, 155184557391536, 100000000000000)] + public void PowRationalTests(BigInteger num, BigInteger den, BigInteger powerNum, BigInteger powerDen, BigInteger expectedNum, BigInteger expectedDen) + { + var value = new QuantityValue(num, den); + var power = new QuantityValue(powerNum, powerDen); + var expected = new QuantityValue(expectedNum, expectedDen); + Assert.Equal(expected, QuantityValue.Pow(value, power, 15)); + } + + [Theory] + [InlineData(double.NaN, -3, double.NaN)] + [InlineData(double.NaN, -2, double.NaN)] + [InlineData(double.NaN, -1, double.NaN)] + [InlineData(double.NaN, 0, 1)] + [InlineData(double.NaN, 1, double.NaN)] + [InlineData(double.NaN, 2, double.NaN)] + [InlineData(double.NaN, 3, double.NaN)] + [InlineData(double.PositiveInfinity, -3, 0)] + [InlineData(double.PositiveInfinity, -2, 0)] + [InlineData(double.PositiveInfinity, -1, 0)] + [InlineData(double.PositiveInfinity, 0, 1)] + [InlineData(double.PositiveInfinity, 1, double.PositiveInfinity)] + [InlineData(double.PositiveInfinity, 2, double.PositiveInfinity)] + [InlineData(double.NegativeInfinity, -3, 0)] + [InlineData(double.NegativeInfinity, -2, 0)] + [InlineData(double.NegativeInfinity, -1, 0)] + [InlineData(double.NegativeInfinity, 0, 1)] + [InlineData(double.NegativeInfinity, 1, double.NegativeInfinity)] + [InlineData(double.NegativeInfinity, 2, double.PositiveInfinity)] + [InlineData(double.NegativeInfinity, 3, double.NegativeInfinity)] + public void PowRationalWithNaNOrInfinityTests(double number, double power, double expectedResult) + { + var result = QuantityValue.Pow(number, power); +#if NET + Assert.Equal(double.Pow(number, power), result.ToDouble()); +#endif + Assert.Equal(expectedResult, result); + } + + [Fact] + public void Sqrt_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + Assert.Throws(() => QuantityValue.Sqrt(QuantityValue.One, -1)); + } + + [Theory] + [InlineData(double.NaN)] + [InlineData(double.PositiveInfinity)] + [InlineData(double.NegativeInfinity)] + [InlineData(-1)] + [InlineData(0)] + [InlineData(1)] + public void Sqrt_WithSpecialValues_MatchesTheOutputOfMathSqrt(double doubleValue) + { + var expected = Math.Sqrt(doubleValue); + + var actual = QuantityValue.Sqrt(doubleValue); + + Assert.Equal(expected, actual); + } + + [Theory] + [InlineData(0.1)] + [InlineData(12.34)] + [InlineData(0.01234)] + [InlineData(123.45)] + [InlineData(0.0012345)] + public void Sqrt_WithLowAccuracy_MatchesTheOutputOfMathSqrt(double doubleValue) + { + var expected = Math.Sqrt(doubleValue); + + var actual = QuantityValue.Sqrt(doubleValue, 15); + + Assert.Equal(expected, actual.ToDouble(), 15); + } + + [Theory] + [InlineData(2, 1, 5)] + [InlineData(10, 1, 5)] + [InlineData(30, 20, 5)] + [InlineData(4, 3, 5)] + [InlineData(5, 3, 5)] + [InlineData(12345678, 9, 5)] // reduced to 1371742/1 + [InlineData(123456789, 2, 7)] + [InlineData(1, 2, 5)] + [InlineData(1, 3, 5)] + [InlineData(1, 10, 5)] + [InlineData(2, 3, 5)] + [InlineData(20, 30, 5)] + [InlineData(9, 12345678, 5)] // reduced to 1/1371742 + [InlineData(2, 123456789, 7)] + public void Sqrt_WithExactRoot_CalculatesExactly(int numerator, int denominator, int accuracy) + { + var expectedValue = new QuantityValue(numerator, denominator); + var quantityValue = expectedValue * expectedValue; + + var actualValue = QuantityValue.Sqrt(quantityValue, accuracy); + + Assert.Equal(expectedValue, actualValue); + } + + [Fact] + public void Sqrt_ReturnsNoLessThanTheSpecifiedNumberOfCorrectDigits() + { + // these are the first 100 decimal places (from http://www.numberworld.org/digits/Sqrt(2)/) + const string firstOneHundredDecimals = "1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727"; + var expected = QuantityValue.Parse(firstOneHundredDecimals, CultureInfo.InvariantCulture); + Assert.All(Enumerable.Range(1, 100), digits => + { + var result = QuantityValue.Sqrt(2, digits); + AssertEx.EqualTolerance(expected, result, new QuantityValue(1, BigInteger.Pow(10, digits))); + }); + } + + [Fact] + public void Sqrt_ReturnsMoreThanTheSpecifiedNumberOfDigits() + { + // Sqrt(2, 1) ~= 14/10, Sqrt(2, 2) ~= 141/100.. Sqrt(2, n) = a/b with len(a) ~= n + var tolerance = new QuantityValue(2038, 10000); // ~20.38% + Assert.All(Enumerable.Range(1, 1000), digits => + { + var result = QuantityValue.Sqrt(2, digits); + var (numerator, _) = result; + AssertEx.EqualTolerance(digits + 1, numerator.ToString().Length, tolerance); + }); + } + + [Fact] + public void Sqrt_WithVeryPreciseQuantityValue_CalculatesCorrectly() + { + // Arrange: a very precise quantity value ~ {0.3160846809101182} + var numerator = BigInteger.Parse( + "7017075566499415481183895525487656110361817123500083731653571771256593466607002465509486669805631606869622837818618382797847715440102824717432866745242640865976075222884078899654447525335854152217507362365722656250000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); + var denominator = BigInteger.Parse( + "22199986238797791147406259737557652523540869928960600626046611277198843489042928693958126769955174387224059480985453176875329090776309059513483264000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); + var quantityValue = new QuantityValue(numerator, denominator); + // Act + var result = QuantityValue.Sqrt(quantityValue, 5); + // Assert + AssertEx.EqualTolerance(result, 0.56m, 0.1); +#if NET + Assert.Equal(573312, result.Numerator); + Assert.Equal(1019740, result.Denominator); +#else + // since we don't have access to BigInteger.GetBitLength we are slightly more conservative (using a larger shift) + Assert.Equal(1146624, result.Numerator); + Assert.Equal(2039480, result.Denominator); +#endif + } + + [Theory] + [InlineData(2, 1)] + [InlineData(10, 1)] + [InlineData(30, 20)] + [InlineData(200, 300)] + [InlineData(1234, 56789)] + public void Sqrt_WithVeryLargeValue_CalculatesCorrectly(int numeratorScale, int denominatorScale) + { + var expectedValue = new QuantityValue(numeratorScale, denominatorScale) * double.MaxValue; + var quantityValue = expectedValue * expectedValue; + + var actualValue = QuantityValue.Sqrt(quantityValue, 190); // double.MaxValue ~= 1.8e308 but the exact value is found early + + Assert.Equal(expectedValue, actualValue); + } + + [Theory] + [InlineData(1, 2)] + [InlineData(1, 10)] + [InlineData(20, 30)] + [InlineData(200, 300)] + [InlineData(1234, 56789)] + public void Sqrt_WithVerySmallValue_CalculatesCorrectly(int numeratorScale, int denominatorScale) + { + var expectedValue = new QuantityValue(numeratorScale, denominatorScale) / double.MaxValue; + var quantityValue = expectedValue * expectedValue; + + var actualValue = QuantityValue.Sqrt(quantityValue, 190); // double.MaxValue ~= 1.8e308 but the exact value is found early + + Assert.Equal(expectedValue, actualValue); + } + + [Theory] + [InlineData(2)] + [InlineData(20)] + [InlineData(300000)] + [InlineData(9007199254740993)] + [InlineData(long.MaxValue)] + [InlineData(ulong.MaxValue)] + public void Sqrt_WithWholeNumber_CalculatesWithTheSpecifiedAccuracy(ulong expectedValue) + { + var squaredValue = BigInteger.Pow(expectedValue, 2); + var expectedString = expectedValue.ToString("G"); + var maxDigits = expectedString.Length; + + for (var digits = 1; digits < maxDigits; digits++) + { + var result = QuantityValue.Sqrt(squaredValue, digits); + + if (result == expectedValue) + { + break; // the extra digits happened to be correct (compounding probability) + } + + AssertEx.EqualTolerance(expectedValue, result, new QuantityValue(1, BigInteger.Pow(10, digits))); + } + + Assert.Equal(expectedValue, QuantityValue.Sqrt(squaredValue, maxDigits)); + } + + [Theory] + [InlineData(1)] + [InlineData(20)] + [InlineData(300000)] + [InlineData(9007199254740993)] + [InlineData(long.MaxValue)] + [InlineData(ulong.MaxValue)] + public void Sqrt_WithLargeWholeNumber_CalculatesWithTheSpecifiedAccuracy(ulong scale) + { + var expectedValue = scale * (BigInteger)double.MaxValue; + var squaredValue = BigInteger.Pow(expectedValue, 2); + var expectedString = expectedValue.ToString("G"); + var maxDigits = expectedString.Length; + + for (var digits = 1; digits < maxDigits; digits++) + { + var result = QuantityValue.Sqrt(squaredValue, digits); + + if (result == expectedValue) + { + break; // the extra digits happened to be correct (compounding probability) + } + + AssertEx.EqualTolerance(expectedValue, result, new QuantityValue(1, BigInteger.Pow(10, digits))); + } + + Assert.Equal(expectedValue, QuantityValue.Sqrt(squaredValue, maxDigits)); + } + + [Theory] + // (x, -3) + [InlineData(-3, -3, -0.693361274350635)] + [InlineData(-2, -3, -0.7937005259841)] + [InlineData(-1, -3, -1)] + [InlineData(0, -3, double.PositiveInfinity)] + [InlineData(1, -3, 1)] + [InlineData(2, -3, 0.7937005259841)] + [InlineData(3, -3, 0.693361274350635)] + // (x, -2) + [InlineData(-3, -2, double.NaN)] + [InlineData(-2, -2, double.NaN)] + [InlineData(-1, -2, double.NaN)] + [InlineData(0, -2, double.PositiveInfinity)] + [InlineData(1, -2, 1)] + [InlineData(2, -2, 0.70710678118654802)] + [InlineData(3, -2, 0.577350269189626)] + // (x, -1) + [InlineData(-3, -1, -0.333333333333333)] + [InlineData(-2, -1, -0.5)] + [InlineData(-1, -1, -1)] + [InlineData(0, -1, double.PositiveInfinity)] + [InlineData(1, -1, 1)] + [InlineData(2, -1, 0.5)] + [InlineData(3, -1, 0.333333333333333)] + // (x, 0) + [InlineData(-3, 0, double.NaN)] // NaN + [InlineData(-2, 0, double.NaN)] // NaN + [InlineData(-1, 0, double.NaN)] // NaN + [InlineData(0, 0, double.NaN)] // NaN + [InlineData(1, 0, double.NaN)] // NaN + [InlineData(2, 0, double.NaN)] // NaN + [InlineData(3, 0, double.NaN)] // NaN + // (x, 1) + [InlineData(-3, 1, -3)] + [InlineData(-2, 1, -2)] + [InlineData(-1, 1, -1)] + [InlineData(0, 1, 0)] + [InlineData(1, 1, 1)] + [InlineData(2, 1, 2)] + [InlineData(3, 1, 3)] + // (x, 2) + [InlineData(-3, 2, double.NaN)] + [InlineData(-2, 2, double.NaN)] + [InlineData(-1, 2, double.NaN)] + [InlineData(0, 2, 0)] + [InlineData(1, 2, 1)] + [InlineData(2, 2, 1.414213562373095)] + [InlineData(3, 2, 1.732050807568877)] + // (x, 3) + [InlineData(-3, 3, -1.4422495703074081)] + [InlineData(-2, 3, -1.259921049894873)] + [InlineData(-1, 3, -1)] + [InlineData(0, 3, 0)] + [InlineData(1, 3, 1)] + [InlineData(2, 3, 1.259921049894873)] + [InlineData(3, 3, 1.4422495703074081)] + [InlineData(8, 3, 2)] + [InlineData(27, 3, 3)] + // (x, 4) + [InlineData(16, 4, 2)] + [InlineData(0.0625, 4, 0.5)] + public void RootTests(double number, int root, double expectedValue) + { + QuantityValue quantityValue = number; + + var result = QuantityValue.RootN(quantityValue, root); +#if NET + Assert.Equal(double.RootN(number, root), result.ToDouble(), 15); +#endif + Assert.Equal(expectedValue, result.ToDouble(), 15); + } + + [Theory] + [InlineData(double.NaN, -3, double.NaN)] + [InlineData(double.NaN, -2, double.NaN)] + [InlineData(double.NaN, -1, double.NaN)] + [InlineData(double.NaN, 0, double.NaN)] + [InlineData(double.NaN, 1, double.NaN)] + [InlineData(double.NaN, 2, double.NaN)] + [InlineData(double.NaN, 3, double.NaN)] + [InlineData(double.PositiveInfinity, -3, 0)] + [InlineData(double.PositiveInfinity, -2, 0)] + [InlineData(double.PositiveInfinity, -1, 0)] + [InlineData(double.PositiveInfinity, 0, double.NaN)] + [InlineData(double.PositiveInfinity, 1, double.PositiveInfinity)] + [InlineData(double.PositiveInfinity, 2, double.PositiveInfinity)] + [InlineData(double.NegativeInfinity, -3, 0)] + [InlineData(double.NegativeInfinity, -2, double.NaN)] + [InlineData(double.NegativeInfinity, -1, 0)] + [InlineData(double.NegativeInfinity, 0, double.NaN)] + [InlineData(double.NegativeInfinity, 1, double.NegativeInfinity)] + [InlineData(double.NegativeInfinity, 2, double.NaN)] + [InlineData(double.NegativeInfinity, 3, double.NegativeInfinity)] + public void RootWithNaNOrInfinityTests(double number, int root, double expectedResult) + { + var result = QuantityValue.RootN(number, root); +#if NET + Assert.Equal(double.RootN(number, root), result.ToDouble()); +#endif + Assert.Equal(expectedResult, result); + } + + [Fact] + public void RootWithNegativeAccuracyThrowsArgumentOutOfRangeException() + { + Assert.Throws(() => QuantityValue.RootN(1, 1, -1)); + } + } +} diff --git a/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.QuantityValueTypeConverter.cs b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.QuantityValueTypeConverter.cs new file mode 100644 index 0000000000..e18c0b7b8d --- /dev/null +++ b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.QuantityValueTypeConverter.cs @@ -0,0 +1,254 @@ +using System.Globalization; +using System.Numerics; +using JetBrains.Annotations; + +namespace UnitsNet.Tests; + +public partial class QuantityValueTests +{ + [TestSubject(typeof(QuantityValueTypeConverter))] + public class TypeConverterTests + { + [Theory] + [InlineData(typeof(string), true)] + [InlineData(typeof(int), true)] + [InlineData(typeof(long), true)] + [InlineData(typeof(decimal), true)] + [InlineData(typeof(double), true)] + [InlineData(typeof(QuantityValue), true)] + [InlineData(typeof(BigInteger), true)] + [InlineData(typeof(object), false)] + public void CanConvertTo_ReturnsExpectedResult(Type destinationType, bool expected) + { + var converter = new QuantityValueTypeConverter(); + Assert.Equal(expected, converter.CanConvertTo(null, destinationType)); + } + + [Theory] + [InlineData(typeof(string), true)] + [InlineData(typeof(int), true)] + [InlineData(typeof(long), true)] + [InlineData(typeof(decimal), true)] + [InlineData(typeof(double), true)] + [InlineData(typeof(QuantityValue), true)] + [InlineData(typeof(BigInteger), true)] + [InlineData(typeof(object), false)] + public void CanConvertFrom_ReturnsExpectedResult(Type sourceType, bool expected) + { + var converter = new QuantityValueTypeConverter(); + Assert.Equal(expected, converter.CanConvertFrom(null, sourceType)); + } + + [Fact] + public void ConvertTo_String() + { + // Arrange + var converter = new QuantityValueTypeConverter(); + var quantityValue = new QuantityValue(123.45m); + // Act + var result = converter.ConvertTo(null, CultureInfo.InvariantCulture, quantityValue, typeof(string)); + // Assert + Assert.Equal("123.45", result); + } + + [Fact] + public void ConvertTo_Int() + { + // Arrange + var converter = new QuantityValueTypeConverter(); + var quantityValue = new QuantityValue(123m); + // Act + var result = converter.ConvertTo(null, CultureInfo.InvariantCulture, quantityValue, typeof(int)); + // Assert + Assert.Equal(123, result); + } + + [Fact] + public void ConvertTo_Long() + { + // Arrange + var converter = new QuantityValueTypeConverter(); + var quantityValue = new QuantityValue(123L); + // Act + var result = converter.ConvertTo(null, CultureInfo.InvariantCulture, quantityValue, typeof(long)); + // Assert + Assert.Equal(123L, result); + } + + [Fact] + public void ConvertTo_Decimal() + { + // Arrange + var converter = new QuantityValueTypeConverter(); + var quantityValue = new QuantityValue(123.45m); + // Act + var result = converter.ConvertTo(null, CultureInfo.InvariantCulture, quantityValue, typeof(decimal)); + // Assert + Assert.Equal(123.45m, result); + } + + [Fact] + public void ConvertTo_Double() + { + // Arrange + var converter = new QuantityValueTypeConverter(); + var quantityValue = new QuantityValue(123.45m); + // Act + var result = converter.ConvertTo(null, CultureInfo.InvariantCulture, quantityValue, typeof(double)); + // Assert + Assert.Equal(123.45, result); + } + + [Fact] + public void ConvertTo_BigInteger() + { + // Arrange + var converter = new QuantityValueTypeConverter(); + var quantityValue = new QuantityValue(123.45m); + // Act + var result = converter.ConvertTo(null, CultureInfo.InvariantCulture, quantityValue, typeof(BigInteger)); + // Assert + Assert.Equal(new BigInteger(123), result); + } + + [Fact] + public void ConvertTo_QuantityValue() + { + // Arrange + var converter = new QuantityValueTypeConverter(); + var quantityValue = new QuantityValue(123.45m); + // Act + var result = converter.ConvertTo(null, CultureInfo.InvariantCulture, quantityValue, typeof(QuantityValue)); + // Assert + Assert.Equal(quantityValue, result); + } + + [Fact] + public void ConvertFrom_Null() + { + // Arrange + var converter = new QuantityValueTypeConverter(); + // Act + var result = converter.ConvertFrom(null, CultureInfo.InvariantCulture, null); + // Assert + Assert.Equal(QuantityValue.Zero, result); + } + + [Fact] + public void ConvertFrom_String() + { + // Arrange + var converter = new QuantityValueTypeConverter(); + var expectedValue = new QuantityValue(123.45m); + // Act + var result = converter.ConvertFrom(null, CultureInfo.InvariantCulture, "123.45"); + // Assert + Assert.Equal(expectedValue, result); + } + + [Fact] + public void ConvertFrom_Int() + { + // Arrange + var converter = new QuantityValueTypeConverter(); + var expectedValue = new QuantityValue(123); + // Act + var result = converter.ConvertFrom(null, CultureInfo.InvariantCulture, 123); + // Assert + Assert.Equal(expectedValue, result); + } + + [Fact] + public void ConvertFrom_Long() + { + // Arrange + var converter = new QuantityValueTypeConverter(); + var expectedValue = new QuantityValue(123); + // Act + var result = converter.ConvertFrom(null, CultureInfo.InvariantCulture, 123L); + // Assert + Assert.Equal(expectedValue, result); + } + + [Fact] + public void ConvertFrom_Decimal() + { + // Arrange + var converter = new QuantityValueTypeConverter(); + var expectedValue = new QuantityValue(123.45m); + // Act + var result = converter.ConvertFrom(null, CultureInfo.InvariantCulture, 123.45m); + // Assert + Assert.Equal(expectedValue, result); + } + + [Fact] + public void ConvertFrom_Double() + { + // Arrange + var converter = new QuantityValueTypeConverter(); + QuantityValue expectedValue = 123.45; + // Act + var result = converter.ConvertFrom(null, CultureInfo.InvariantCulture, 123.45); + // Assert + Assert.Equal(expectedValue, result); + } + + [Fact] + public void ConvertFrom_BigInteger() + { + // Arrange + var converter = new QuantityValueTypeConverter(); + QuantityValue expectedValue = 123; + // Act + var result = converter.ConvertFrom(null, CultureInfo.InvariantCulture, new BigInteger(123)); + // Assert + Assert.Equal(expectedValue, result); + } + + [Fact] + public void ConvertFrom_QuantityValue() + { + // Arrange + var converter = new QuantityValueTypeConverter(); + QuantityValue inputValue = 123; + // Act + var result = converter.ConvertFrom(null, CultureInfo.InvariantCulture, inputValue); + // Assert + Assert.Equal(inputValue, result); + } + + [Fact] + public void ConvertFrom_Null_Returns_Zero() + { + // Arrange + var converter = new QuantityValueTypeConverter(); + // Act + var result = converter.ConvertFrom(null, CultureInfo.InvariantCulture, null); + // Assert + Assert.Equal(QuantityValue.Zero, result); + } + + [Fact] + public void ConvertTo_InvalidConversions_ThrowsException() + { + var converter = new QuantityValueTypeConverter(); + var quantityValue = new QuantityValue(123.45m); + Assert.Throws(() => converter.ConvertTo(null, CultureInfo.InvariantCulture, quantityValue, typeof(DateTime))); + } + + [Fact] + public void ConvertTo_WithNull_ThrowsException() + { + var converter = new QuantityValueTypeConverter(); + Assert.Throws(() => converter.ConvertTo(null, CultureInfo.InvariantCulture, null, typeof(decimal))); + } + + [Fact] + public void ConvertFrom_InvalidConversions_ThrowsException() + { + var converter = new QuantityValueTypeConverter(); + Assert.Throws(() => converter.ConvertFrom(null, CultureInfo.InvariantCulture, DateTime.MinValue)); + } + } +} \ No newline at end of file diff --git a/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.Rounding.cs b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.Rounding.cs new file mode 100644 index 0000000000..79478ee48f --- /dev/null +++ b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.Rounding.cs @@ -0,0 +1,102 @@ +using System.Numerics; + +namespace UnitsNet.Tests; + +public partial class QuantityValueTests +{ + public class RoundingTests + { + private static readonly QuantityValueData[] DecimalFractions = [ + 0, 1, -1, 10, -10, + 0.5m, -0.5m, 0.55m, -0.55m, 1.5m, -1.5m, 1.55m, -1.55m, + 0.1m, -0.1m, 0.15m, -0.15m, 1.2m, -1.2m, 1.25m, -1.25m, + 1.5545665434654m, -1.5545665434654m, + 15.545665434654m, -15.545665434654m, + 155.45665434654m, -155.45665434654m, + 1554.5665434654m, -1554.5665434654m, + 15545.665434654m, -15545.665434654m, + 155456.65434654m, -155456.65434654m, + new QuantityValue(1, 3), new QuantityValue(-1, 3), + new QuantityValue(2, 3), new QuantityValue(-2, 3), + new QuantityValue(1999999999999999991, 3), new QuantityValue(-1999999999999999991, 3), + new QuantityValue(2000000000000000001, 3), new QuantityValue(-2000000000000000001, 3), + ]; + + private static readonly MidpointRounding[] RoundingModes = [ + MidpointRounding.ToEven, + MidpointRounding.AwayFromZero, +#if NET + MidpointRounding.ToZero, + MidpointRounding.ToNegativeInfinity, + MidpointRounding.ToPositiveInfinity +#endif + ]; + + public sealed class BigIntegerTestCases : TheoryData + { + public BigIntegerTestCases() + { + foreach (var roundingMode in RoundingModes) + { + foreach (var decimalFraction in DecimalFractions) + { + Add(decimalFraction, roundingMode, (BigInteger)Math.Round(decimalFraction.Value.ToDecimal(), roundingMode)); + } + } + } + } + + [Theory] + [ClassData(typeof(BigIntegerTestCases))] + public void RoundToBigInteger_ReturnsTheExpectedResult(QuantityValueData value, MidpointRounding mode, BigInteger expected) + { + Assert.Equal(expected, QuantityValue.Round(value, mode)); + } + + [Fact] + public void RoundToBigInteger_Given_NaN_or_Infinity_ThrowsDivideByZeroException() + { + Assert.Throws(() => QuantityValue.Round(QuantityValue.NaN, MidpointRounding.ToEven)); + Assert.Throws(() => QuantityValue.Round(QuantityValue.PositiveInfinity, MidpointRounding.ToEven)); + Assert.Throws(() => QuantityValue.Round(QuantityValue.NegativeInfinity, MidpointRounding.ToEven)); + } + + [Fact] + public void RoundToBigInteger_WithInvalidRoundingMode_ThrowsArgumentOutOfRangeException() + { + Assert.Throws(() => QuantityValue.Round(new QuantityValue(1, 2), (MidpointRounding)5)); + } + + [Fact] + public void Round_ToNegativeDecimals_ThrowsArgumentOutOfRangeException() + { + Assert.Throws(() => QuantityValue.Round(new QuantityValue(1, 2), -1)); + } + + public sealed class DecimalFractionsFractionTestCases : TheoryData + { + private static readonly int[] DecimalPlaces = Enumerable.Range(0, 6).ToArray(); + + public DecimalFractionsFractionTestCases() + { + foreach (var roundingMode in RoundingModes) + { + foreach (var nbDecimals in DecimalPlaces) + { + foreach (var decimalFraction in DecimalFractions) + { + Add(decimalFraction, roundingMode, nbDecimals, Math.Round(decimalFraction.Value.ToDecimal(), nbDecimals, roundingMode)); + } + } + } + } + } + + [Theory] + [ClassData(typeof(DecimalFractionsFractionTestCases))] + public void Round_ReturnsTheExpectedResult(QuantityValueData value, MidpointRounding mode, int decimals, QuantityValueData expected) + { + Assert.Equal(expected.Value, QuantityValue.Round(value.Value, decimals, mode)); + } + } +} diff --git a/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.cs b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.cs new file mode 100644 index 0000000000..4d426132de --- /dev/null +++ b/UnitsNet.Tests/CustomCode/ValueTests/QuantityValueTests.cs @@ -0,0 +1,359 @@ +// 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.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Numerics; +using JetBrains.Annotations; +using Xunit.Abstractions; + +namespace UnitsNet.Tests; + +[TestSubject(typeof(QuantityValue))] +public static partial class QuantityValueTests +{ + public class QuantityValueData : IXunitSerializable + { + private QuantityValue _value; + + public QuantityValueData() + { + // empty constructor + } + + public QuantityValueData(QuantityValue value) + { + _value = value; + } + + public static implicit operator QuantityValue(QuantityValueData data) + { + return data._value; + } + + public static implicit operator QuantityValueData(QuantityValue value) + { + return new QuantityValueData(value); + } + + public static implicit operator QuantityValueData(int value) + { + return new QuantityValueData(value); + } + + public static implicit operator QuantityValueData(decimal value) + { + return new QuantityValueData(value); + } + + public static implicit operator QuantityValueData(double value) + { + return new QuantityValueData(value); + } + + public QuantityValue Value => _value; + + #region Implementation of IXunitSerializable + + public void Serialize(IXunitSerializationInfo info) + { + info.AddValue("Numerator", _value.Numerator); + info.AddValue("Denominator", _value.Denominator); + } + + public void Deserialize(IXunitSerializationInfo info) + { + var numerator = info.GetValue("Numerator"); + var denominator = info.GetValue("Denominator"); + _value = new QuantityValue(numerator, denominator); + } + + #endregion + + public override string ToString() + { + return $"{Value.Numerator}/{Value.Denominator}"; + } + } + +#if NET + /// + /// Represents a fake number implementation for testing purposes. + /// + /// + /// This class is used internally within the test suite to simulate a number type that implements the + /// interface. + /// It provides functionality to test conversions and operations involving custom number types. + /// +#pragma warning disable CA1067, CS0660 + private class FakeNumber : INumberBase +#pragma warning restore CS0660, CA1067 + { + public static FakeNumber Zero { get; } = new(); + + static bool INumberBase.TryConvertFromChecked(TOther value, [MaybeNullWhen(false)] out FakeNumber result) + { + result = null; + return false; + } + + static bool INumberBase.TryConvertFromSaturating(TOther value, [MaybeNullWhen(false)] out FakeNumber result) + { + result = null; + return false; + } + + static bool INumberBase.TryConvertFromTruncating(TOther value, [MaybeNullWhen(false)] out FakeNumber result) + { + result = null; + return false; + } + + static bool INumberBase.TryConvertToChecked(FakeNumber value, [MaybeNullWhen(false)] out TOther result) + { + result = default; + return false; + } + + static bool INumberBase.TryConvertToSaturating(FakeNumber value, [MaybeNullWhen(false)] out TOther result) + { + result = default; + return false; + } + + static bool INumberBase.TryConvertToTruncating(FakeNumber value, [MaybeNullWhen(false)] out TOther result) + { + result = default; + return false; + } + + #region Other interface members (not implemented) + + bool IEquatable.Equals(FakeNumber? other) + { + throw new NotImplementedException(); + } + + string IFormattable.ToString(string? format, IFormatProvider? formatProvider) + { + throw new NotImplementedException(); + } + + bool ISpanFormattable.TryFormat(Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider? provider) + { + throw new NotImplementedException(); + } + + static FakeNumber IParsable.Parse(string s, IFormatProvider? provider) + { + throw new NotImplementedException(); + } + + static bool IParsable.TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, [MaybeNullWhen(false)] out FakeNumber result) + { + throw new NotImplementedException(); + } + + static FakeNumber ISpanParsable.Parse(ReadOnlySpan s, IFormatProvider? provider) + { + throw new NotImplementedException(); + } + + static bool ISpanParsable.TryParse(ReadOnlySpan s, IFormatProvider? provider, [MaybeNullWhen(false)] out FakeNumber result) + { + throw new NotImplementedException(); + } + + + static FakeNumber IAdditionOperators.operator +(FakeNumber left, FakeNumber right) + { + throw new NotImplementedException(); + } + + static FakeNumber IAdditiveIdentity.AdditiveIdentity { get; } = new(); + + static FakeNumber IDecrementOperators.operator --(FakeNumber value) + { + throw new NotImplementedException(); + } + + static FakeNumber IDivisionOperators.operator /(FakeNumber left, FakeNumber right) + { + throw new NotImplementedException(); + } + + static bool IEqualityOperators.operator ==(FakeNumber? left, FakeNumber? right) + { + throw new NotImplementedException(); + } + + static bool IEqualityOperators.operator !=(FakeNumber? left, FakeNumber? right) + { + throw new NotImplementedException(); + } + + static FakeNumber IIncrementOperators.operator ++(FakeNumber value) + { + throw new NotImplementedException(); + } + + static FakeNumber IMultiplicativeIdentity.MultiplicativeIdentity { get; } = new(); + + static FakeNumber IMultiplyOperators.operator *(FakeNumber left, FakeNumber right) + { + throw new NotImplementedException(); + } + + static FakeNumber ISubtractionOperators.operator -(FakeNumber left, FakeNumber right) + { + throw new NotImplementedException(); + } + + static FakeNumber IUnaryNegationOperators.operator -(FakeNumber value) + { + throw new NotImplementedException(); + } + + static FakeNumber IUnaryPlusOperators.operator +(FakeNumber value) + { + throw new NotImplementedException(); + } + + static FakeNumber INumberBase.Abs(FakeNumber value) + { + throw new NotImplementedException(); + } + + static bool INumberBase.IsCanonical(FakeNumber value) + { + throw new NotImplementedException(); + } + + static bool INumberBase.IsComplexNumber(FakeNumber value) + { + throw new NotImplementedException(); + } + + static bool INumberBase.IsEvenInteger(FakeNumber value) + { + throw new NotImplementedException(); + } + + static bool INumberBase.IsFinite(FakeNumber value) + { + throw new NotImplementedException(); + } + + static bool INumberBase.IsImaginaryNumber(FakeNumber value) + { + throw new NotImplementedException(); + } + + static bool INumberBase.IsInfinity(FakeNumber value) + { + throw new NotImplementedException(); + } + + static bool INumberBase.IsInteger(FakeNumber value) + { + throw new NotImplementedException(); + } + + static bool INumberBase.IsNaN(FakeNumber value) + { + throw new NotImplementedException(); + } + + static bool INumberBase.IsNegative(FakeNumber value) + { + throw new NotImplementedException(); + } + + static bool INumberBase.IsNegativeInfinity(FakeNumber value) + { + throw new NotImplementedException(); + } + + static bool INumberBase.IsNormal(FakeNumber value) + { + throw new NotImplementedException(); + } + + static bool INumberBase.IsOddInteger(FakeNumber value) + { + throw new NotImplementedException(); + } + + static bool INumberBase.IsPositive(FakeNumber value) + { + throw new NotImplementedException(); + } + + static bool INumberBase.IsPositiveInfinity(FakeNumber value) + { + throw new NotImplementedException(); + } + + static bool INumberBase.IsRealNumber(FakeNumber value) + { + throw new NotImplementedException(); + } + + static bool INumberBase.IsSubnormal(FakeNumber value) + { + throw new NotImplementedException(); + } + + static bool INumberBase.IsZero(FakeNumber value) + { + throw new NotImplementedException(); + } + + static FakeNumber INumberBase.MaxMagnitude(FakeNumber x, FakeNumber y) + { + throw new NotImplementedException(); + } + + static FakeNumber INumberBase.MaxMagnitudeNumber(FakeNumber x, FakeNumber y) + { + throw new NotImplementedException(); + } + + static FakeNumber INumberBase.MinMagnitude(FakeNumber x, FakeNumber y) + { + throw new NotImplementedException(); + } + + static FakeNumber INumberBase.MinMagnitudeNumber(FakeNumber x, FakeNumber y) + { + throw new NotImplementedException(); + } + + static FakeNumber INumberBase.Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider) + { + throw new NotImplementedException(); + } + + static FakeNumber INumberBase.Parse(string s, NumberStyles style, IFormatProvider? provider) + { + throw new NotImplementedException(); + } + + static bool INumberBase.TryParse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider, [MaybeNullWhen(false)] out FakeNumber result) + { + throw new NotImplementedException(); + } + + static bool INumberBase.TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, [MaybeNullWhen(false)] out FakeNumber result) + { + throw new NotImplementedException(); + } + + static FakeNumber INumberBase.One { get; } = new(); + static int INumberBase.Radix { get; } = 10; + + #endregion + } + +#endif +} \ No newline at end of file diff --git a/UnitsNet.Tests/CustomQuantities/HowMuch.cs b/UnitsNet.Tests/CustomQuantities/HowMuch.cs index 026d1ec5fb..56070970d4 100644 --- a/UnitsNet.Tests/CustomQuantities/HowMuch.cs +++ b/UnitsNet.Tests/CustomQuantities/HowMuch.cs @@ -9,41 +9,39 @@ namespace UnitsNet.Tests.CustomQuantities /// public readonly struct HowMuch : IQuantity { - public HowMuch(double value, HowMuchUnit unit) + public HowMuch(QuantityValue value, HowMuchUnit unit) { Unit = unit; Value = value; } - - public static HowMuch From(double value, HowMuchUnit unit) + + public static HowMuch From(QuantityValue value, HowMuchUnit unit) { return new HowMuch(value, unit); } - public double As(HowMuchUnit unit) - { - throw new NotImplementedException(); - } - public HowMuchUnit Unit { get; } - public double Value { get; } + public QuantityValue Value { get; } + #region IQuantity - + public static readonly QuantityInfo Info = new( nameof(HowMuch), HowMuchUnit.Some, new UnitDefinition[] { new(HowMuchUnit.Some, "Some", BaseUnits.Undefined), - new(HowMuchUnit.ATon, "Tons", new BaseUnits(mass: MassUnit.Tonne)), - new(HowMuchUnit.AShitTon, "ShitTons", BaseUnits.Undefined) + new(HowMuchUnit.ATon, "Tons", new BaseUnits(mass: MassUnit.Tonne), new QuantityValue(1, 10)), + new(HowMuchUnit.AShitTon, "ShitTons", BaseUnits.Undefined, new QuantityValue(1, 100)) }, new HowMuch(0, HowMuchUnit.Some), new BaseDimensions(0, 1, 0, 0, 0, 0, 0), From); + public BaseDimensions Dimensions => Info.BaseDimensions; + QuantityInfo IQuantity.QuantityInfo { get => Info; @@ -59,59 +57,62 @@ QuantityInfo IQuantity.QuantityInfo get => Info; } - public BaseDimensions Dimensions => Info.BaseDimensions; - - UnitKey IQuantity.UnitKey { get => UnitKey.ForUnit(Unit); } - public double As(Enum unit) => Convert.ToDouble(unit); - public double As(UnitKey unitKey) + public override string ToString() { - return As(unitKey.ToUnit()); + return $"{Value} {Unit}"; } - public double As(UnitSystem unitSystem) => throw new NotImplementedException(); + public string ToString(string? format, IFormatProvider? formatProvider) + { + return $"HowMuch ({format}, {formatProvider})"; + } - public IQuantity ToUnit(Enum unit) +#if !NET + // all the following methods have a default interface implementation for net8.0 and above + IQuantityInstanceInfo IQuantityOfType.QuantityInfo { - if (unit is HowMuchUnit howMuchUnit) return new HowMuch(As(unit), howMuchUnit); - throw new ArgumentException("Must be of type HowMuchUnit.", nameof(unit)); + get => Info; } - public IQuantity ToUnit(HowMuchUnit unit) + Enum IQuantity.Unit { - throw new NotImplementedException(); + get => Unit; } - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) + // all of these are now marked as obsolete + + QuantityValue IQuantity.As(Enum unit) { - throw new NotImplementedException(); + return UnitConverter.Default.ConvertValue(this, unit); } - public IQuantity ToUnit(UnitSystem unitSystem) => throw new NotImplementedException(); - - public override string ToString() + IQuantity IQuantity.ToUnit(Enum unit) { - return $"{Value} {Unit}"; + return UnitConverter.Default.ConvertTo(this, unit); } - public string ToString(string? format, IFormatProvider? formatProvider) + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) { - return $"HowMuch ({format}, {formatProvider})"; + return this.ToUnit(unitSystem); } -#if !NET + IQuantity IQuantity.ToUnit(HowMuchUnit unit) + { + return this.ToUnit(unit); + } - QuantityInfo IQuantity.QuantityInfo + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) { - get { return Info; } + return this.ToUnit(unitSystem); } - Enum IQuantity.Unit => Unit; #endif + #endregion } } diff --git a/UnitsNet.Tests/DisableParallelizationCollectionFixture.cs b/UnitsNet.Tests/DisableParallelizationCollectionFixture.cs index 71aeda5945..c0ba905ce2 100644 --- a/UnitsNet.Tests/DisableParallelizationCollectionFixture.cs +++ b/UnitsNet.Tests/DisableParallelizationCollectionFixture.cs @@ -1,4 +1,5 @@ using System.Globalization; +using UnitsNet.Tests.Helpers; using Xunit; namespace UnitsNet.Tests; diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AbsorbedDoseOfIonizingRadiationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AbsorbedDoseOfIonizingRadiationTestsBase.g.cs index 8ba1957189..f48b50e3dc 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AbsorbedDoseOfIonizingRadiationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AbsorbedDoseOfIonizingRadiationTestsBase.g.cs @@ -189,6 +189,20 @@ public void AbsorbedDoseOfIonizingRadiation_QuantityInfo_ReturnsQuantityInfoDesc Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void AbsorbedDoseOfIonizingRadiationInfo_CreateWithCustomUnitInfos() + { + AbsorbedDoseOfIonizingRadiationUnit[] expectedUnits = [AbsorbedDoseOfIonizingRadiationUnit.Gray]; + + AbsorbedDoseOfIonizingRadiation.AbsorbedDoseOfIonizingRadiationInfo quantityInfo = AbsorbedDoseOfIonizingRadiation.AbsorbedDoseOfIonizingRadiationInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("AbsorbedDoseOfIonizingRadiation", quantityInfo.Name); + Assert.Equal(AbsorbedDoseOfIonizingRadiation.Zero, quantityInfo.Zero); + Assert.Equal(AbsorbedDoseOfIonizingRadiation.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void GrayToAbsorbedDoseOfIonizingRadiationUnits() { @@ -405,7 +419,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 пГр", AbsorbedDoseOfIonizingRadiationUnit.Picogray, 4.2)] [InlineData("ru-RU", "4,2 рад", AbsorbedDoseOfIonizingRadiationUnit.Rad, 4.2)] [InlineData("ru-RU", "4,2 ТГр", AbsorbedDoseOfIonizingRadiationUnit.Teragray, 4.2)] - public void Parse(string culture, string quantityString, AbsorbedDoseOfIonizingRadiationUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, AbsorbedDoseOfIonizingRadiationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = AbsorbedDoseOfIonizingRadiation.Parse(quantityString); @@ -448,7 +462,7 @@ public void Parse(string culture, string quantityString, AbsorbedDoseOfIonizingR [InlineData("ru-RU", "4,2 пГр", AbsorbedDoseOfIonizingRadiationUnit.Picogray, 4.2)] [InlineData("ru-RU", "4,2 рад", AbsorbedDoseOfIonizingRadiationUnit.Rad, 4.2)] [InlineData("ru-RU", "4,2 ТГр", AbsorbedDoseOfIonizingRadiationUnit.Teragray, 4.2)] - public void TryParse(string culture, string quantityString, AbsorbedDoseOfIonizingRadiationUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, AbsorbedDoseOfIonizingRadiationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(AbsorbedDoseOfIonizingRadiation.TryParse(quantityString, out AbsorbedDoseOfIonizingRadiation parsed)); @@ -810,6 +824,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AbsorbedDoseOfIo var quantity = AbsorbedDoseOfIonizingRadiation.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -833,48 +848,50 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(AbsorbedDoseOfIoniz IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - AbsorbedDoseOfIonizingRadiation gray = AbsorbedDoseOfIonizingRadiation.FromGrays(1); - AssertEx.EqualTolerance(1, AbsorbedDoseOfIonizingRadiation.FromCentigrays(gray.Centigrays).Grays, CentigraysTolerance); - AssertEx.EqualTolerance(1, AbsorbedDoseOfIonizingRadiation.FromDecigrays(gray.Decigrays).Grays, DecigraysTolerance); - AssertEx.EqualTolerance(1, AbsorbedDoseOfIonizingRadiation.FromFemtograys(gray.Femtograys).Grays, FemtograysTolerance); - AssertEx.EqualTolerance(1, AbsorbedDoseOfIonizingRadiation.FromGigagrays(gray.Gigagrays).Grays, GigagraysTolerance); - AssertEx.EqualTolerance(1, AbsorbedDoseOfIonizingRadiation.FromGrays(gray.Grays).Grays, GraysTolerance); - AssertEx.EqualTolerance(1, AbsorbedDoseOfIonizingRadiation.FromKilograys(gray.Kilograys).Grays, KilograysTolerance); - AssertEx.EqualTolerance(1, AbsorbedDoseOfIonizingRadiation.FromKilorads(gray.Kilorads).Grays, KiloradsTolerance); - AssertEx.EqualTolerance(1, AbsorbedDoseOfIonizingRadiation.FromMegagrays(gray.Megagrays).Grays, MegagraysTolerance); - AssertEx.EqualTolerance(1, AbsorbedDoseOfIonizingRadiation.FromMegarads(gray.Megarads).Grays, MegaradsTolerance); - AssertEx.EqualTolerance(1, AbsorbedDoseOfIonizingRadiation.FromMicrograys(gray.Micrograys).Grays, MicrograysTolerance); - AssertEx.EqualTolerance(1, AbsorbedDoseOfIonizingRadiation.FromMilligrays(gray.Milligrays).Grays, MilligraysTolerance); - AssertEx.EqualTolerance(1, AbsorbedDoseOfIonizingRadiation.FromMillirads(gray.Millirads).Grays, MilliradsTolerance); - AssertEx.EqualTolerance(1, AbsorbedDoseOfIonizingRadiation.FromNanograys(gray.Nanograys).Grays, NanograysTolerance); - AssertEx.EqualTolerance(1, AbsorbedDoseOfIonizingRadiation.FromPetagrays(gray.Petagrays).Grays, PetagraysTolerance); - AssertEx.EqualTolerance(1, AbsorbedDoseOfIonizingRadiation.FromPicograys(gray.Picograys).Grays, PicograysTolerance); - AssertEx.EqualTolerance(1, AbsorbedDoseOfIonizingRadiation.FromRads(gray.Rads).Grays, RadsTolerance); - AssertEx.EqualTolerance(1, AbsorbedDoseOfIonizingRadiation.FromTeragrays(gray.Teragrays).Grays, TeragraysTolerance); + AbsorbedDoseOfIonizingRadiation gray = AbsorbedDoseOfIonizingRadiation.FromGrays(3); + Assert.Equal(3, AbsorbedDoseOfIonizingRadiation.FromCentigrays(gray.Centigrays).Grays); + Assert.Equal(3, AbsorbedDoseOfIonizingRadiation.FromDecigrays(gray.Decigrays).Grays); + Assert.Equal(3, AbsorbedDoseOfIonizingRadiation.FromFemtograys(gray.Femtograys).Grays); + Assert.Equal(3, AbsorbedDoseOfIonizingRadiation.FromGigagrays(gray.Gigagrays).Grays); + Assert.Equal(3, AbsorbedDoseOfIonizingRadiation.FromGrays(gray.Grays).Grays); + Assert.Equal(3, AbsorbedDoseOfIonizingRadiation.FromKilograys(gray.Kilograys).Grays); + Assert.Equal(3, AbsorbedDoseOfIonizingRadiation.FromKilorads(gray.Kilorads).Grays); + Assert.Equal(3, AbsorbedDoseOfIonizingRadiation.FromMegagrays(gray.Megagrays).Grays); + Assert.Equal(3, AbsorbedDoseOfIonizingRadiation.FromMegarads(gray.Megarads).Grays); + Assert.Equal(3, AbsorbedDoseOfIonizingRadiation.FromMicrograys(gray.Micrograys).Grays); + Assert.Equal(3, AbsorbedDoseOfIonizingRadiation.FromMilligrays(gray.Milligrays).Grays); + Assert.Equal(3, AbsorbedDoseOfIonizingRadiation.FromMillirads(gray.Millirads).Grays); + Assert.Equal(3, AbsorbedDoseOfIonizingRadiation.FromNanograys(gray.Nanograys).Grays); + Assert.Equal(3, AbsorbedDoseOfIonizingRadiation.FromPetagrays(gray.Petagrays).Grays); + Assert.Equal(3, AbsorbedDoseOfIonizingRadiation.FromPicograys(gray.Picograys).Grays); + Assert.Equal(3, AbsorbedDoseOfIonizingRadiation.FromRads(gray.Rads).Grays); + Assert.Equal(3, AbsorbedDoseOfIonizingRadiation.FromTeragrays(gray.Teragrays).Grays); } [Fact] public void ArithmeticOperators() { AbsorbedDoseOfIonizingRadiation v = AbsorbedDoseOfIonizingRadiation.FromGrays(1); - AssertEx.EqualTolerance(-1, -v.Grays, GraysTolerance); - AssertEx.EqualTolerance(2, (AbsorbedDoseOfIonizingRadiation.FromGrays(3)-v).Grays, GraysTolerance); - AssertEx.EqualTolerance(2, (v + v).Grays, GraysTolerance); - AssertEx.EqualTolerance(10, (v*10).Grays, GraysTolerance); - AssertEx.EqualTolerance(10, (10*v).Grays, GraysTolerance); - AssertEx.EqualTolerance(2, (AbsorbedDoseOfIonizingRadiation.FromGrays(10)/5).Grays, GraysTolerance); - AssertEx.EqualTolerance(2, AbsorbedDoseOfIonizingRadiation.FromGrays(10)/AbsorbedDoseOfIonizingRadiation.FromGrays(5), GraysTolerance); + Assert.Equal(-1, -v.Grays); + Assert.Equal(2, (AbsorbedDoseOfIonizingRadiation.FromGrays(3) - v).Grays); + Assert.Equal(2, (v + v).Grays); + Assert.Equal(10, (v * 10).Grays); + Assert.Equal(10, (10 * v).Grays); + Assert.Equal(2, (AbsorbedDoseOfIonizingRadiation.FromGrays(10) / 5).Grays); + Assert.Equal(2, AbsorbedDoseOfIonizingRadiation.FromGrays(10) / AbsorbedDoseOfIonizingRadiation.FromGrays(5)); } [Fact] @@ -920,8 +937,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, AbsorbedDoseOfIonizingRadiationUnit.Gray, 1, AbsorbedDoseOfIonizingRadiationUnit.Gray, true)] // Same value and unit. [InlineData(1, AbsorbedDoseOfIonizingRadiationUnit.Gray, 2, AbsorbedDoseOfIonizingRadiationUnit.Gray, false)] // Different value. - [InlineData(2, AbsorbedDoseOfIonizingRadiationUnit.Gray, 1, AbsorbedDoseOfIonizingRadiationUnit.Centigray, false)] // Different value and unit. - [InlineData(1, AbsorbedDoseOfIonizingRadiationUnit.Gray, 1, AbsorbedDoseOfIonizingRadiationUnit.Centigray, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, AbsorbedDoseOfIonizingRadiationUnit unitA, double valueB, AbsorbedDoseOfIonizingRadiationUnit unitB, bool expectEqual) { var a = new AbsorbedDoseOfIonizingRadiation(valueA, unitA); @@ -981,8 +996,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(firstValue); var otherQuantity = AbsorbedDoseOfIonizingRadiation.FromGrays(secondValue); AbsorbedDoseOfIonizingRadiation maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, AbsorbedDoseOfIonizingRadiation.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1001,7 +1016,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1014,6 +1029,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(AbsorbedDoseOfIonizingRadiation.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(AbsorbedDoseOfIonizingRadiation.Info.Units, AbsorbedDoseOfIonizingRadiation.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, AbsorbedDoseOfIonizingRadiation.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1108,7 +1135,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = AbsorbedDoseOfIonizingRadiation.FromGrays(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(AbsorbedDoseOfIonizingRadiation), quantity.As(AbsorbedDoseOfIonizingRadiation.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs index 17c71097ba..f1abfa977d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AccelerationTestsBase.g.cs @@ -177,6 +177,20 @@ public void Acceleration_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void AccelerationInfo_CreateWithCustomUnitInfos() + { + AccelerationUnit[] expectedUnits = [AccelerationUnit.MeterPerSecondSquared]; + + Acceleration.AccelerationInfo quantityInfo = Acceleration.AccelerationInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Acceleration", quantityInfo.Name); + Assert.Equal(Acceleration.Zero, quantityInfo.Zero); + Assert.Equal(Acceleration.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void MeterPerSecondSquaredToAccelerationUnits() { @@ -381,7 +395,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 мg", AccelerationUnit.MillistandardGravity, 4.2)] [InlineData("ru-RU", "4,2 нм/с²", AccelerationUnit.NanometerPerSecondSquared, 4.2)] [InlineData("ru-RU", "4,2 g", AccelerationUnit.StandardGravity, 4.2)] - public void Parse(string culture, string quantityString, AccelerationUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, AccelerationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Acceleration.Parse(quantityString); @@ -418,7 +432,7 @@ public void Parse(string culture, string quantityString, AccelerationUnit expect [InlineData("ru-RU", "4,2 мg", AccelerationUnit.MillistandardGravity, 4.2)] [InlineData("ru-RU", "4,2 нм/с²", AccelerationUnit.NanometerPerSecondSquared, 4.2)] [InlineData("ru-RU", "4,2 g", AccelerationUnit.StandardGravity, 4.2)] - public void TryParse(string culture, string quantityString, AccelerationUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, AccelerationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Acceleration.TryParse(quantityString, out Acceleration parsed)); @@ -738,6 +752,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AccelerationUnit var quantity = Acceleration.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -761,45 +776,47 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(AccelerationUnit un IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Acceleration meterpersecondsquared = Acceleration.FromMetersPerSecondSquared(1); - AssertEx.EqualTolerance(1, Acceleration.FromCentimetersPerSecondSquared(meterpersecondsquared.CentimetersPerSecondSquared).MetersPerSecondSquared, CentimetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromDecimetersPerSecondSquared(meterpersecondsquared.DecimetersPerSecondSquared).MetersPerSecondSquared, DecimetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromFeetPerSecondSquared(meterpersecondsquared.FeetPerSecondSquared).MetersPerSecondSquared, FeetPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromInchesPerSecondSquared(meterpersecondsquared.InchesPerSecondSquared).MetersPerSecondSquared, InchesPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromKilometersPerSecondSquared(meterpersecondsquared.KilometersPerSecondSquared).MetersPerSecondSquared, KilometersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromKnotsPerHour(meterpersecondsquared.KnotsPerHour).MetersPerSecondSquared, KnotsPerHourTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromKnotsPerMinute(meterpersecondsquared.KnotsPerMinute).MetersPerSecondSquared, KnotsPerMinuteTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromKnotsPerSecond(meterpersecondsquared.KnotsPerSecond).MetersPerSecondSquared, KnotsPerSecondTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromMetersPerSecondSquared(meterpersecondsquared.MetersPerSecondSquared).MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromMicrometersPerSecondSquared(meterpersecondsquared.MicrometersPerSecondSquared).MetersPerSecondSquared, MicrometersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromMillimetersPerSecondSquared(meterpersecondsquared.MillimetersPerSecondSquared).MetersPerSecondSquared, MillimetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromMillistandardGravity(meterpersecondsquared.MillistandardGravity).MetersPerSecondSquared, MillistandardGravityTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromNanometersPerSecondSquared(meterpersecondsquared.NanometersPerSecondSquared).MetersPerSecondSquared, NanometersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Acceleration.FromStandardGravity(meterpersecondsquared.StandardGravity).MetersPerSecondSquared, StandardGravityTolerance); + Acceleration meterpersecondsquared = Acceleration.FromMetersPerSecondSquared(3); + Assert.Equal(3, Acceleration.FromCentimetersPerSecondSquared(meterpersecondsquared.CentimetersPerSecondSquared).MetersPerSecondSquared); + Assert.Equal(3, Acceleration.FromDecimetersPerSecondSquared(meterpersecondsquared.DecimetersPerSecondSquared).MetersPerSecondSquared); + Assert.Equal(3, Acceleration.FromFeetPerSecondSquared(meterpersecondsquared.FeetPerSecondSquared).MetersPerSecondSquared); + Assert.Equal(3, Acceleration.FromInchesPerSecondSquared(meterpersecondsquared.InchesPerSecondSquared).MetersPerSecondSquared); + Assert.Equal(3, Acceleration.FromKilometersPerSecondSquared(meterpersecondsquared.KilometersPerSecondSquared).MetersPerSecondSquared); + Assert.Equal(3, Acceleration.FromKnotsPerHour(meterpersecondsquared.KnotsPerHour).MetersPerSecondSquared); + Assert.Equal(3, Acceleration.FromKnotsPerMinute(meterpersecondsquared.KnotsPerMinute).MetersPerSecondSquared); + Assert.Equal(3, Acceleration.FromKnotsPerSecond(meterpersecondsquared.KnotsPerSecond).MetersPerSecondSquared); + Assert.Equal(3, Acceleration.FromMetersPerSecondSquared(meterpersecondsquared.MetersPerSecondSquared).MetersPerSecondSquared); + Assert.Equal(3, Acceleration.FromMicrometersPerSecondSquared(meterpersecondsquared.MicrometersPerSecondSquared).MetersPerSecondSquared); + Assert.Equal(3, Acceleration.FromMillimetersPerSecondSquared(meterpersecondsquared.MillimetersPerSecondSquared).MetersPerSecondSquared); + Assert.Equal(3, Acceleration.FromMillistandardGravity(meterpersecondsquared.MillistandardGravity).MetersPerSecondSquared); + Assert.Equal(3, Acceleration.FromNanometersPerSecondSquared(meterpersecondsquared.NanometersPerSecondSquared).MetersPerSecondSquared); + Assert.Equal(3, Acceleration.FromStandardGravity(meterpersecondsquared.StandardGravity).MetersPerSecondSquared); } [Fact] public void ArithmeticOperators() { Acceleration v = Acceleration.FromMetersPerSecondSquared(1); - AssertEx.EqualTolerance(-1, -v.MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(2, (Acceleration.FromMetersPerSecondSquared(3)-v).MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(2, (v + v).MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(10, (v*10).MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(10, (10*v).MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(2, (Acceleration.FromMetersPerSecondSquared(10)/5).MetersPerSecondSquared, MetersPerSecondSquaredTolerance); - AssertEx.EqualTolerance(2, Acceleration.FromMetersPerSecondSquared(10)/Acceleration.FromMetersPerSecondSquared(5), MetersPerSecondSquaredTolerance); + Assert.Equal(-1, -v.MetersPerSecondSquared); + Assert.Equal(2, (Acceleration.FromMetersPerSecondSquared(3) - v).MetersPerSecondSquared); + Assert.Equal(2, (v + v).MetersPerSecondSquared); + Assert.Equal(10, (v * 10).MetersPerSecondSquared); + Assert.Equal(10, (10 * v).MetersPerSecondSquared); + Assert.Equal(2, (Acceleration.FromMetersPerSecondSquared(10) / 5).MetersPerSecondSquared); + Assert.Equal(2, Acceleration.FromMetersPerSecondSquared(10) / Acceleration.FromMetersPerSecondSquared(5)); } [Fact] @@ -845,8 +862,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, AccelerationUnit.MeterPerSecondSquared, 1, AccelerationUnit.MeterPerSecondSquared, true)] // Same value and unit. [InlineData(1, AccelerationUnit.MeterPerSecondSquared, 2, AccelerationUnit.MeterPerSecondSquared, false)] // Different value. - [InlineData(2, AccelerationUnit.MeterPerSecondSquared, 1, AccelerationUnit.CentimeterPerSecondSquared, false)] // Different value and unit. - [InlineData(1, AccelerationUnit.MeterPerSecondSquared, 1, AccelerationUnit.CentimeterPerSecondSquared, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, AccelerationUnit unitA, double valueB, AccelerationUnit unitB, bool expectEqual) { var a = new Acceleration(valueA, unitA); @@ -906,8 +921,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Acceleration.FromMetersPerSecondSquared(firstValue); var otherQuantity = Acceleration.FromMetersPerSecondSquared(secondValue); Acceleration maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Acceleration.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -926,7 +941,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -939,6 +954,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Acceleration.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Acceleration.Info.Units, Acceleration.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Acceleration.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1027,7 +1054,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Acceleration.FromMetersPerSecondSquared(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Acceleration), quantity.As(Acceleration.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs index df6c0e205a..ad8c36b55e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AmountOfSubstanceTestsBase.g.cs @@ -189,6 +189,20 @@ public void AmountOfSubstance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void AmountOfSubstanceInfo_CreateWithCustomUnitInfos() + { + AmountOfSubstanceUnit[] expectedUnits = [AmountOfSubstanceUnit.Mole]; + + AmountOfSubstance.AmountOfSubstanceInfo quantityInfo = AmountOfSubstance.AmountOfSubstanceInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("AmountOfSubstance", quantityInfo.Name); + Assert.Equal(AmountOfSubstance.Zero, quantityInfo.Zero); + Assert.Equal(AmountOfSubstance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void MoleToAmountOfSubstanceUnits() { @@ -388,7 +402,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 nlbmol", AmountOfSubstanceUnit.NanopoundMole, 4.2)] [InlineData("en-US", "4.2 pmol", AmountOfSubstanceUnit.Picomole, 4.2)] [InlineData("en-US", "4.2 lbmol", AmountOfSubstanceUnit.PoundMole, 4.2)] - public void Parse(string culture, string quantityString, AmountOfSubstanceUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, AmountOfSubstanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = AmountOfSubstance.Parse(quantityString); @@ -414,7 +428,7 @@ public void Parse(string culture, string quantityString, AmountOfSubstanceUnit e [InlineData("en-US", "4.2 nlbmol", AmountOfSubstanceUnit.NanopoundMole, 4.2)] [InlineData("en-US", "4.2 pmol", AmountOfSubstanceUnit.Picomole, 4.2)] [InlineData("en-US", "4.2 lbmol", AmountOfSubstanceUnit.PoundMole, 4.2)] - public void TryParse(string culture, string quantityString, AmountOfSubstanceUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, AmountOfSubstanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(AmountOfSubstance.TryParse(quantityString, out AmountOfSubstance parsed)); @@ -691,6 +705,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AmountOfSubstanc var quantity = AmountOfSubstance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -714,48 +729,50 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(AmountOfSubstanceUn IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - AmountOfSubstance mole = AmountOfSubstance.FromMoles(1); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromCentimoles(mole.Centimoles).Moles, CentimolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromCentipoundMoles(mole.CentipoundMoles).Moles, CentipoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromDecimoles(mole.Decimoles).Moles, DecimolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromDecipoundMoles(mole.DecipoundMoles).Moles, DecipoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromFemtomoles(mole.Femtomoles).Moles, FemtomolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromKilomoles(mole.Kilomoles).Moles, KilomolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromKilopoundMoles(mole.KilopoundMoles).Moles, KilopoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromMegamoles(mole.Megamoles).Moles, MegamolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromMicromoles(mole.Micromoles).Moles, MicromolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromMicropoundMoles(mole.MicropoundMoles).Moles, MicropoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromMillimoles(mole.Millimoles).Moles, MillimolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromMillipoundMoles(mole.MillipoundMoles).Moles, MillipoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromMoles(mole.Moles).Moles, MolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromNanomoles(mole.Nanomoles).Moles, NanomolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromNanopoundMoles(mole.NanopoundMoles).Moles, NanopoundMolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromPicomoles(mole.Picomoles).Moles, PicomolesTolerance); - AssertEx.EqualTolerance(1, AmountOfSubstance.FromPoundMoles(mole.PoundMoles).Moles, PoundMolesTolerance); + AmountOfSubstance mole = AmountOfSubstance.FromMoles(3); + Assert.Equal(3, AmountOfSubstance.FromCentimoles(mole.Centimoles).Moles); + Assert.Equal(3, AmountOfSubstance.FromCentipoundMoles(mole.CentipoundMoles).Moles); + Assert.Equal(3, AmountOfSubstance.FromDecimoles(mole.Decimoles).Moles); + Assert.Equal(3, AmountOfSubstance.FromDecipoundMoles(mole.DecipoundMoles).Moles); + Assert.Equal(3, AmountOfSubstance.FromFemtomoles(mole.Femtomoles).Moles); + Assert.Equal(3, AmountOfSubstance.FromKilomoles(mole.Kilomoles).Moles); + Assert.Equal(3, AmountOfSubstance.FromKilopoundMoles(mole.KilopoundMoles).Moles); + Assert.Equal(3, AmountOfSubstance.FromMegamoles(mole.Megamoles).Moles); + Assert.Equal(3, AmountOfSubstance.FromMicromoles(mole.Micromoles).Moles); + Assert.Equal(3, AmountOfSubstance.FromMicropoundMoles(mole.MicropoundMoles).Moles); + Assert.Equal(3, AmountOfSubstance.FromMillimoles(mole.Millimoles).Moles); + Assert.Equal(3, AmountOfSubstance.FromMillipoundMoles(mole.MillipoundMoles).Moles); + Assert.Equal(3, AmountOfSubstance.FromMoles(mole.Moles).Moles); + Assert.Equal(3, AmountOfSubstance.FromNanomoles(mole.Nanomoles).Moles); + Assert.Equal(3, AmountOfSubstance.FromNanopoundMoles(mole.NanopoundMoles).Moles); + Assert.Equal(3, AmountOfSubstance.FromPicomoles(mole.Picomoles).Moles); + Assert.Equal(3, AmountOfSubstance.FromPoundMoles(mole.PoundMoles).Moles); } [Fact] public void ArithmeticOperators() { AmountOfSubstance v = AmountOfSubstance.FromMoles(1); - AssertEx.EqualTolerance(-1, -v.Moles, MolesTolerance); - AssertEx.EqualTolerance(2, (AmountOfSubstance.FromMoles(3)-v).Moles, MolesTolerance); - AssertEx.EqualTolerance(2, (v + v).Moles, MolesTolerance); - AssertEx.EqualTolerance(10, (v*10).Moles, MolesTolerance); - AssertEx.EqualTolerance(10, (10*v).Moles, MolesTolerance); - AssertEx.EqualTolerance(2, (AmountOfSubstance.FromMoles(10)/5).Moles, MolesTolerance); - AssertEx.EqualTolerance(2, AmountOfSubstance.FromMoles(10)/AmountOfSubstance.FromMoles(5), MolesTolerance); + Assert.Equal(-1, -v.Moles); + Assert.Equal(2, (AmountOfSubstance.FromMoles(3) - v).Moles); + Assert.Equal(2, (v + v).Moles); + Assert.Equal(10, (v * 10).Moles); + Assert.Equal(10, (10 * v).Moles); + Assert.Equal(2, (AmountOfSubstance.FromMoles(10) / 5).Moles); + Assert.Equal(2, AmountOfSubstance.FromMoles(10) / AmountOfSubstance.FromMoles(5)); } [Fact] @@ -801,8 +818,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, AmountOfSubstanceUnit.Mole, 1, AmountOfSubstanceUnit.Mole, true)] // Same value and unit. [InlineData(1, AmountOfSubstanceUnit.Mole, 2, AmountOfSubstanceUnit.Mole, false)] // Different value. - [InlineData(2, AmountOfSubstanceUnit.Mole, 1, AmountOfSubstanceUnit.Centimole, false)] // Different value and unit. - [InlineData(1, AmountOfSubstanceUnit.Mole, 1, AmountOfSubstanceUnit.Centimole, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, AmountOfSubstanceUnit unitA, double valueB, AmountOfSubstanceUnit unitB, bool expectEqual) { var a = new AmountOfSubstance(valueA, unitA); @@ -862,8 +877,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = AmountOfSubstance.FromMoles(firstValue); var otherQuantity = AmountOfSubstance.FromMoles(secondValue); AmountOfSubstance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, AmountOfSubstance.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -882,7 +897,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -895,6 +910,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(AmountOfSubstance.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(AmountOfSubstance.Info.Units, AmountOfSubstance.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, AmountOfSubstance.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -989,7 +1016,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = AmountOfSubstance.FromMoles(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(AmountOfSubstance), quantity.As(AmountOfSubstance.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs index 2d3be5a3a3..a0eea73ead 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AmplitudeRatioTestsBase.g.cs @@ -116,6 +116,20 @@ public void AmplitudeRatio_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void AmplitudeRatioInfo_CreateWithCustomUnitInfos() + { + AmplitudeRatioUnit[] expectedUnits = [AmplitudeRatioUnit.DecibelVolt]; + + AmplitudeRatio.AmplitudeRatioInfo quantityInfo = AmplitudeRatio.AmplitudeRatioInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("AmplitudeRatio", quantityInfo.Name); + Assert.Equal(AmplitudeRatio.Zero, quantityInfo.Zero); + Assert.Equal(AmplitudeRatio.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void DecibelVoltToAmplitudeRatioUnits() { @@ -237,7 +251,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() [InlineData("en-US", "4.2 dBmV", AmplitudeRatioUnit.DecibelMillivolt, 4.2)] [InlineData("en-US", "4.2 dBu", AmplitudeRatioUnit.DecibelUnloaded, 4.2)] [InlineData("en-US", "4.2 dBV", AmplitudeRatioUnit.DecibelVolt, 4.2)] - public void Parse(string culture, string quantityString, AmplitudeRatioUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, AmplitudeRatioUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = AmplitudeRatio.Parse(quantityString); @@ -250,7 +264,7 @@ public void Parse(string culture, string quantityString, AmplitudeRatioUnit expe [InlineData("en-US", "4.2 dBmV", AmplitudeRatioUnit.DecibelMillivolt, 4.2)] [InlineData("en-US", "4.2 dBu", AmplitudeRatioUnit.DecibelUnloaded, 4.2)] [InlineData("en-US", "4.2 dBV", AmplitudeRatioUnit.DecibelVolt, 4.2)] - public void TryParse(string culture, string quantityString, AmplitudeRatioUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, AmplitudeRatioUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(AmplitudeRatio.TryParse(quantityString, out AmplitudeRatio parsed)); @@ -410,6 +424,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AmplitudeRatioUn var quantity = AmplitudeRatio.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -433,35 +448,37 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(AmplitudeRatioUnit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - AmplitudeRatio decibelvolt = AmplitudeRatio.FromDecibelVolts(1); - AssertEx.EqualTolerance(1, AmplitudeRatio.FromDecibelMicrovolts(decibelvolt.DecibelMicrovolts).DecibelVolts, DecibelMicrovoltsTolerance); - AssertEx.EqualTolerance(1, AmplitudeRatio.FromDecibelMillivolts(decibelvolt.DecibelMillivolts).DecibelVolts, DecibelMillivoltsTolerance); - AssertEx.EqualTolerance(1, AmplitudeRatio.FromDecibelsUnloaded(decibelvolt.DecibelsUnloaded).DecibelVolts, DecibelsUnloadedTolerance); - AssertEx.EqualTolerance(1, AmplitudeRatio.FromDecibelVolts(decibelvolt.DecibelVolts).DecibelVolts, DecibelVoltsTolerance); + AmplitudeRatio decibelvolt = AmplitudeRatio.FromDecibelVolts(3); + Assert.Equal(3, AmplitudeRatio.FromDecibelMicrovolts(decibelvolt.DecibelMicrovolts).DecibelVolts); + Assert.Equal(3, AmplitudeRatio.FromDecibelMillivolts(decibelvolt.DecibelMillivolts).DecibelVolts); + Assert.Equal(3, AmplitudeRatio.FromDecibelsUnloaded(decibelvolt.DecibelsUnloaded).DecibelVolts); + Assert.Equal(3, AmplitudeRatio.FromDecibelVolts(decibelvolt.DecibelVolts).DecibelVolts); } [Fact] public void LogarithmicArithmeticOperators() { AmplitudeRatio v = AmplitudeRatio.FromDecibelVolts(40); - AssertEx.EqualTolerance(-40, -v.DecibelVolts, DecibelVoltsTolerance); + Assert.Equal(-40, -v.DecibelVolts); AssertLogarithmicAddition(); AssertLogarithmicSubtraction(); - AssertEx.EqualTolerance(50, (v*10).DecibelVolts, DecibelVoltsTolerance); - AssertEx.EqualTolerance(50, (10*v).DecibelVolts, DecibelVoltsTolerance); - AssertEx.EqualTolerance(35, (v/5).DecibelVolts, DecibelVoltsTolerance); - AssertEx.EqualTolerance(35, v/AmplitudeRatio.FromDecibelVolts(5), DecibelVoltsTolerance); + Assert.Equal(50, (v * 10).DecibelVolts); + Assert.Equal(50, (10 * v).DecibelVolts); + Assert.Equal(35, (v / 5).DecibelVolts); + Assert.Equal(35, v / AmplitudeRatio.FromDecibelVolts(5)); } protected abstract void AssertLogarithmicAddition(); @@ -511,8 +528,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, AmplitudeRatioUnit.DecibelVolt, 1, AmplitudeRatioUnit.DecibelVolt, true)] // Same value and unit. [InlineData(1, AmplitudeRatioUnit.DecibelVolt, 2, AmplitudeRatioUnit.DecibelVolt, false)] // Different value. - [InlineData(2, AmplitudeRatioUnit.DecibelVolt, 1, AmplitudeRatioUnit.DecibelMicrovolt, false)] // Different value and unit. - [InlineData(1, AmplitudeRatioUnit.DecibelVolt, 1, AmplitudeRatioUnit.DecibelMicrovolt, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, AmplitudeRatioUnit unitA, double valueB, AmplitudeRatioUnit unitB, bool expectEqual) { var a = new AmplitudeRatio(valueA, unitA); @@ -572,8 +587,8 @@ public void Equals_Logarithmic_WithTolerance(double firstValue, double secondVal var quantity = AmplitudeRatio.FromDecibelVolts(firstValue); var otherQuantity = AmplitudeRatio.FromDecibelVolts(secondValue); AmplitudeRatio maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, AmplitudeRatio.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, largerTolerance)); @@ -594,7 +609,7 @@ public void Equals_Logarithmic_WithNegativeTolerance_DoesNotThrowArgumentOutOfRa [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -607,6 +622,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(AmplitudeRatio.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(AmplitudeRatio.Info.Units, AmplitudeRatio.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, AmplitudeRatio.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -675,7 +702,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = AmplitudeRatio.FromDecibelVolts(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(AmplitudeRatio), quantity.As(AmplitudeRatio.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs index 873ceb53bc..04bae0f739 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AngleTestsBase.g.cs @@ -160,6 +160,20 @@ public void Angle_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void AngleInfo_CreateWithCustomUnitInfos() + { + AngleUnit[] expectedUnits = [AngleUnit.Radian]; + + Angle.AngleInfo quantityInfo = Angle.AngleInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Angle", quantityInfo.Name); + Assert.Equal(Angle.Zero, quantityInfo.Zero); + Assert.Equal(Angle.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void RadianToAngleUnits() { @@ -336,7 +350,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() [InlineData("ru-RU", "4,2 нрад", AngleUnit.Nanoradian, 4.2)] [InlineData("ru-RU", "4,2 рад", AngleUnit.Radian, 4.2)] [InlineData("ru-RU", "4,2 r", AngleUnit.Revolution, 4.2)] - public void Parse(string culture, string quantityString, AngleUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, AngleUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Angle.Parse(quantityString); @@ -382,7 +396,7 @@ public void Parse(string culture, string quantityString, AngleUnit expectedUnit, [InlineData("ru-RU", "4,2 нрад", AngleUnit.Nanoradian, 4.2)] [InlineData("ru-RU", "4,2 рад", AngleUnit.Radian, 4.2)] [InlineData("ru-RU", "4,2 r", AngleUnit.Revolution, 4.2)] - public void TryParse(string culture, string quantityString, AngleUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, AngleUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Angle.TryParse(quantityString, out Angle parsed)); @@ -781,6 +795,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AngleUnit unit) var quantity = Angle.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -804,46 +819,48 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(AngleUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Angle radian = Angle.FromRadians(1); - AssertEx.EqualTolerance(1, Angle.FromArcminutes(radian.Arcminutes).Radians, ArcminutesTolerance); - AssertEx.EqualTolerance(1, Angle.FromArcseconds(radian.Arcseconds).Radians, ArcsecondsTolerance); - AssertEx.EqualTolerance(1, Angle.FromCentiradians(radian.Centiradians).Radians, CentiradiansTolerance); - AssertEx.EqualTolerance(1, Angle.FromDeciradians(radian.Deciradians).Radians, DeciradiansTolerance); - AssertEx.EqualTolerance(1, Angle.FromDegrees(radian.Degrees).Radians, DegreesTolerance); - AssertEx.EqualTolerance(1, Angle.FromGradians(radian.Gradians).Radians, GradiansTolerance); - AssertEx.EqualTolerance(1, Angle.FromMicrodegrees(radian.Microdegrees).Radians, MicrodegreesTolerance); - AssertEx.EqualTolerance(1, Angle.FromMicroradians(radian.Microradians).Radians, MicroradiansTolerance); - AssertEx.EqualTolerance(1, Angle.FromMillidegrees(radian.Millidegrees).Radians, MillidegreesTolerance); - AssertEx.EqualTolerance(1, Angle.FromMilliradians(radian.Milliradians).Radians, MilliradiansTolerance); - AssertEx.EqualTolerance(1, Angle.FromNanodegrees(radian.Nanodegrees).Radians, NanodegreesTolerance); - AssertEx.EqualTolerance(1, Angle.FromNanoradians(radian.Nanoradians).Radians, NanoradiansTolerance); - AssertEx.EqualTolerance(1, Angle.FromNatoMils(radian.NatoMils).Radians, NatoMilsTolerance); - AssertEx.EqualTolerance(1, Angle.FromRadians(radian.Radians).Radians, RadiansTolerance); - AssertEx.EqualTolerance(1, Angle.FromRevolutions(radian.Revolutions).Radians, RevolutionsTolerance); + Angle radian = Angle.FromRadians(3); + Assert.Equal(3, Angle.FromArcminutes(radian.Arcminutes).Radians); + Assert.Equal(3, Angle.FromArcseconds(radian.Arcseconds).Radians); + Assert.Equal(3, Angle.FromCentiradians(radian.Centiradians).Radians); + Assert.Equal(3, Angle.FromDeciradians(radian.Deciradians).Radians); + Assert.Equal(3, Angle.FromDegrees(radian.Degrees).Radians); + Assert.Equal(3, Angle.FromGradians(radian.Gradians).Radians); + Assert.Equal(3, Angle.FromMicrodegrees(radian.Microdegrees).Radians); + Assert.Equal(3, Angle.FromMicroradians(radian.Microradians).Radians); + Assert.Equal(3, Angle.FromMillidegrees(radian.Millidegrees).Radians); + Assert.Equal(3, Angle.FromMilliradians(radian.Milliradians).Radians); + Assert.Equal(3, Angle.FromNanodegrees(radian.Nanodegrees).Radians); + Assert.Equal(3, Angle.FromNanoradians(radian.Nanoradians).Radians); + Assert.Equal(3, Angle.FromNatoMils(radian.NatoMils).Radians); + Assert.Equal(3, Angle.FromRadians(radian.Radians).Radians); + Assert.Equal(3, Angle.FromRevolutions(radian.Revolutions).Radians); } [Fact] public void ArithmeticOperators() { Angle v = Angle.FromRadians(1); - AssertEx.EqualTolerance(-1, -v.Radians, RadiansTolerance); - AssertEx.EqualTolerance(2, (Angle.FromRadians(3)-v).Radians, RadiansTolerance); - AssertEx.EqualTolerance(2, (v + v).Radians, RadiansTolerance); - AssertEx.EqualTolerance(10, (v*10).Radians, RadiansTolerance); - AssertEx.EqualTolerance(10, (10*v).Radians, RadiansTolerance); - AssertEx.EqualTolerance(2, (Angle.FromRadians(10)/5).Radians, RadiansTolerance); - AssertEx.EqualTolerance(2, Angle.FromRadians(10)/Angle.FromRadians(5), RadiansTolerance); + Assert.Equal(-1, -v.Radians); + Assert.Equal(2, (Angle.FromRadians(3) - v).Radians); + Assert.Equal(2, (v + v).Radians); + Assert.Equal(10, (v * 10).Radians); + Assert.Equal(10, (10 * v).Radians); + Assert.Equal(2, (Angle.FromRadians(10) / 5).Radians); + Assert.Equal(2, Angle.FromRadians(10) / Angle.FromRadians(5)); } [Fact] @@ -889,8 +906,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, AngleUnit.Radian, 1, AngleUnit.Radian, true)] // Same value and unit. [InlineData(1, AngleUnit.Radian, 2, AngleUnit.Radian, false)] // Different value. - [InlineData(2, AngleUnit.Radian, 1, AngleUnit.Arcminute, false)] // Different value and unit. - [InlineData(1, AngleUnit.Radian, 1, AngleUnit.Arcminute, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, AngleUnit unitA, double valueB, AngleUnit unitB, bool expectEqual) { var a = new Angle(valueA, unitA); @@ -950,8 +965,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Angle.FromRadians(firstValue); var otherQuantity = Angle.FromRadians(secondValue); Angle maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Angle.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -970,7 +985,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -983,6 +998,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Angle.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Angle.Info.Units, Angle.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Angle.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1073,7 +1100,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Angle.FromRadians(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Angle), quantity.As(Angle.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs index 671597a4aa..374ddc1d7e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaDensityTestsBase.g.cs @@ -133,6 +133,20 @@ public void AreaDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void AreaDensityInfo_CreateWithCustomUnitInfos() + { + AreaDensityUnit[] expectedUnits = [AreaDensityUnit.KilogramPerSquareMeter]; + + AreaDensity.AreaDensityInfo quantityInfo = AreaDensity.AreaDensityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("AreaDensity", quantityInfo.Name); + Assert.Equal(AreaDensity.Zero, quantityInfo.Zero); + Assert.Equal(AreaDensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void KilogramPerSquareMeterToAreaDensityUnits() { @@ -291,7 +305,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 gsm", AreaDensityUnit.GramPerSquareMeter, 4.2)] [InlineData("en-US", "4.2 kg/m²", AreaDensityUnit.KilogramPerSquareMeter, 4.2)] [InlineData("en-US", "4.2 mg/m²", AreaDensityUnit.MilligramPerSquareMeter, 4.2)] - public void Parse(string culture, string quantityString, AreaDensityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, AreaDensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = AreaDensity.Parse(quantityString); @@ -304,7 +318,7 @@ public void Parse(string culture, string quantityString, AreaDensityUnit expecte [InlineData("en-US", "4.2 gsm", AreaDensityUnit.GramPerSquareMeter, 4.2)] [InlineData("en-US", "4.2 kg/m²", AreaDensityUnit.KilogramPerSquareMeter, 4.2)] [InlineData("en-US", "4.2 mg/m²", AreaDensityUnit.MilligramPerSquareMeter, 4.2)] - public void TryParse(string culture, string quantityString, AreaDensityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, AreaDensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(AreaDensity.TryParse(quantityString, out AreaDensity parsed)); @@ -463,6 +477,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AreaDensityUnit var quantity = AreaDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -486,34 +501,36 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(AreaDensityUnit uni IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - AreaDensity kilogrampersquaremeter = AreaDensity.FromKilogramsPerSquareMeter(1); - AssertEx.EqualTolerance(1, AreaDensity.FromGramsPerSquareMeter(kilogrampersquaremeter.GramsPerSquareMeter).KilogramsPerSquareMeter, GramsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, AreaDensity.FromKilogramsPerSquareMeter(kilogrampersquaremeter.KilogramsPerSquareMeter).KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, AreaDensity.FromMilligramsPerSquareMeter(kilogrampersquaremeter.MilligramsPerSquareMeter).KilogramsPerSquareMeter, MilligramsPerSquareMeterTolerance); + AreaDensity kilogrampersquaremeter = AreaDensity.FromKilogramsPerSquareMeter(3); + Assert.Equal(3, AreaDensity.FromGramsPerSquareMeter(kilogrampersquaremeter.GramsPerSquareMeter).KilogramsPerSquareMeter); + Assert.Equal(3, AreaDensity.FromKilogramsPerSquareMeter(kilogrampersquaremeter.KilogramsPerSquareMeter).KilogramsPerSquareMeter); + Assert.Equal(3, AreaDensity.FromMilligramsPerSquareMeter(kilogrampersquaremeter.MilligramsPerSquareMeter).KilogramsPerSquareMeter); } [Fact] public void ArithmeticOperators() { AreaDensity v = AreaDensity.FromKilogramsPerSquareMeter(1); - AssertEx.EqualTolerance(-1, -v.KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (AreaDensity.FromKilogramsPerSquareMeter(3)-v).KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (AreaDensity.FromKilogramsPerSquareMeter(10)/5).KilogramsPerSquareMeter, KilogramsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, AreaDensity.FromKilogramsPerSquareMeter(10)/AreaDensity.FromKilogramsPerSquareMeter(5), KilogramsPerSquareMeterTolerance); + Assert.Equal(-1, -v.KilogramsPerSquareMeter); + Assert.Equal(2, (AreaDensity.FromKilogramsPerSquareMeter(3) - v).KilogramsPerSquareMeter); + Assert.Equal(2, (v + v).KilogramsPerSquareMeter); + Assert.Equal(10, (v * 10).KilogramsPerSquareMeter); + Assert.Equal(10, (10 * v).KilogramsPerSquareMeter); + Assert.Equal(2, (AreaDensity.FromKilogramsPerSquareMeter(10) / 5).KilogramsPerSquareMeter); + Assert.Equal(2, AreaDensity.FromKilogramsPerSquareMeter(10) / AreaDensity.FromKilogramsPerSquareMeter(5)); } [Fact] @@ -559,8 +576,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, AreaDensityUnit.KilogramPerSquareMeter, 1, AreaDensityUnit.KilogramPerSquareMeter, true)] // Same value and unit. [InlineData(1, AreaDensityUnit.KilogramPerSquareMeter, 2, AreaDensityUnit.KilogramPerSquareMeter, false)] // Different value. - [InlineData(2, AreaDensityUnit.KilogramPerSquareMeter, 1, AreaDensityUnit.GramPerSquareMeter, false)] // Different value and unit. - [InlineData(1, AreaDensityUnit.KilogramPerSquareMeter, 1, AreaDensityUnit.GramPerSquareMeter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, AreaDensityUnit unitA, double valueB, AreaDensityUnit unitB, bool expectEqual) { var a = new AreaDensity(valueA, unitA); @@ -620,8 +635,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = AreaDensity.FromKilogramsPerSquareMeter(firstValue); var otherQuantity = AreaDensity.FromKilogramsPerSquareMeter(secondValue); AreaDensity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, AreaDensity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -640,7 +655,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -653,6 +668,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(AreaDensity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(AreaDensity.Info.Units, AreaDensity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, AreaDensity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -719,7 +746,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = AreaDensity.FromKilogramsPerSquareMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(AreaDensity), quantity.As(AreaDensity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs index 1feac48950..0880688e5c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaMomentOfInertiaTestsBase.g.cs @@ -145,6 +145,20 @@ public void AreaMomentOfInertia_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void AreaMomentOfInertiaInfo_CreateWithCustomUnitInfos() + { + AreaMomentOfInertiaUnit[] expectedUnits = [AreaMomentOfInertiaUnit.MeterToTheFourth]; + + AreaMomentOfInertia.AreaMomentOfInertiaInfo quantityInfo = AreaMomentOfInertia.AreaMomentOfInertiaInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("AreaMomentOfInertia", quantityInfo.Name); + Assert.Equal(AreaMomentOfInertia.Zero, quantityInfo.Zero); + Assert.Equal(AreaMomentOfInertia.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void MeterToTheFourthToAreaMomentOfInertiaUnits() { @@ -311,7 +325,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 in⁴", AreaMomentOfInertiaUnit.InchToTheFourth, 4.2)] [InlineData("en-US", "4.2 m⁴", AreaMomentOfInertiaUnit.MeterToTheFourth, 4.2)] [InlineData("en-US", "4.2 mm⁴", AreaMomentOfInertiaUnit.MillimeterToTheFourth, 4.2)] - public void Parse(string culture, string quantityString, AreaMomentOfInertiaUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, AreaMomentOfInertiaUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = AreaMomentOfInertia.Parse(quantityString); @@ -326,7 +340,7 @@ public void Parse(string culture, string quantityString, AreaMomentOfInertiaUnit [InlineData("en-US", "4.2 in⁴", AreaMomentOfInertiaUnit.InchToTheFourth, 4.2)] [InlineData("en-US", "4.2 m⁴", AreaMomentOfInertiaUnit.MeterToTheFourth, 4.2)] [InlineData("en-US", "4.2 mm⁴", AreaMomentOfInertiaUnit.MillimeterToTheFourth, 4.2)] - public void TryParse(string culture, string quantityString, AreaMomentOfInertiaUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, AreaMomentOfInertiaUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(AreaMomentOfInertia.TryParse(quantityString, out AreaMomentOfInertia parsed)); @@ -504,6 +518,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AreaMomentOfIner var quantity = AreaMomentOfInertia.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -527,37 +542,39 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(AreaMomentOfInertia IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - AreaMomentOfInertia metertothefourth = AreaMomentOfInertia.FromMetersToTheFourth(1); - AssertEx.EqualTolerance(1, AreaMomentOfInertia.FromCentimetersToTheFourth(metertothefourth.CentimetersToTheFourth).MetersToTheFourth, CentimetersToTheFourthTolerance); - AssertEx.EqualTolerance(1, AreaMomentOfInertia.FromDecimetersToTheFourth(metertothefourth.DecimetersToTheFourth).MetersToTheFourth, DecimetersToTheFourthTolerance); - AssertEx.EqualTolerance(1, AreaMomentOfInertia.FromFeetToTheFourth(metertothefourth.FeetToTheFourth).MetersToTheFourth, FeetToTheFourthTolerance); - AssertEx.EqualTolerance(1, AreaMomentOfInertia.FromInchesToTheFourth(metertothefourth.InchesToTheFourth).MetersToTheFourth, InchesToTheFourthTolerance); - AssertEx.EqualTolerance(1, AreaMomentOfInertia.FromMetersToTheFourth(metertothefourth.MetersToTheFourth).MetersToTheFourth, MetersToTheFourthTolerance); - AssertEx.EqualTolerance(1, AreaMomentOfInertia.FromMillimetersToTheFourth(metertothefourth.MillimetersToTheFourth).MetersToTheFourth, MillimetersToTheFourthTolerance); + AreaMomentOfInertia metertothefourth = AreaMomentOfInertia.FromMetersToTheFourth(3); + Assert.Equal(3, AreaMomentOfInertia.FromCentimetersToTheFourth(metertothefourth.CentimetersToTheFourth).MetersToTheFourth); + Assert.Equal(3, AreaMomentOfInertia.FromDecimetersToTheFourth(metertothefourth.DecimetersToTheFourth).MetersToTheFourth); + Assert.Equal(3, AreaMomentOfInertia.FromFeetToTheFourth(metertothefourth.FeetToTheFourth).MetersToTheFourth); + Assert.Equal(3, AreaMomentOfInertia.FromInchesToTheFourth(metertothefourth.InchesToTheFourth).MetersToTheFourth); + Assert.Equal(3, AreaMomentOfInertia.FromMetersToTheFourth(metertothefourth.MetersToTheFourth).MetersToTheFourth); + Assert.Equal(3, AreaMomentOfInertia.FromMillimetersToTheFourth(metertothefourth.MillimetersToTheFourth).MetersToTheFourth); } [Fact] public void ArithmeticOperators() { AreaMomentOfInertia v = AreaMomentOfInertia.FromMetersToTheFourth(1); - AssertEx.EqualTolerance(-1, -v.MetersToTheFourth, MetersToTheFourthTolerance); - AssertEx.EqualTolerance(2, (AreaMomentOfInertia.FromMetersToTheFourth(3)-v).MetersToTheFourth, MetersToTheFourthTolerance); - AssertEx.EqualTolerance(2, (v + v).MetersToTheFourth, MetersToTheFourthTolerance); - AssertEx.EqualTolerance(10, (v*10).MetersToTheFourth, MetersToTheFourthTolerance); - AssertEx.EqualTolerance(10, (10*v).MetersToTheFourth, MetersToTheFourthTolerance); - AssertEx.EqualTolerance(2, (AreaMomentOfInertia.FromMetersToTheFourth(10)/5).MetersToTheFourth, MetersToTheFourthTolerance); - AssertEx.EqualTolerance(2, AreaMomentOfInertia.FromMetersToTheFourth(10)/AreaMomentOfInertia.FromMetersToTheFourth(5), MetersToTheFourthTolerance); + Assert.Equal(-1, -v.MetersToTheFourth); + Assert.Equal(2, (AreaMomentOfInertia.FromMetersToTheFourth(3) - v).MetersToTheFourth); + Assert.Equal(2, (v + v).MetersToTheFourth); + Assert.Equal(10, (v * 10).MetersToTheFourth); + Assert.Equal(10, (10 * v).MetersToTheFourth); + Assert.Equal(2, (AreaMomentOfInertia.FromMetersToTheFourth(10) / 5).MetersToTheFourth); + Assert.Equal(2, AreaMomentOfInertia.FromMetersToTheFourth(10) / AreaMomentOfInertia.FromMetersToTheFourth(5)); } [Fact] @@ -603,8 +620,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, AreaMomentOfInertiaUnit.MeterToTheFourth, 1, AreaMomentOfInertiaUnit.MeterToTheFourth, true)] // Same value and unit. [InlineData(1, AreaMomentOfInertiaUnit.MeterToTheFourth, 2, AreaMomentOfInertiaUnit.MeterToTheFourth, false)] // Different value. - [InlineData(2, AreaMomentOfInertiaUnit.MeterToTheFourth, 1, AreaMomentOfInertiaUnit.CentimeterToTheFourth, false)] // Different value and unit. - [InlineData(1, AreaMomentOfInertiaUnit.MeterToTheFourth, 1, AreaMomentOfInertiaUnit.CentimeterToTheFourth, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, AreaMomentOfInertiaUnit unitA, double valueB, AreaMomentOfInertiaUnit unitB, bool expectEqual) { var a = new AreaMomentOfInertia(valueA, unitA); @@ -664,8 +679,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = AreaMomentOfInertia.FromMetersToTheFourth(firstValue); var otherQuantity = AreaMomentOfInertia.FromMetersToTheFourth(secondValue); AreaMomentOfInertia maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, AreaMomentOfInertia.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -684,7 +699,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -697,6 +712,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(AreaMomentOfInertia.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(AreaMomentOfInertia.Info.Units, AreaMomentOfInertia.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, AreaMomentOfInertia.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -769,7 +796,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = AreaMomentOfInertia.FromMetersToTheFourth(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(AreaMomentOfInertia), quantity.As(AreaMomentOfInertia.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs index fbcd77a1c4..5f0783bc8f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/AreaTestsBase.g.cs @@ -177,6 +177,20 @@ public void Area_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void AreaInfo_CreateWithCustomUnitInfos() + { + AreaUnit[] expectedUnits = [AreaUnit.SquareMeter]; + + Area.AreaInfo quantityInfo = Area.AreaInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Area", quantityInfo.Name); + Assert.Equal(Area.Zero, quantityInfo.Zero); + Assert.Equal(Area.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void SquareMeterToAreaUnits() { @@ -392,7 +406,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("zh-CN", "4.2 平方毫米", AreaUnit.SquareMillimeter, 4.2)] [InlineData("zh-CN", "4.2 平方海里", AreaUnit.SquareNauticalMile, 4.2)] [InlineData("zh-CN", "4.2 平方码", AreaUnit.SquareYard, 4.2)] - public void Parse(string culture, string quantityString, AreaUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, AreaUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Area.Parse(quantityString); @@ -447,7 +461,7 @@ public void ParseWithAmbiguousAbbreviation(string culture, string quantityString [InlineData("zh-CN", "4.2 平方毫米", AreaUnit.SquareMillimeter, 4.2)] [InlineData("zh-CN", "4.2 平方海里", AreaUnit.SquareNauticalMile, 4.2)] [InlineData("zh-CN", "4.2 平方码", AreaUnit.SquareYard, 4.2)] - public void TryParse(string culture, string quantityString, AreaUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, AreaUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Area.TryParse(quantityString, out Area parsed)); @@ -845,6 +859,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(AreaUnit unit) var quantity = Area.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -868,45 +883,47 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(AreaUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Area squaremeter = Area.FromSquareMeters(1); - AssertEx.EqualTolerance(1, Area.FromAcres(squaremeter.Acres).SquareMeters, AcresTolerance); - AssertEx.EqualTolerance(1, Area.FromHectares(squaremeter.Hectares).SquareMeters, HectaresTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareCentimeters(squaremeter.SquareCentimeters).SquareMeters, SquareCentimetersTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareDecimeters(squaremeter.SquareDecimeters).SquareMeters, SquareDecimetersTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareFeet(squaremeter.SquareFeet).SquareMeters, SquareFeetTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareInches(squaremeter.SquareInches).SquareMeters, SquareInchesTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareKilometers(squaremeter.SquareKilometers).SquareMeters, SquareKilometersTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareMeters(squaremeter.SquareMeters).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareMicrometers(squaremeter.SquareMicrometers).SquareMeters, SquareMicrometersTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareMiles(squaremeter.SquareMiles).SquareMeters, SquareMilesTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareMillimeters(squaremeter.SquareMillimeters).SquareMeters, SquareMillimetersTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareNauticalMiles(squaremeter.SquareNauticalMiles).SquareMeters, SquareNauticalMilesTolerance); - AssertEx.EqualTolerance(1, Area.FromSquareYards(squaremeter.SquareYards).SquareMeters, SquareYardsTolerance); - AssertEx.EqualTolerance(1, Area.FromUsSurveySquareFeet(squaremeter.UsSurveySquareFeet).SquareMeters, UsSurveySquareFeetTolerance); + Area squaremeter = Area.FromSquareMeters(3); + Assert.Equal(3, Area.FromAcres(squaremeter.Acres).SquareMeters); + Assert.Equal(3, Area.FromHectares(squaremeter.Hectares).SquareMeters); + Assert.Equal(3, Area.FromSquareCentimeters(squaremeter.SquareCentimeters).SquareMeters); + Assert.Equal(3, Area.FromSquareDecimeters(squaremeter.SquareDecimeters).SquareMeters); + Assert.Equal(3, Area.FromSquareFeet(squaremeter.SquareFeet).SquareMeters); + Assert.Equal(3, Area.FromSquareInches(squaremeter.SquareInches).SquareMeters); + Assert.Equal(3, Area.FromSquareKilometers(squaremeter.SquareKilometers).SquareMeters); + Assert.Equal(3, Area.FromSquareMeters(squaremeter.SquareMeters).SquareMeters); + Assert.Equal(3, Area.FromSquareMicrometers(squaremeter.SquareMicrometers).SquareMeters); + Assert.Equal(3, Area.FromSquareMiles(squaremeter.SquareMiles).SquareMeters); + Assert.Equal(3, Area.FromSquareMillimeters(squaremeter.SquareMillimeters).SquareMeters); + Assert.Equal(3, Area.FromSquareNauticalMiles(squaremeter.SquareNauticalMiles).SquareMeters); + Assert.Equal(3, Area.FromSquareYards(squaremeter.SquareYards).SquareMeters); + Assert.Equal(3, Area.FromUsSurveySquareFeet(squaremeter.UsSurveySquareFeet).SquareMeters); } [Fact] public void ArithmeticOperators() { Area v = Area.FromSquareMeters(1); - AssertEx.EqualTolerance(-1, -v.SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(2, (Area.FromSquareMeters(3)-v).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(2, (v + v).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(10, (v*10).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(10, (10*v).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(2, (Area.FromSquareMeters(10)/5).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(2, Area.FromSquareMeters(10)/Area.FromSquareMeters(5), SquareMetersTolerance); + Assert.Equal(-1, -v.SquareMeters); + Assert.Equal(2, (Area.FromSquareMeters(3) - v).SquareMeters); + Assert.Equal(2, (v + v).SquareMeters); + Assert.Equal(10, (v * 10).SquareMeters); + Assert.Equal(10, (10 * v).SquareMeters); + Assert.Equal(2, (Area.FromSquareMeters(10) / 5).SquareMeters); + Assert.Equal(2, Area.FromSquareMeters(10) / Area.FromSquareMeters(5)); } [Fact] @@ -952,8 +969,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, AreaUnit.SquareMeter, 1, AreaUnit.SquareMeter, true)] // Same value and unit. [InlineData(1, AreaUnit.SquareMeter, 2, AreaUnit.SquareMeter, false)] // Different value. - [InlineData(2, AreaUnit.SquareMeter, 1, AreaUnit.Acre, false)] // Different value and unit. - [InlineData(1, AreaUnit.SquareMeter, 1, AreaUnit.Acre, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, AreaUnit unitA, double valueB, AreaUnit unitB, bool expectEqual) { var a = new Area(valueA, unitA); @@ -1013,8 +1028,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Area.FromSquareMeters(firstValue); var otherQuantity = Area.FromSquareMeters(secondValue); Area maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Area.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1033,7 +1048,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1046,6 +1061,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Area.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Area.Info.Units, Area.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Area.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1134,7 +1161,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Area.FromSquareMeters(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Area), quantity.As(Area.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs index d148bf47a4..4d50b69df8 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/BitRateTestsBase.g.cs @@ -277,6 +277,20 @@ public void BitRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void BitRateInfo_CreateWithCustomUnitInfos() + { + BitRateUnit[] expectedUnits = [BitRateUnit.BitPerSecond]; + + BitRate.BitRateInfo quantityInfo = BitRate.BitRateInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("BitRate", quantityInfo.Name); + Assert.Equal(BitRate.Zero, quantityInfo.Zero); + Assert.Equal(BitRate.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void BitPerSecondToBitRateUnits() { @@ -555,7 +569,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 Tbps", BitRateUnit.TerabitPerSecond, 4.2)] [InlineData("en-US", "4.2 TB/s", BitRateUnit.TerabytePerSecond, 4.2)] [InlineData("en-US", "4.2 To/s", BitRateUnit.TeraoctetPerSecond, 4.2)] - public void Parse(string culture, string quantityString, BitRateUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, BitRateUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = BitRate.Parse(quantityString); @@ -616,7 +630,7 @@ public void Parse(string culture, string quantityString, BitRateUnit expectedUni [InlineData("en-US", "4.2 Tbps", BitRateUnit.TerabitPerSecond, 4.2)] [InlineData("en-US", "4.2 TB/s", BitRateUnit.TerabytePerSecond, 4.2)] [InlineData("en-US", "4.2 To/s", BitRateUnit.TeraoctetPerSecond, 4.2)] - public void TryParse(string culture, string quantityString, BitRateUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, BitRateUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(BitRate.TryParse(quantityString, out BitRate parsed)); @@ -1195,6 +1209,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(BitRateUnit unit var quantity = BitRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -1218,70 +1233,72 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(BitRateUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - BitRate bitpersecond = BitRate.FromBitsPerSecond(1); - AssertEx.EqualTolerance(1, BitRate.FromBitsPerSecond(bitpersecond.BitsPerSecond).BitsPerSecond, BitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromBytesPerSecond(bitpersecond.BytesPerSecond).BitsPerSecond, BytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromExabitsPerSecond(bitpersecond.ExabitsPerSecond).BitsPerSecond, ExabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromExabytesPerSecond(bitpersecond.ExabytesPerSecond).BitsPerSecond, ExabytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromExaoctetsPerSecond(bitpersecond.ExaoctetsPerSecond).BitsPerSecond, ExaoctetsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromExbibitsPerSecond(bitpersecond.ExbibitsPerSecond).BitsPerSecond, ExbibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromExbibytesPerSecond(bitpersecond.ExbibytesPerSecond).BitsPerSecond, ExbibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromExbioctetsPerSecond(bitpersecond.ExbioctetsPerSecond).BitsPerSecond, ExbioctetsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromGibibitsPerSecond(bitpersecond.GibibitsPerSecond).BitsPerSecond, GibibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromGibibytesPerSecond(bitpersecond.GibibytesPerSecond).BitsPerSecond, GibibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromGibioctetsPerSecond(bitpersecond.GibioctetsPerSecond).BitsPerSecond, GibioctetsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromGigabitsPerSecond(bitpersecond.GigabitsPerSecond).BitsPerSecond, GigabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromGigabytesPerSecond(bitpersecond.GigabytesPerSecond).BitsPerSecond, GigabytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromGigaoctetsPerSecond(bitpersecond.GigaoctetsPerSecond).BitsPerSecond, GigaoctetsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromKibibitsPerSecond(bitpersecond.KibibitsPerSecond).BitsPerSecond, KibibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromKibibytesPerSecond(bitpersecond.KibibytesPerSecond).BitsPerSecond, KibibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromKibioctetsPerSecond(bitpersecond.KibioctetsPerSecond).BitsPerSecond, KibioctetsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromKilobitsPerSecond(bitpersecond.KilobitsPerSecond).BitsPerSecond, KilobitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromKilobytesPerSecond(bitpersecond.KilobytesPerSecond).BitsPerSecond, KilobytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromKilooctetsPerSecond(bitpersecond.KilooctetsPerSecond).BitsPerSecond, KilooctetsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromMebibitsPerSecond(bitpersecond.MebibitsPerSecond).BitsPerSecond, MebibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromMebibytesPerSecond(bitpersecond.MebibytesPerSecond).BitsPerSecond, MebibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromMebioctetsPerSecond(bitpersecond.MebioctetsPerSecond).BitsPerSecond, MebioctetsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromMegabitsPerSecond(bitpersecond.MegabitsPerSecond).BitsPerSecond, MegabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromMegabytesPerSecond(bitpersecond.MegabytesPerSecond).BitsPerSecond, MegabytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromMegaoctetsPerSecond(bitpersecond.MegaoctetsPerSecond).BitsPerSecond, MegaoctetsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromOctetsPerSecond(bitpersecond.OctetsPerSecond).BitsPerSecond, OctetsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromPebibitsPerSecond(bitpersecond.PebibitsPerSecond).BitsPerSecond, PebibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromPebibytesPerSecond(bitpersecond.PebibytesPerSecond).BitsPerSecond, PebibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromPebioctetsPerSecond(bitpersecond.PebioctetsPerSecond).BitsPerSecond, PebioctetsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromPetabitsPerSecond(bitpersecond.PetabitsPerSecond).BitsPerSecond, PetabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromPetabytesPerSecond(bitpersecond.PetabytesPerSecond).BitsPerSecond, PetabytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromPetaoctetsPerSecond(bitpersecond.PetaoctetsPerSecond).BitsPerSecond, PetaoctetsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromTebibitsPerSecond(bitpersecond.TebibitsPerSecond).BitsPerSecond, TebibitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromTebibytesPerSecond(bitpersecond.TebibytesPerSecond).BitsPerSecond, TebibytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromTebioctetsPerSecond(bitpersecond.TebioctetsPerSecond).BitsPerSecond, TebioctetsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromTerabitsPerSecond(bitpersecond.TerabitsPerSecond).BitsPerSecond, TerabitsPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromTerabytesPerSecond(bitpersecond.TerabytesPerSecond).BitsPerSecond, TerabytesPerSecondTolerance); - AssertEx.EqualTolerance(1, BitRate.FromTeraoctetsPerSecond(bitpersecond.TeraoctetsPerSecond).BitsPerSecond, TeraoctetsPerSecondTolerance); + BitRate bitpersecond = BitRate.FromBitsPerSecond(3); + Assert.Equal(3, BitRate.FromBitsPerSecond(bitpersecond.BitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromBytesPerSecond(bitpersecond.BytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromExabitsPerSecond(bitpersecond.ExabitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromExabytesPerSecond(bitpersecond.ExabytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromExaoctetsPerSecond(bitpersecond.ExaoctetsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromExbibitsPerSecond(bitpersecond.ExbibitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromExbibytesPerSecond(bitpersecond.ExbibytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromExbioctetsPerSecond(bitpersecond.ExbioctetsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromGibibitsPerSecond(bitpersecond.GibibitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromGibibytesPerSecond(bitpersecond.GibibytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromGibioctetsPerSecond(bitpersecond.GibioctetsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromGigabitsPerSecond(bitpersecond.GigabitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromGigabytesPerSecond(bitpersecond.GigabytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromGigaoctetsPerSecond(bitpersecond.GigaoctetsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromKibibitsPerSecond(bitpersecond.KibibitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromKibibytesPerSecond(bitpersecond.KibibytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromKibioctetsPerSecond(bitpersecond.KibioctetsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromKilobitsPerSecond(bitpersecond.KilobitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromKilobytesPerSecond(bitpersecond.KilobytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromKilooctetsPerSecond(bitpersecond.KilooctetsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromMebibitsPerSecond(bitpersecond.MebibitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromMebibytesPerSecond(bitpersecond.MebibytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromMebioctetsPerSecond(bitpersecond.MebioctetsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromMegabitsPerSecond(bitpersecond.MegabitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromMegabytesPerSecond(bitpersecond.MegabytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromMegaoctetsPerSecond(bitpersecond.MegaoctetsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromOctetsPerSecond(bitpersecond.OctetsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromPebibitsPerSecond(bitpersecond.PebibitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromPebibytesPerSecond(bitpersecond.PebibytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromPebioctetsPerSecond(bitpersecond.PebioctetsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromPetabitsPerSecond(bitpersecond.PetabitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromPetabytesPerSecond(bitpersecond.PetabytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromPetaoctetsPerSecond(bitpersecond.PetaoctetsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromTebibitsPerSecond(bitpersecond.TebibitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromTebibytesPerSecond(bitpersecond.TebibytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromTebioctetsPerSecond(bitpersecond.TebioctetsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromTerabitsPerSecond(bitpersecond.TerabitsPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromTerabytesPerSecond(bitpersecond.TerabytesPerSecond).BitsPerSecond); + Assert.Equal(3, BitRate.FromTeraoctetsPerSecond(bitpersecond.TeraoctetsPerSecond).BitsPerSecond); } [Fact] public void ArithmeticOperators() { BitRate v = BitRate.FromBitsPerSecond(1); - AssertEx.EqualTolerance(-1, -v.BitsPerSecond, BitsPerSecondTolerance); - AssertEx.EqualTolerance(2, (BitRate.FromBitsPerSecond(3)-v).BitsPerSecond, BitsPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).BitsPerSecond, BitsPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).BitsPerSecond, BitsPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).BitsPerSecond, BitsPerSecondTolerance); - AssertEx.EqualTolerance(2, (BitRate.FromBitsPerSecond(10)/5).BitsPerSecond, BitsPerSecondTolerance); - AssertEx.EqualTolerance(2, BitRate.FromBitsPerSecond(10)/BitRate.FromBitsPerSecond(5), BitsPerSecondTolerance); + Assert.Equal(-1, -v.BitsPerSecond); + Assert.Equal(2, (BitRate.FromBitsPerSecond(3) - v).BitsPerSecond); + Assert.Equal(2, (v + v).BitsPerSecond); + Assert.Equal(10, (v * 10).BitsPerSecond); + Assert.Equal(10, (10 * v).BitsPerSecond); + Assert.Equal(2, (BitRate.FromBitsPerSecond(10) / 5).BitsPerSecond); + Assert.Equal(2, BitRate.FromBitsPerSecond(10) / BitRate.FromBitsPerSecond(5)); } [Fact] @@ -1327,8 +1344,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, BitRateUnit.BitPerSecond, 1, BitRateUnit.BitPerSecond, true)] // Same value and unit. [InlineData(1, BitRateUnit.BitPerSecond, 2, BitRateUnit.BitPerSecond, false)] // Different value. - [InlineData(2, BitRateUnit.BitPerSecond, 1, BitRateUnit.BytePerSecond, false)] // Different value and unit. - [InlineData(1, BitRateUnit.BitPerSecond, 1, BitRateUnit.BytePerSecond, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, BitRateUnit unitA, double valueB, BitRateUnit unitB, bool expectEqual) { var a = new BitRate(valueA, unitA); @@ -1388,8 +1403,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = BitRate.FromBitsPerSecond(firstValue); var otherQuantity = BitRate.FromBitsPerSecond(secondValue); BitRate maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, BitRate.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1408,7 +1423,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1421,6 +1436,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(BitRate.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(BitRate.Info.Units, BitRate.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, BitRate.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1559,7 +1586,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = BitRate.FromBitsPerSecond(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(BitRate), quantity.As(BitRate.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs index 79b8e77ca1..2bcc6da5ff 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/BrakeSpecificFuelConsumptionTestsBase.g.cs @@ -133,6 +133,20 @@ public void BrakeSpecificFuelConsumption_QuantityInfo_ReturnsQuantityInfoDescrib Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void BrakeSpecificFuelConsumptionInfo_CreateWithCustomUnitInfos() + { + BrakeSpecificFuelConsumptionUnit[] expectedUnits = [BrakeSpecificFuelConsumptionUnit.KilogramPerJoule]; + + BrakeSpecificFuelConsumption.BrakeSpecificFuelConsumptionInfo quantityInfo = BrakeSpecificFuelConsumption.BrakeSpecificFuelConsumptionInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("BrakeSpecificFuelConsumption", quantityInfo.Name); + Assert.Equal(BrakeSpecificFuelConsumption.Zero, quantityInfo.Zero); + Assert.Equal(BrakeSpecificFuelConsumption.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void KilogramPerJouleToBrakeSpecificFuelConsumptionUnits() { @@ -290,7 +304,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 g/kWh", BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, 4.2)] [InlineData("en-US", "4.2 kg/J", BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, 4.2)] [InlineData("en-US", "4.2 lb/hph", BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, 4.2)] - public void Parse(string culture, string quantityString, BrakeSpecificFuelConsumptionUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, BrakeSpecificFuelConsumptionUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = BrakeSpecificFuelConsumption.Parse(quantityString); @@ -302,7 +316,7 @@ public void Parse(string culture, string quantityString, BrakeSpecificFuelConsum [InlineData("en-US", "4.2 g/kWh", BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, 4.2)] [InlineData("en-US", "4.2 kg/J", BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, 4.2)] [InlineData("en-US", "4.2 lb/hph", BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, 4.2)] - public void TryParse(string culture, string quantityString, BrakeSpecificFuelConsumptionUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, BrakeSpecificFuelConsumptionUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(BrakeSpecificFuelConsumption.TryParse(quantityString, out BrakeSpecificFuelConsumption parsed)); @@ -453,6 +467,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(BrakeSpecificFue var quantity = BrakeSpecificFuelConsumption.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -476,34 +491,36 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(BrakeSpecificFuelCo IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - BrakeSpecificFuelConsumption kilogramperjoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - AssertEx.EqualTolerance(1, BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(kilogramperjoule.GramsPerKiloWattHour).KilogramsPerJoule, GramsPerKiloWattHourTolerance); - AssertEx.EqualTolerance(1, BrakeSpecificFuelConsumption.FromKilogramsPerJoule(kilogramperjoule.KilogramsPerJoule).KilogramsPerJoule, KilogramsPerJouleTolerance); - AssertEx.EqualTolerance(1, BrakeSpecificFuelConsumption.FromPoundsPerMechanicalHorsepowerHour(kilogramperjoule.PoundsPerMechanicalHorsepowerHour).KilogramsPerJoule, PoundsPerMechanicalHorsepowerHourTolerance); + BrakeSpecificFuelConsumption kilogramperjoule = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(3); + Assert.Equal(3, BrakeSpecificFuelConsumption.FromGramsPerKiloWattHour(kilogramperjoule.GramsPerKiloWattHour).KilogramsPerJoule); + Assert.Equal(3, BrakeSpecificFuelConsumption.FromKilogramsPerJoule(kilogramperjoule.KilogramsPerJoule).KilogramsPerJoule); + Assert.Equal(3, BrakeSpecificFuelConsumption.FromPoundsPerMechanicalHorsepowerHour(kilogramperjoule.PoundsPerMechanicalHorsepowerHour).KilogramsPerJoule); } [Fact] public void ArithmeticOperators() { BrakeSpecificFuelConsumption v = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1); - AssertEx.EqualTolerance(-1, -v.KilogramsPerJoule, KilogramsPerJouleTolerance); - AssertEx.EqualTolerance(2, (BrakeSpecificFuelConsumption.FromKilogramsPerJoule(3)-v).KilogramsPerJoule, KilogramsPerJouleTolerance); - AssertEx.EqualTolerance(2, (v + v).KilogramsPerJoule, KilogramsPerJouleTolerance); - AssertEx.EqualTolerance(10, (v*10).KilogramsPerJoule, KilogramsPerJouleTolerance); - AssertEx.EqualTolerance(10, (10*v).KilogramsPerJoule, KilogramsPerJouleTolerance); - AssertEx.EqualTolerance(2, (BrakeSpecificFuelConsumption.FromKilogramsPerJoule(10)/5).KilogramsPerJoule, KilogramsPerJouleTolerance); - AssertEx.EqualTolerance(2, BrakeSpecificFuelConsumption.FromKilogramsPerJoule(10)/BrakeSpecificFuelConsumption.FromKilogramsPerJoule(5), KilogramsPerJouleTolerance); + Assert.Equal(-1, -v.KilogramsPerJoule); + Assert.Equal(2, (BrakeSpecificFuelConsumption.FromKilogramsPerJoule(3) - v).KilogramsPerJoule); + Assert.Equal(2, (v + v).KilogramsPerJoule); + Assert.Equal(10, (v * 10).KilogramsPerJoule); + Assert.Equal(10, (10 * v).KilogramsPerJoule); + Assert.Equal(2, (BrakeSpecificFuelConsumption.FromKilogramsPerJoule(10) / 5).KilogramsPerJoule); + Assert.Equal(2, BrakeSpecificFuelConsumption.FromKilogramsPerJoule(10) / BrakeSpecificFuelConsumption.FromKilogramsPerJoule(5)); } [Fact] @@ -549,8 +566,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, 1, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, true)] // Same value and unit. [InlineData(1, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, 2, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, false)] // Different value. - [InlineData(2, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, 1, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, false)] // Different value and unit. - [InlineData(1, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, 1, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, BrakeSpecificFuelConsumptionUnit unitA, double valueB, BrakeSpecificFuelConsumptionUnit unitB, bool expectEqual) { var a = new BrakeSpecificFuelConsumption(valueA, unitA); @@ -610,8 +625,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(firstValue); var otherQuantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(secondValue); BrakeSpecificFuelConsumption maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, BrakeSpecificFuelConsumption.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -630,7 +645,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -643,6 +658,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(BrakeSpecificFuelConsumption.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(BrakeSpecificFuelConsumption.Info.Units, BrakeSpecificFuelConsumption.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, BrakeSpecificFuelConsumption.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -709,7 +736,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = BrakeSpecificFuelConsumption.FromKilogramsPerJoule(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(BrakeSpecificFuelConsumption), quantity.As(BrakeSpecificFuelConsumption.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs index 16d3ded374..bca066537e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/CoefficientOfThermalExpansionTestsBase.g.cs @@ -145,6 +145,20 @@ public void CoefficientOfThermalExpansion_QuantityInfo_ReturnsQuantityInfoDescri Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void CoefficientOfThermalExpansionInfo_CreateWithCustomUnitInfos() + { + CoefficientOfThermalExpansionUnit[] expectedUnits = [CoefficientOfThermalExpansionUnit.PerKelvin]; + + CoefficientOfThermalExpansion.CoefficientOfThermalExpansionInfo quantityInfo = CoefficientOfThermalExpansion.CoefficientOfThermalExpansionInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("CoefficientOfThermalExpansion", quantityInfo.Name); + Assert.Equal(CoefficientOfThermalExpansion.Zero, quantityInfo.Zero); + Assert.Equal(CoefficientOfThermalExpansion.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void PerKelvinToCoefficientOfThermalExpansionUnits() { @@ -311,7 +325,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 ppm/°C", CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius, 4.2)] [InlineData("en-US", "4.2 ppm/°F", CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit, 4.2)] [InlineData("en-US", "4.2 ppm/K", CoefficientOfThermalExpansionUnit.PpmPerKelvin, 4.2)] - public void Parse(string culture, string quantityString, CoefficientOfThermalExpansionUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, CoefficientOfThermalExpansionUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = CoefficientOfThermalExpansion.Parse(quantityString); @@ -326,7 +340,7 @@ public void Parse(string culture, string quantityString, CoefficientOfThermalExp [InlineData("en-US", "4.2 ppm/°C", CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius, 4.2)] [InlineData("en-US", "4.2 ppm/°F", CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit, 4.2)] [InlineData("en-US", "4.2 ppm/K", CoefficientOfThermalExpansionUnit.PpmPerKelvin, 4.2)] - public void TryParse(string culture, string quantityString, CoefficientOfThermalExpansionUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, CoefficientOfThermalExpansionUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(CoefficientOfThermalExpansion.TryParse(quantityString, out CoefficientOfThermalExpansion parsed)); @@ -504,6 +518,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(CoefficientOfThe var quantity = CoefficientOfThermalExpansion.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -527,37 +542,39 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(CoefficientOfTherma IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - CoefficientOfThermalExpansion perkelvin = CoefficientOfThermalExpansion.FromPerKelvin(1); - AssertEx.EqualTolerance(1, CoefficientOfThermalExpansion.FromPerDegreeCelsius(perkelvin.PerDegreeCelsius).PerKelvin, PerDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, CoefficientOfThermalExpansion.FromPerDegreeFahrenheit(perkelvin.PerDegreeFahrenheit).PerKelvin, PerDegreeFahrenheitTolerance); - AssertEx.EqualTolerance(1, CoefficientOfThermalExpansion.FromPerKelvin(perkelvin.PerKelvin).PerKelvin, PerKelvinTolerance); - AssertEx.EqualTolerance(1, CoefficientOfThermalExpansion.FromPpmPerDegreeCelsius(perkelvin.PpmPerDegreeCelsius).PerKelvin, PpmPerDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, CoefficientOfThermalExpansion.FromPpmPerDegreeFahrenheit(perkelvin.PpmPerDegreeFahrenheit).PerKelvin, PpmPerDegreeFahrenheitTolerance); - AssertEx.EqualTolerance(1, CoefficientOfThermalExpansion.FromPpmPerKelvin(perkelvin.PpmPerKelvin).PerKelvin, PpmPerKelvinTolerance); + CoefficientOfThermalExpansion perkelvin = CoefficientOfThermalExpansion.FromPerKelvin(3); + Assert.Equal(3, CoefficientOfThermalExpansion.FromPerDegreeCelsius(perkelvin.PerDegreeCelsius).PerKelvin); + Assert.Equal(3, CoefficientOfThermalExpansion.FromPerDegreeFahrenheit(perkelvin.PerDegreeFahrenheit).PerKelvin); + Assert.Equal(3, CoefficientOfThermalExpansion.FromPerKelvin(perkelvin.PerKelvin).PerKelvin); + Assert.Equal(3, CoefficientOfThermalExpansion.FromPpmPerDegreeCelsius(perkelvin.PpmPerDegreeCelsius).PerKelvin); + Assert.Equal(3, CoefficientOfThermalExpansion.FromPpmPerDegreeFahrenheit(perkelvin.PpmPerDegreeFahrenheit).PerKelvin); + Assert.Equal(3, CoefficientOfThermalExpansion.FromPpmPerKelvin(perkelvin.PpmPerKelvin).PerKelvin); } [Fact] public void ArithmeticOperators() { CoefficientOfThermalExpansion v = CoefficientOfThermalExpansion.FromPerKelvin(1); - AssertEx.EqualTolerance(-1, -v.PerKelvin, PerKelvinTolerance); - AssertEx.EqualTolerance(2, (CoefficientOfThermalExpansion.FromPerKelvin(3)-v).PerKelvin, PerKelvinTolerance); - AssertEx.EqualTolerance(2, (v + v).PerKelvin, PerKelvinTolerance); - AssertEx.EqualTolerance(10, (v*10).PerKelvin, PerKelvinTolerance); - AssertEx.EqualTolerance(10, (10*v).PerKelvin, PerKelvinTolerance); - AssertEx.EqualTolerance(2, (CoefficientOfThermalExpansion.FromPerKelvin(10)/5).PerKelvin, PerKelvinTolerance); - AssertEx.EqualTolerance(2, CoefficientOfThermalExpansion.FromPerKelvin(10)/CoefficientOfThermalExpansion.FromPerKelvin(5), PerKelvinTolerance); + Assert.Equal(-1, -v.PerKelvin); + Assert.Equal(2, (CoefficientOfThermalExpansion.FromPerKelvin(3) - v).PerKelvin); + Assert.Equal(2, (v + v).PerKelvin); + Assert.Equal(10, (v * 10).PerKelvin); + Assert.Equal(10, (10 * v).PerKelvin); + Assert.Equal(2, (CoefficientOfThermalExpansion.FromPerKelvin(10) / 5).PerKelvin); + Assert.Equal(2, CoefficientOfThermalExpansion.FromPerKelvin(10) / CoefficientOfThermalExpansion.FromPerKelvin(5)); } [Fact] @@ -603,8 +620,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, CoefficientOfThermalExpansionUnit.PerKelvin, 1, CoefficientOfThermalExpansionUnit.PerKelvin, true)] // Same value and unit. [InlineData(1, CoefficientOfThermalExpansionUnit.PerKelvin, 2, CoefficientOfThermalExpansionUnit.PerKelvin, false)] // Different value. - [InlineData(2, CoefficientOfThermalExpansionUnit.PerKelvin, 1, CoefficientOfThermalExpansionUnit.PerDegreeCelsius, false)] // Different value and unit. - [InlineData(1, CoefficientOfThermalExpansionUnit.PerKelvin, 1, CoefficientOfThermalExpansionUnit.PerDegreeCelsius, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, CoefficientOfThermalExpansionUnit unitA, double valueB, CoefficientOfThermalExpansionUnit unitB, bool expectEqual) { var a = new CoefficientOfThermalExpansion(valueA, unitA); @@ -664,8 +679,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = CoefficientOfThermalExpansion.FromPerKelvin(firstValue); var otherQuantity = CoefficientOfThermalExpansion.FromPerKelvin(secondValue); CoefficientOfThermalExpansion maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, CoefficientOfThermalExpansion.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -684,7 +699,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -697,6 +712,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(CoefficientOfThermalExpansion.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(CoefficientOfThermalExpansion.Info.Units, CoefficientOfThermalExpansion.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, CoefficientOfThermalExpansion.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -769,7 +796,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = CoefficientOfThermalExpansion.FromPerKelvin(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(CoefficientOfThermalExpansion), quantity.As(CoefficientOfThermalExpansion.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/CompressibilityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/CompressibilityTestsBase.g.cs index 352de0fc8c..6e4fb17237 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/CompressibilityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/CompressibilityTestsBase.g.cs @@ -149,6 +149,20 @@ public void Compressibility_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void CompressibilityInfo_CreateWithCustomUnitInfos() + { + CompressibilityUnit[] expectedUnits = [CompressibilityUnit.InversePascal]; + + Compressibility.CompressibilityInfo quantityInfo = Compressibility.CompressibilityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Compressibility", quantityInfo.Name); + Assert.Equal(Compressibility.Zero, quantityInfo.Zero); + Assert.Equal(Compressibility.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void InversePascalToCompressibilityUnits() { @@ -325,7 +339,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 1/Pa", CompressibilityUnit.InversePascal, 4.2)] [InlineData("en-US", "4.2 psi⁻¹", CompressibilityUnit.InversePoundForcePerSquareInch, 4.2)] [InlineData("en-US", "4.2 1/psi", CompressibilityUnit.InversePoundForcePerSquareInch, 4.2)] - public void Parse(string culture, string quantityString, CompressibilityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, CompressibilityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Compressibility.Parse(quantityString); @@ -348,7 +362,7 @@ public void Parse(string culture, string quantityString, CompressibilityUnit exp [InlineData("en-US", "4.2 1/Pa", CompressibilityUnit.InversePascal, 4.2)] [InlineData("en-US", "4.2 psi⁻¹", CompressibilityUnit.InversePoundForcePerSquareInch, 4.2)] [InlineData("en-US", "4.2 1/psi", CompressibilityUnit.InversePoundForcePerSquareInch, 4.2)] - public void TryParse(string culture, string quantityString, CompressibilityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, CompressibilityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Compressibility.TryParse(quantityString, out Compressibility parsed)); @@ -591,6 +605,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(CompressibilityU var quantity = Compressibility.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -614,38 +629,40 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(CompressibilityUnit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Compressibility inversepascal = Compressibility.FromInversePascals(1); - AssertEx.EqualTolerance(1, Compressibility.FromInverseAtmospheres(inversepascal.InverseAtmospheres).InversePascals, InverseAtmospheresTolerance); - AssertEx.EqualTolerance(1, Compressibility.FromInverseBars(inversepascal.InverseBars).InversePascals, InverseBarsTolerance); - AssertEx.EqualTolerance(1, Compressibility.FromInverseKilopascals(inversepascal.InverseKilopascals).InversePascals, InverseKilopascalsTolerance); - AssertEx.EqualTolerance(1, Compressibility.FromInverseMegapascals(inversepascal.InverseMegapascals).InversePascals, InverseMegapascalsTolerance); - AssertEx.EqualTolerance(1, Compressibility.FromInverseMillibars(inversepascal.InverseMillibars).InversePascals, InverseMillibarsTolerance); - AssertEx.EqualTolerance(1, Compressibility.FromInversePascals(inversepascal.InversePascals).InversePascals, InversePascalsTolerance); - AssertEx.EqualTolerance(1, Compressibility.FromInversePoundsForcePerSquareInch(inversepascal.InversePoundsForcePerSquareInch).InversePascals, InversePoundsForcePerSquareInchTolerance); + Compressibility inversepascal = Compressibility.FromInversePascals(3); + Assert.Equal(3, Compressibility.FromInverseAtmospheres(inversepascal.InverseAtmospheres).InversePascals); + Assert.Equal(3, Compressibility.FromInverseBars(inversepascal.InverseBars).InversePascals); + Assert.Equal(3, Compressibility.FromInverseKilopascals(inversepascal.InverseKilopascals).InversePascals); + Assert.Equal(3, Compressibility.FromInverseMegapascals(inversepascal.InverseMegapascals).InversePascals); + Assert.Equal(3, Compressibility.FromInverseMillibars(inversepascal.InverseMillibars).InversePascals); + Assert.Equal(3, Compressibility.FromInversePascals(inversepascal.InversePascals).InversePascals); + Assert.Equal(3, Compressibility.FromInversePoundsForcePerSquareInch(inversepascal.InversePoundsForcePerSquareInch).InversePascals); } [Fact] public void ArithmeticOperators() { Compressibility v = Compressibility.FromInversePascals(1); - AssertEx.EqualTolerance(-1, -v.InversePascals, InversePascalsTolerance); - AssertEx.EqualTolerance(2, (Compressibility.FromInversePascals(3)-v).InversePascals, InversePascalsTolerance); - AssertEx.EqualTolerance(2, (v + v).InversePascals, InversePascalsTolerance); - AssertEx.EqualTolerance(10, (v*10).InversePascals, InversePascalsTolerance); - AssertEx.EqualTolerance(10, (10*v).InversePascals, InversePascalsTolerance); - AssertEx.EqualTolerance(2, (Compressibility.FromInversePascals(10)/5).InversePascals, InversePascalsTolerance); - AssertEx.EqualTolerance(2, Compressibility.FromInversePascals(10)/Compressibility.FromInversePascals(5), InversePascalsTolerance); + Assert.Equal(-1, -v.InversePascals); + Assert.Equal(2, (Compressibility.FromInversePascals(3) - v).InversePascals); + Assert.Equal(2, (v + v).InversePascals); + Assert.Equal(10, (v * 10).InversePascals); + Assert.Equal(10, (10 * v).InversePascals); + Assert.Equal(2, (Compressibility.FromInversePascals(10) / 5).InversePascals); + Assert.Equal(2, Compressibility.FromInversePascals(10) / Compressibility.FromInversePascals(5)); } [Fact] @@ -691,8 +708,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, CompressibilityUnit.InversePascal, 1, CompressibilityUnit.InversePascal, true)] // Same value and unit. [InlineData(1, CompressibilityUnit.InversePascal, 2, CompressibilityUnit.InversePascal, false)] // Different value. - [InlineData(2, CompressibilityUnit.InversePascal, 1, CompressibilityUnit.InverseAtmosphere, false)] // Different value and unit. - [InlineData(1, CompressibilityUnit.InversePascal, 1, CompressibilityUnit.InverseAtmosphere, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, CompressibilityUnit unitA, double valueB, CompressibilityUnit unitB, bool expectEqual) { var a = new Compressibility(valueA, unitA); @@ -752,8 +767,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Compressibility.FromInversePascals(firstValue); var otherQuantity = Compressibility.FromInversePascals(secondValue); Compressibility maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Compressibility.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -772,7 +787,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -785,6 +800,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Compressibility.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Compressibility.Info.Units, Compressibility.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Compressibility.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -859,7 +886,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Compressibility.FromInversePascals(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Compressibility), quantity.As(Compressibility.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs index ec5fe0b0ab..6fefd78d1a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/DensityTestsBase.g.cs @@ -345,6 +345,20 @@ public void Density_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void DensityInfo_CreateWithCustomUnitInfos() + { + DensityUnit[] expectedUnits = [DensityUnit.KilogramPerCubicMeter]; + + Density.DensityInfo quantityInfo = Density.DensityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Density", quantityInfo.Name); + Assert.Equal(Density.Zero, quantityInfo.Zero); + Assert.Equal(Density.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void KilogramPerCubicMeterToDensityUnits() { @@ -671,7 +685,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 кг/м³", DensityUnit.KilogramPerCubicMeter, 4.2)] [InlineData("ru-RU", "4,2 мкг/м³", DensityUnit.MicrogramPerCubicMeter, 4.2)] [InlineData("ru-RU", "4,2 мг/м³", DensityUnit.MilligramPerCubicMeter, 4.2)] - public void Parse(string culture, string quantityString, DensityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, DensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Density.Parse(quantityString); @@ -746,7 +760,7 @@ public void Parse(string culture, string quantityString, DensityUnit expectedUni [InlineData("ru-RU", "4,2 кг/м³", DensityUnit.KilogramPerCubicMeter, 4.2)] [InlineData("ru-RU", "4,2 мкг/м³", DensityUnit.MicrogramPerCubicMeter, 4.2)] [InlineData("ru-RU", "4,2 мг/м³", DensityUnit.MilligramPerCubicMeter, 4.2)] - public void TryParse(string culture, string quantityString, DensityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, DensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Density.TryParse(quantityString, out Density parsed)); @@ -1442,6 +1456,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(DensityUnit unit var quantity = Density.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -1465,87 +1480,89 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(DensityUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Density kilogrampercubicmeter = Density.FromKilogramsPerCubicMeter(1); - AssertEx.EqualTolerance(1, Density.FromCentigramsPerDeciliter(kilogrampercubicmeter.CentigramsPerDeciliter).KilogramsPerCubicMeter, CentigramsPerDeciliterTolerance); - AssertEx.EqualTolerance(1, Density.FromCentigramsPerLiter(kilogrampercubicmeter.CentigramsPerLiter).KilogramsPerCubicMeter, CentigramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromCentigramsPerMilliliter(kilogrampercubicmeter.CentigramsPerMilliliter).KilogramsPerCubicMeter, CentigramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.FromDecigramsPerDeciliter(kilogrampercubicmeter.DecigramsPerDeciliter).KilogramsPerCubicMeter, DecigramsPerDeciliterTolerance); - AssertEx.EqualTolerance(1, Density.FromDecigramsPerLiter(kilogrampercubicmeter.DecigramsPerLiter).KilogramsPerCubicMeter, DecigramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromDecigramsPerMilliliter(kilogrampercubicmeter.DecigramsPerMilliliter).KilogramsPerCubicMeter, DecigramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.FromFemtogramsPerDeciliter(kilogrampercubicmeter.FemtogramsPerDeciliter).KilogramsPerCubicMeter, FemtogramsPerDeciliterTolerance); - AssertEx.EqualTolerance(1, Density.FromFemtogramsPerLiter(kilogrampercubicmeter.FemtogramsPerLiter).KilogramsPerCubicMeter, FemtogramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromFemtogramsPerMilliliter(kilogrampercubicmeter.FemtogramsPerMilliliter).KilogramsPerCubicMeter, FemtogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.FromGramsPerCubicCentimeter(kilogrampercubicmeter.GramsPerCubicCentimeter).KilogramsPerCubicMeter, GramsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, Density.FromGramsPerCubicFoot(kilogrampercubicmeter.GramsPerCubicFoot).KilogramsPerCubicMeter, GramsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, Density.FromGramsPerCubicInch(kilogrampercubicmeter.GramsPerCubicInch).KilogramsPerCubicMeter, GramsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, Density.FromGramsPerCubicMeter(kilogrampercubicmeter.GramsPerCubicMeter).KilogramsPerCubicMeter, GramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Density.FromGramsPerCubicMillimeter(kilogrampercubicmeter.GramsPerCubicMillimeter).KilogramsPerCubicMeter, GramsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, Density.FromGramsPerDeciliter(kilogrampercubicmeter.GramsPerDeciliter).KilogramsPerCubicMeter, GramsPerDeciliterTolerance); - AssertEx.EqualTolerance(1, Density.FromGramsPerLiter(kilogrampercubicmeter.GramsPerLiter).KilogramsPerCubicMeter, GramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromGramsPerMilliliter(kilogrampercubicmeter.GramsPerMilliliter).KilogramsPerCubicMeter, GramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.FromKilogramsPerCubicCentimeter(kilogrampercubicmeter.KilogramsPerCubicCentimeter).KilogramsPerCubicMeter, KilogramsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, Density.FromKilogramsPerCubicMeter(kilogrampercubicmeter.KilogramsPerCubicMeter).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Density.FromKilogramsPerCubicMillimeter(kilogrampercubicmeter.KilogramsPerCubicMillimeter).KilogramsPerCubicMeter, KilogramsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, Density.FromKilogramsPerLiter(kilogrampercubicmeter.KilogramsPerLiter).KilogramsPerCubicMeter, KilogramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromKilopoundsPerCubicFoot(kilogrampercubicmeter.KilopoundsPerCubicFoot).KilogramsPerCubicMeter, KilopoundsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, Density.FromKilopoundsPerCubicInch(kilogrampercubicmeter.KilopoundsPerCubicInch).KilogramsPerCubicMeter, KilopoundsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, Density.FromKilopoundsPerCubicYard(kilogrampercubicmeter.KilopoundsPerCubicYard).KilogramsPerCubicMeter, KilopoundsPerCubicYardTolerance); - AssertEx.EqualTolerance(1, Density.FromMicrogramsPerCubicMeter(kilogrampercubicmeter.MicrogramsPerCubicMeter).KilogramsPerCubicMeter, MicrogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Density.FromMicrogramsPerDeciliter(kilogrampercubicmeter.MicrogramsPerDeciliter).KilogramsPerCubicMeter, MicrogramsPerDeciliterTolerance); - AssertEx.EqualTolerance(1, Density.FromMicrogramsPerLiter(kilogrampercubicmeter.MicrogramsPerLiter).KilogramsPerCubicMeter, MicrogramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromMicrogramsPerMilliliter(kilogrampercubicmeter.MicrogramsPerMilliliter).KilogramsPerCubicMeter, MicrogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.FromMilligramsPerCubicMeter(kilogrampercubicmeter.MilligramsPerCubicMeter).KilogramsPerCubicMeter, MilligramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Density.FromMilligramsPerDeciliter(kilogrampercubicmeter.MilligramsPerDeciliter).KilogramsPerCubicMeter, MilligramsPerDeciliterTolerance); - AssertEx.EqualTolerance(1, Density.FromMilligramsPerLiter(kilogrampercubicmeter.MilligramsPerLiter).KilogramsPerCubicMeter, MilligramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromMilligramsPerMilliliter(kilogrampercubicmeter.MilligramsPerMilliliter).KilogramsPerCubicMeter, MilligramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.FromNanogramsPerDeciliter(kilogrampercubicmeter.NanogramsPerDeciliter).KilogramsPerCubicMeter, NanogramsPerDeciliterTolerance); - AssertEx.EqualTolerance(1, Density.FromNanogramsPerLiter(kilogrampercubicmeter.NanogramsPerLiter).KilogramsPerCubicMeter, NanogramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromNanogramsPerMilliliter(kilogrampercubicmeter.NanogramsPerMilliliter).KilogramsPerCubicMeter, NanogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.FromPicogramsPerDeciliter(kilogrampercubicmeter.PicogramsPerDeciliter).KilogramsPerCubicMeter, PicogramsPerDeciliterTolerance); - AssertEx.EqualTolerance(1, Density.FromPicogramsPerLiter(kilogrampercubicmeter.PicogramsPerLiter).KilogramsPerCubicMeter, PicogramsPerLiterTolerance); - AssertEx.EqualTolerance(1, Density.FromPicogramsPerMilliliter(kilogrampercubicmeter.PicogramsPerMilliliter).KilogramsPerCubicMeter, PicogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, Density.FromPoundsPerCubicCentimeter(kilogrampercubicmeter.PoundsPerCubicCentimeter).KilogramsPerCubicMeter, PoundsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, Density.FromPoundsPerCubicFoot(kilogrampercubicmeter.PoundsPerCubicFoot).KilogramsPerCubicMeter, PoundsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, Density.FromPoundsPerCubicInch(kilogrampercubicmeter.PoundsPerCubicInch).KilogramsPerCubicMeter, PoundsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, Density.FromPoundsPerCubicMeter(kilogrampercubicmeter.PoundsPerCubicMeter).KilogramsPerCubicMeter, PoundsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Density.FromPoundsPerCubicMillimeter(kilogrampercubicmeter.PoundsPerCubicMillimeter).KilogramsPerCubicMeter, PoundsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, Density.FromPoundsPerCubicYard(kilogrampercubicmeter.PoundsPerCubicYard).KilogramsPerCubicMeter, PoundsPerCubicYardTolerance); - AssertEx.EqualTolerance(1, Density.FromPoundsPerImperialGallon(kilogrampercubicmeter.PoundsPerImperialGallon).KilogramsPerCubicMeter, PoundsPerImperialGallonTolerance); - AssertEx.EqualTolerance(1, Density.FromPoundsPerUSGallon(kilogrampercubicmeter.PoundsPerUSGallon).KilogramsPerCubicMeter, PoundsPerUSGallonTolerance); - AssertEx.EqualTolerance(1, Density.FromSlugsPerCubicCentimeter(kilogrampercubicmeter.SlugsPerCubicCentimeter).KilogramsPerCubicMeter, SlugsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, Density.FromSlugsPerCubicFoot(kilogrampercubicmeter.SlugsPerCubicFoot).KilogramsPerCubicMeter, SlugsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, Density.FromSlugsPerCubicInch(kilogrampercubicmeter.SlugsPerCubicInch).KilogramsPerCubicMeter, SlugsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, Density.FromSlugsPerCubicMeter(kilogrampercubicmeter.SlugsPerCubicMeter).KilogramsPerCubicMeter, SlugsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Density.FromSlugsPerCubicMillimeter(kilogrampercubicmeter.SlugsPerCubicMillimeter).KilogramsPerCubicMeter, SlugsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, Density.FromTonnesPerCubicCentimeter(kilogrampercubicmeter.TonnesPerCubicCentimeter).KilogramsPerCubicMeter, TonnesPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, Density.FromTonnesPerCubicFoot(kilogrampercubicmeter.TonnesPerCubicFoot).KilogramsPerCubicMeter, TonnesPerCubicFootTolerance); - AssertEx.EqualTolerance(1, Density.FromTonnesPerCubicInch(kilogrampercubicmeter.TonnesPerCubicInch).KilogramsPerCubicMeter, TonnesPerCubicInchTolerance); - AssertEx.EqualTolerance(1, Density.FromTonnesPerCubicMeter(kilogrampercubicmeter.TonnesPerCubicMeter).KilogramsPerCubicMeter, TonnesPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Density.FromTonnesPerCubicMillimeter(kilogrampercubicmeter.TonnesPerCubicMillimeter).KilogramsPerCubicMeter, TonnesPerCubicMillimeterTolerance); + Density kilogrampercubicmeter = Density.FromKilogramsPerCubicMeter(3); + Assert.Equal(3, Density.FromCentigramsPerDeciliter(kilogrampercubicmeter.CentigramsPerDeciliter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromCentigramsPerLiter(kilogrampercubicmeter.CentigramsPerLiter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromCentigramsPerMilliliter(kilogrampercubicmeter.CentigramsPerMilliliter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromDecigramsPerDeciliter(kilogrampercubicmeter.DecigramsPerDeciliter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromDecigramsPerLiter(kilogrampercubicmeter.DecigramsPerLiter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromDecigramsPerMilliliter(kilogrampercubicmeter.DecigramsPerMilliliter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromFemtogramsPerDeciliter(kilogrampercubicmeter.FemtogramsPerDeciliter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromFemtogramsPerLiter(kilogrampercubicmeter.FemtogramsPerLiter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromFemtogramsPerMilliliter(kilogrampercubicmeter.FemtogramsPerMilliliter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromGramsPerCubicCentimeter(kilogrampercubicmeter.GramsPerCubicCentimeter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromGramsPerCubicFoot(kilogrampercubicmeter.GramsPerCubicFoot).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromGramsPerCubicInch(kilogrampercubicmeter.GramsPerCubicInch).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromGramsPerCubicMeter(kilogrampercubicmeter.GramsPerCubicMeter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromGramsPerCubicMillimeter(kilogrampercubicmeter.GramsPerCubicMillimeter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromGramsPerDeciliter(kilogrampercubicmeter.GramsPerDeciliter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromGramsPerLiter(kilogrampercubicmeter.GramsPerLiter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromGramsPerMilliliter(kilogrampercubicmeter.GramsPerMilliliter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromKilogramsPerCubicCentimeter(kilogrampercubicmeter.KilogramsPerCubicCentimeter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromKilogramsPerCubicMeter(kilogrampercubicmeter.KilogramsPerCubicMeter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromKilogramsPerCubicMillimeter(kilogrampercubicmeter.KilogramsPerCubicMillimeter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromKilogramsPerLiter(kilogrampercubicmeter.KilogramsPerLiter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromKilopoundsPerCubicFoot(kilogrampercubicmeter.KilopoundsPerCubicFoot).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromKilopoundsPerCubicInch(kilogrampercubicmeter.KilopoundsPerCubicInch).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromKilopoundsPerCubicYard(kilogrampercubicmeter.KilopoundsPerCubicYard).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromMicrogramsPerCubicMeter(kilogrampercubicmeter.MicrogramsPerCubicMeter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromMicrogramsPerDeciliter(kilogrampercubicmeter.MicrogramsPerDeciliter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromMicrogramsPerLiter(kilogrampercubicmeter.MicrogramsPerLiter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromMicrogramsPerMilliliter(kilogrampercubicmeter.MicrogramsPerMilliliter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromMilligramsPerCubicMeter(kilogrampercubicmeter.MilligramsPerCubicMeter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromMilligramsPerDeciliter(kilogrampercubicmeter.MilligramsPerDeciliter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromMilligramsPerLiter(kilogrampercubicmeter.MilligramsPerLiter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromMilligramsPerMilliliter(kilogrampercubicmeter.MilligramsPerMilliliter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromNanogramsPerDeciliter(kilogrampercubicmeter.NanogramsPerDeciliter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromNanogramsPerLiter(kilogrampercubicmeter.NanogramsPerLiter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromNanogramsPerMilliliter(kilogrampercubicmeter.NanogramsPerMilliliter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromPicogramsPerDeciliter(kilogrampercubicmeter.PicogramsPerDeciliter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromPicogramsPerLiter(kilogrampercubicmeter.PicogramsPerLiter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromPicogramsPerMilliliter(kilogrampercubicmeter.PicogramsPerMilliliter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromPoundsPerCubicCentimeter(kilogrampercubicmeter.PoundsPerCubicCentimeter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromPoundsPerCubicFoot(kilogrampercubicmeter.PoundsPerCubicFoot).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromPoundsPerCubicInch(kilogrampercubicmeter.PoundsPerCubicInch).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromPoundsPerCubicMeter(kilogrampercubicmeter.PoundsPerCubicMeter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromPoundsPerCubicMillimeter(kilogrampercubicmeter.PoundsPerCubicMillimeter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromPoundsPerCubicYard(kilogrampercubicmeter.PoundsPerCubicYard).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromPoundsPerImperialGallon(kilogrampercubicmeter.PoundsPerImperialGallon).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromPoundsPerUSGallon(kilogrampercubicmeter.PoundsPerUSGallon).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromSlugsPerCubicCentimeter(kilogrampercubicmeter.SlugsPerCubicCentimeter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromSlugsPerCubicFoot(kilogrampercubicmeter.SlugsPerCubicFoot).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromSlugsPerCubicInch(kilogrampercubicmeter.SlugsPerCubicInch).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromSlugsPerCubicMeter(kilogrampercubicmeter.SlugsPerCubicMeter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromSlugsPerCubicMillimeter(kilogrampercubicmeter.SlugsPerCubicMillimeter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromTonnesPerCubicCentimeter(kilogrampercubicmeter.TonnesPerCubicCentimeter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromTonnesPerCubicFoot(kilogrampercubicmeter.TonnesPerCubicFoot).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromTonnesPerCubicInch(kilogrampercubicmeter.TonnesPerCubicInch).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromTonnesPerCubicMeter(kilogrampercubicmeter.TonnesPerCubicMeter).KilogramsPerCubicMeter); + Assert.Equal(3, Density.FromTonnesPerCubicMillimeter(kilogrampercubicmeter.TonnesPerCubicMillimeter).KilogramsPerCubicMeter); } [Fact] public void ArithmeticOperators() { Density v = Density.FromKilogramsPerCubicMeter(1); - AssertEx.EqualTolerance(-1, -v.KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (Density.FromKilogramsPerCubicMeter(3)-v).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (Density.FromKilogramsPerCubicMeter(10)/5).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, Density.FromKilogramsPerCubicMeter(10)/Density.FromKilogramsPerCubicMeter(5), KilogramsPerCubicMeterTolerance); + Assert.Equal(-1, -v.KilogramsPerCubicMeter); + Assert.Equal(2, (Density.FromKilogramsPerCubicMeter(3) - v).KilogramsPerCubicMeter); + Assert.Equal(2, (v + v).KilogramsPerCubicMeter); + Assert.Equal(10, (v * 10).KilogramsPerCubicMeter); + Assert.Equal(10, (10 * v).KilogramsPerCubicMeter); + Assert.Equal(2, (Density.FromKilogramsPerCubicMeter(10) / 5).KilogramsPerCubicMeter); + Assert.Equal(2, Density.FromKilogramsPerCubicMeter(10) / Density.FromKilogramsPerCubicMeter(5)); } [Fact] @@ -1591,8 +1608,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, DensityUnit.KilogramPerCubicMeter, 1, DensityUnit.KilogramPerCubicMeter, true)] // Same value and unit. [InlineData(1, DensityUnit.KilogramPerCubicMeter, 2, DensityUnit.KilogramPerCubicMeter, false)] // Different value. - [InlineData(2, DensityUnit.KilogramPerCubicMeter, 1, DensityUnit.CentigramPerDeciliter, false)] // Different value and unit. - [InlineData(1, DensityUnit.KilogramPerCubicMeter, 1, DensityUnit.CentigramPerDeciliter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, DensityUnit unitA, double valueB, DensityUnit unitB, bool expectEqual) { var a = new Density(valueA, unitA); @@ -1652,8 +1667,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Density.FromKilogramsPerCubicMeter(firstValue); var otherQuantity = Density.FromKilogramsPerCubicMeter(secondValue); Density maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Density.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1672,7 +1687,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1685,6 +1700,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Density.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Density.Info.Units, Density.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Density.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1857,7 +1884,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Density.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Density), quantity.As(Density.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/DoseAreaProductTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/DoseAreaProductTestsBase.g.cs index bd00cbf085..e62248b167 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/DoseAreaProductTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/DoseAreaProductTestsBase.g.cs @@ -221,6 +221,20 @@ public void DoseAreaProduct_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void DoseAreaProductInfo_CreateWithCustomUnitInfos() + { + DoseAreaProductUnit[] expectedUnits = [DoseAreaProductUnit.GraySquareMeter]; + + DoseAreaProduct.DoseAreaProductInfo quantityInfo = DoseAreaProduct.DoseAreaProductInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("DoseAreaProduct", quantityInfo.Name); + Assert.Equal(DoseAreaProduct.Zero, quantityInfo.Zero); + Assert.Equal(DoseAreaProduct.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void GraySquareMeterToDoseAreaProductUnits() { @@ -469,7 +483,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 мГр·м²", DoseAreaProductUnit.MilligraySquareMeter, 4.2)] [InlineData("ru-RU", "4,2 мГр·мкм²", DoseAreaProductUnit.MilligraySquareMicrometer, 4.2)] [InlineData("ru-RU", "4,2 мГр·мм²", DoseAreaProductUnit.MilligraySquareMillimeter, 4.2)] - public void Parse(string culture, string quantityString, DoseAreaProductUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, DoseAreaProductUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = DoseAreaProduct.Parse(quantityString); @@ -528,7 +542,7 @@ public void Parse(string culture, string quantityString, DoseAreaProductUnit exp [InlineData("ru-RU", "4,2 мГр·м²", DoseAreaProductUnit.MilligraySquareMeter, 4.2)] [InlineData("ru-RU", "4,2 мГр·мкм²", DoseAreaProductUnit.MilligraySquareMicrometer, 4.2)] [InlineData("ru-RU", "4,2 мГр·мм²", DoseAreaProductUnit.MilligraySquareMillimeter, 4.2)] - public void TryParse(string culture, string quantityString, DoseAreaProductUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, DoseAreaProductUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(DoseAreaProduct.TryParse(quantityString, out DoseAreaProduct parsed)); @@ -1002,6 +1016,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(DoseAreaProductU var quantity = DoseAreaProduct.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -1025,56 +1040,58 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(DoseAreaProductUnit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - DoseAreaProduct graysquaremeter = DoseAreaProduct.FromGraySquareMeters(1); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromCentigraySquareCentimeters(graysquaremeter.CentigraySquareCentimeters).GraySquareMeters, CentigraySquareCentimetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromCentigraySquareDecimeters(graysquaremeter.CentigraySquareDecimeters).GraySquareMeters, CentigraySquareDecimetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromCentigraySquareMeters(graysquaremeter.CentigraySquareMeters).GraySquareMeters, CentigraySquareMetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromCentigraySquareMicrometers(graysquaremeter.CentigraySquareMicrometers).GraySquareMeters, CentigraySquareMicrometersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromCentigraySquareMillimeters(graysquaremeter.CentigraySquareMillimeters).GraySquareMeters, CentigraySquareMillimetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromDecigraySquareCentimeters(graysquaremeter.DecigraySquareCentimeters).GraySquareMeters, DecigraySquareCentimetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromDecigraySquareDecimeters(graysquaremeter.DecigraySquareDecimeters).GraySquareMeters, DecigraySquareDecimetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromDecigraySquareMeters(graysquaremeter.DecigraySquareMeters).GraySquareMeters, DecigraySquareMetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromDecigraySquareMicrometers(graysquaremeter.DecigraySquareMicrometers).GraySquareMeters, DecigraySquareMicrometersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromDecigraySquareMillimeters(graysquaremeter.DecigraySquareMillimeters).GraySquareMeters, DecigraySquareMillimetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromGraySquareCentimeters(graysquaremeter.GraySquareCentimeters).GraySquareMeters, GraySquareCentimetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromGraySquareDecimeters(graysquaremeter.GraySquareDecimeters).GraySquareMeters, GraySquareDecimetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromGraySquareMeters(graysquaremeter.GraySquareMeters).GraySquareMeters, GraySquareMetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromGraySquareMicrometers(graysquaremeter.GraySquareMicrometers).GraySquareMeters, GraySquareMicrometersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromGraySquareMillimeters(graysquaremeter.GraySquareMillimeters).GraySquareMeters, GraySquareMillimetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromMicrograySquareCentimeters(graysquaremeter.MicrograySquareCentimeters).GraySquareMeters, MicrograySquareCentimetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromMicrograySquareDecimeters(graysquaremeter.MicrograySquareDecimeters).GraySquareMeters, MicrograySquareDecimetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromMicrograySquareMeters(graysquaremeter.MicrograySquareMeters).GraySquareMeters, MicrograySquareMetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromMicrograySquareMicrometers(graysquaremeter.MicrograySquareMicrometers).GraySquareMeters, MicrograySquareMicrometersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromMicrograySquareMillimeters(graysquaremeter.MicrograySquareMillimeters).GraySquareMeters, MicrograySquareMillimetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromMilligraySquareCentimeters(graysquaremeter.MilligraySquareCentimeters).GraySquareMeters, MilligraySquareCentimetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromMilligraySquareDecimeters(graysquaremeter.MilligraySquareDecimeters).GraySquareMeters, MilligraySquareDecimetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromMilligraySquareMeters(graysquaremeter.MilligraySquareMeters).GraySquareMeters, MilligraySquareMetersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromMilligraySquareMicrometers(graysquaremeter.MilligraySquareMicrometers).GraySquareMeters, MilligraySquareMicrometersTolerance); - AssertEx.EqualTolerance(1, DoseAreaProduct.FromMilligraySquareMillimeters(graysquaremeter.MilligraySquareMillimeters).GraySquareMeters, MilligraySquareMillimetersTolerance); + DoseAreaProduct graysquaremeter = DoseAreaProduct.FromGraySquareMeters(3); + Assert.Equal(3, DoseAreaProduct.FromCentigraySquareCentimeters(graysquaremeter.CentigraySquareCentimeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromCentigraySquareDecimeters(graysquaremeter.CentigraySquareDecimeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromCentigraySquareMeters(graysquaremeter.CentigraySquareMeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromCentigraySquareMicrometers(graysquaremeter.CentigraySquareMicrometers).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromCentigraySquareMillimeters(graysquaremeter.CentigraySquareMillimeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromDecigraySquareCentimeters(graysquaremeter.DecigraySquareCentimeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromDecigraySquareDecimeters(graysquaremeter.DecigraySquareDecimeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromDecigraySquareMeters(graysquaremeter.DecigraySquareMeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromDecigraySquareMicrometers(graysquaremeter.DecigraySquareMicrometers).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromDecigraySquareMillimeters(graysquaremeter.DecigraySquareMillimeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromGraySquareCentimeters(graysquaremeter.GraySquareCentimeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromGraySquareDecimeters(graysquaremeter.GraySquareDecimeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromGraySquareMeters(graysquaremeter.GraySquareMeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromGraySquareMicrometers(graysquaremeter.GraySquareMicrometers).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromGraySquareMillimeters(graysquaremeter.GraySquareMillimeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromMicrograySquareCentimeters(graysquaremeter.MicrograySquareCentimeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromMicrograySquareDecimeters(graysquaremeter.MicrograySquareDecimeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromMicrograySquareMeters(graysquaremeter.MicrograySquareMeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromMicrograySquareMicrometers(graysquaremeter.MicrograySquareMicrometers).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromMicrograySquareMillimeters(graysquaremeter.MicrograySquareMillimeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromMilligraySquareCentimeters(graysquaremeter.MilligraySquareCentimeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromMilligraySquareDecimeters(graysquaremeter.MilligraySquareDecimeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromMilligraySquareMeters(graysquaremeter.MilligraySquareMeters).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromMilligraySquareMicrometers(graysquaremeter.MilligraySquareMicrometers).GraySquareMeters); + Assert.Equal(3, DoseAreaProduct.FromMilligraySquareMillimeters(graysquaremeter.MilligraySquareMillimeters).GraySquareMeters); } [Fact] public void ArithmeticOperators() { DoseAreaProduct v = DoseAreaProduct.FromGraySquareMeters(1); - AssertEx.EqualTolerance(-1, -v.GraySquareMeters, GraySquareMetersTolerance); - AssertEx.EqualTolerance(2, (DoseAreaProduct.FromGraySquareMeters(3)-v).GraySquareMeters, GraySquareMetersTolerance); - AssertEx.EqualTolerance(2, (v + v).GraySquareMeters, GraySquareMetersTolerance); - AssertEx.EqualTolerance(10, (v*10).GraySquareMeters, GraySquareMetersTolerance); - AssertEx.EqualTolerance(10, (10*v).GraySquareMeters, GraySquareMetersTolerance); - AssertEx.EqualTolerance(2, (DoseAreaProduct.FromGraySquareMeters(10)/5).GraySquareMeters, GraySquareMetersTolerance); - AssertEx.EqualTolerance(2, DoseAreaProduct.FromGraySquareMeters(10)/DoseAreaProduct.FromGraySquareMeters(5), GraySquareMetersTolerance); + Assert.Equal(-1, -v.GraySquareMeters); + Assert.Equal(2, (DoseAreaProduct.FromGraySquareMeters(3) - v).GraySquareMeters); + Assert.Equal(2, (v + v).GraySquareMeters); + Assert.Equal(10, (v * 10).GraySquareMeters); + Assert.Equal(10, (10 * v).GraySquareMeters); + Assert.Equal(2, (DoseAreaProduct.FromGraySquareMeters(10) / 5).GraySquareMeters); + Assert.Equal(2, DoseAreaProduct.FromGraySquareMeters(10) / DoseAreaProduct.FromGraySquareMeters(5)); } [Fact] @@ -1120,8 +1137,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, DoseAreaProductUnit.GraySquareMeter, 1, DoseAreaProductUnit.GraySquareMeter, true)] // Same value and unit. [InlineData(1, DoseAreaProductUnit.GraySquareMeter, 2, DoseAreaProductUnit.GraySquareMeter, false)] // Different value. - [InlineData(2, DoseAreaProductUnit.GraySquareMeter, 1, DoseAreaProductUnit.CentigraySquareCentimeter, false)] // Different value and unit. - [InlineData(1, DoseAreaProductUnit.GraySquareMeter, 1, DoseAreaProductUnit.CentigraySquareCentimeter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, DoseAreaProductUnit unitA, double valueB, DoseAreaProductUnit unitB, bool expectEqual) { var a = new DoseAreaProduct(valueA, unitA); @@ -1181,8 +1196,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = DoseAreaProduct.FromGraySquareMeters(firstValue); var otherQuantity = DoseAreaProduct.FromGraySquareMeters(secondValue); DoseAreaProduct maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, DoseAreaProduct.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1201,7 +1216,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1214,6 +1229,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(DoseAreaProduct.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(DoseAreaProduct.Info.Units, DoseAreaProduct.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, DoseAreaProduct.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1324,7 +1351,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = DoseAreaProduct.FromGraySquareMeters(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(DoseAreaProduct), quantity.As(DoseAreaProduct.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs index 85c35c55cc..36a3d4cbd2 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/DurationTestsBase.g.cs @@ -173,6 +173,20 @@ public void Duration_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void DurationInfo_CreateWithCustomUnitInfos() + { + DurationUnit[] expectedUnits = [DurationUnit.Second]; + + Duration.DurationInfo quantityInfo = Duration.DurationInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Duration", quantityInfo.Name); + Assert.Equal(Duration.Zero, quantityInfo.Zero); + Assert.Equal(Duration.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void SecondToDurationUnits() { @@ -415,7 +429,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 с", DurationUnit.Second, 4.2)] [InlineData("ru-RU", "4,2 нед", DurationUnit.Week, 4.2)] [InlineData("ru-RU", "4,2 год", DurationUnit.Year365, 4.2)] - public void Parse(string culture, string quantityString, DurationUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, DurationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Duration.Parse(quantityString); @@ -492,7 +506,7 @@ public void Parse(string culture, string quantityString, DurationUnit expectedUn [InlineData("ru-RU", "4,2 с", DurationUnit.Second, 4.2)] [InlineData("ru-RU", "4,2 нед", DurationUnit.Week, 4.2)] [InlineData("ru-RU", "4,2 год", DurationUnit.Year365, 4.2)] - public void TryParse(string culture, string quantityString, DurationUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, DurationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Duration.TryParse(quantityString, out Duration parsed)); @@ -1112,6 +1126,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(DurationUnit uni var quantity = Duration.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -1135,44 +1150,46 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(DurationUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Duration second = Duration.FromSeconds(1); - AssertEx.EqualTolerance(1, Duration.FromDays(second.Days).Seconds, DaysTolerance); - AssertEx.EqualTolerance(1, Duration.FromHours(second.Hours).Seconds, HoursTolerance); - AssertEx.EqualTolerance(1, Duration.FromJulianYears(second.JulianYears).Seconds, JulianYearsTolerance); - AssertEx.EqualTolerance(1, Duration.FromMicroseconds(second.Microseconds).Seconds, MicrosecondsTolerance); - AssertEx.EqualTolerance(1, Duration.FromMilliseconds(second.Milliseconds).Seconds, MillisecondsTolerance); - AssertEx.EqualTolerance(1, Duration.FromMinutes(second.Minutes).Seconds, MinutesTolerance); - AssertEx.EqualTolerance(1, Duration.FromMonths30(second.Months30).Seconds, Months30Tolerance); - AssertEx.EqualTolerance(1, Duration.FromNanoseconds(second.Nanoseconds).Seconds, NanosecondsTolerance); - AssertEx.EqualTolerance(1, Duration.FromPicoseconds(second.Picoseconds).Seconds, PicosecondsTolerance); - AssertEx.EqualTolerance(1, Duration.FromSeconds(second.Seconds).Seconds, SecondsTolerance); - AssertEx.EqualTolerance(1, Duration.FromSols(second.Sols).Seconds, SolsTolerance); - AssertEx.EqualTolerance(1, Duration.FromWeeks(second.Weeks).Seconds, WeeksTolerance); - AssertEx.EqualTolerance(1, Duration.FromYears365(second.Years365).Seconds, Years365Tolerance); + Duration second = Duration.FromSeconds(3); + Assert.Equal(3, Duration.FromDays(second.Days).Seconds); + Assert.Equal(3, Duration.FromHours(second.Hours).Seconds); + Assert.Equal(3, Duration.FromJulianYears(second.JulianYears).Seconds); + Assert.Equal(3, Duration.FromMicroseconds(second.Microseconds).Seconds); + Assert.Equal(3, Duration.FromMilliseconds(second.Milliseconds).Seconds); + Assert.Equal(3, Duration.FromMinutes(second.Minutes).Seconds); + Assert.Equal(3, Duration.FromMonths30(second.Months30).Seconds); + Assert.Equal(3, Duration.FromNanoseconds(second.Nanoseconds).Seconds); + Assert.Equal(3, Duration.FromPicoseconds(second.Picoseconds).Seconds); + Assert.Equal(3, Duration.FromSeconds(second.Seconds).Seconds); + Assert.Equal(3, Duration.FromSols(second.Sols).Seconds); + Assert.Equal(3, Duration.FromWeeks(second.Weeks).Seconds); + Assert.Equal(3, Duration.FromYears365(second.Years365).Seconds); } [Fact] public void ArithmeticOperators() { Duration v = Duration.FromSeconds(1); - AssertEx.EqualTolerance(-1, -v.Seconds, SecondsTolerance); - AssertEx.EqualTolerance(2, (Duration.FromSeconds(3)-v).Seconds, SecondsTolerance); - AssertEx.EqualTolerance(2, (v + v).Seconds, SecondsTolerance); - AssertEx.EqualTolerance(10, (v*10).Seconds, SecondsTolerance); - AssertEx.EqualTolerance(10, (10*v).Seconds, SecondsTolerance); - AssertEx.EqualTolerance(2, (Duration.FromSeconds(10)/5).Seconds, SecondsTolerance); - AssertEx.EqualTolerance(2, Duration.FromSeconds(10)/Duration.FromSeconds(5), SecondsTolerance); + Assert.Equal(-1, -v.Seconds); + Assert.Equal(2, (Duration.FromSeconds(3) - v).Seconds); + Assert.Equal(2, (v + v).Seconds); + Assert.Equal(10, (v * 10).Seconds); + Assert.Equal(10, (10 * v).Seconds); + Assert.Equal(2, (Duration.FromSeconds(10) / 5).Seconds); + Assert.Equal(2, Duration.FromSeconds(10) / Duration.FromSeconds(5)); } [Fact] @@ -1218,8 +1235,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, DurationUnit.Second, 1, DurationUnit.Second, true)] // Same value and unit. [InlineData(1, DurationUnit.Second, 2, DurationUnit.Second, false)] // Different value. - [InlineData(2, DurationUnit.Second, 1, DurationUnit.Day, false)] // Different value and unit. - [InlineData(1, DurationUnit.Second, 1, DurationUnit.Day, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, DurationUnit unitA, double valueB, DurationUnit unitB, bool expectEqual) { var a = new Duration(valueA, unitA); @@ -1279,8 +1294,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Duration.FromSeconds(firstValue); var otherQuantity = Duration.FromSeconds(secondValue); Duration maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Duration.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1299,7 +1314,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1312,6 +1327,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Duration.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Duration.Info.Units, Duration.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Duration.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1398,7 +1425,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Duration.FromSeconds(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Duration), quantity.As(Duration.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs index a534786b25..58a20ea8f1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/DynamicViscosityTestsBase.g.cs @@ -161,6 +161,20 @@ public void DynamicViscosity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity( Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void DynamicViscosityInfo_CreateWithCustomUnitInfos() + { + DynamicViscosityUnit[] expectedUnits = [DynamicViscosityUnit.NewtonSecondPerMeterSquared]; + + DynamicViscosity.DynamicViscosityInfo quantityInfo = DynamicViscosity.DynamicViscosityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("DynamicViscosity", quantityInfo.Name); + Assert.Equal(DynamicViscosity.Zero, quantityInfo.Zero); + Assert.Equal(DynamicViscosity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void NewtonSecondPerMeterSquaredToDynamicViscosityUnits() { @@ -342,7 +356,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 lbf·s/in²", DynamicViscosityUnit.PoundForceSecondPerSquareInch, 4.2)] [InlineData("en-US", "4.2 lb/(ft·s)", DynamicViscosityUnit.PoundPerFootSecond, 4.2)] [InlineData("en-US", "4.2 reyn", DynamicViscosityUnit.Reyn, 4.2)] - public void Parse(string culture, string quantityString, DynamicViscosityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, DynamicViscosityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = DynamicViscosity.Parse(quantityString); @@ -364,7 +378,7 @@ public void Parse(string culture, string quantityString, DynamicViscosityUnit ex [InlineData("en-US", "4.2 lbf·s/in²", DynamicViscosityUnit.PoundForceSecondPerSquareInch, 4.2)] [InlineData("en-US", "4.2 lb/(ft·s)", DynamicViscosityUnit.PoundPerFootSecond, 4.2)] [InlineData("en-US", "4.2 reyn", DynamicViscosityUnit.Reyn, 4.2)] - public void TryParse(string culture, string quantityString, DynamicViscosityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, DynamicViscosityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(DynamicViscosity.TryParse(quantityString, out DynamicViscosity parsed)); @@ -602,6 +616,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(DynamicViscosity var quantity = DynamicViscosity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -625,41 +640,43 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(DynamicViscosityUni IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - DynamicViscosity newtonsecondpermetersquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - AssertEx.EqualTolerance(1, DynamicViscosity.FromCentipoise(newtonsecondpermetersquared.Centipoise).NewtonSecondsPerMeterSquared, CentipoiseTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.FromMicropascalSeconds(newtonsecondpermetersquared.MicropascalSeconds).NewtonSecondsPerMeterSquared, MicropascalSecondsTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.FromMillipascalSeconds(newtonsecondpermetersquared.MillipascalSeconds).NewtonSecondsPerMeterSquared, MillipascalSecondsTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.FromNewtonSecondsPerMeterSquared(newtonsecondpermetersquared.NewtonSecondsPerMeterSquared).NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.FromPascalSeconds(newtonsecondpermetersquared.PascalSeconds).NewtonSecondsPerMeterSquared, PascalSecondsTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.FromPoise(newtonsecondpermetersquared.Poise).NewtonSecondsPerMeterSquared, PoiseTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.FromPoundsForceSecondPerSquareFoot(newtonsecondpermetersquared.PoundsForceSecondPerSquareFoot).NewtonSecondsPerMeterSquared, PoundsForceSecondPerSquareFootTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.FromPoundsForceSecondPerSquareInch(newtonsecondpermetersquared.PoundsForceSecondPerSquareInch).NewtonSecondsPerMeterSquared, PoundsForceSecondPerSquareInchTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.FromPoundsPerFootSecond(newtonsecondpermetersquared.PoundsPerFootSecond).NewtonSecondsPerMeterSquared, PoundsPerFootSecondTolerance); - AssertEx.EqualTolerance(1, DynamicViscosity.FromReyns(newtonsecondpermetersquared.Reyns).NewtonSecondsPerMeterSquared, ReynsTolerance); + DynamicViscosity newtonsecondpermetersquared = DynamicViscosity.FromNewtonSecondsPerMeterSquared(3); + Assert.Equal(3, DynamicViscosity.FromCentipoise(newtonsecondpermetersquared.Centipoise).NewtonSecondsPerMeterSquared); + Assert.Equal(3, DynamicViscosity.FromMicropascalSeconds(newtonsecondpermetersquared.MicropascalSeconds).NewtonSecondsPerMeterSquared); + Assert.Equal(3, DynamicViscosity.FromMillipascalSeconds(newtonsecondpermetersquared.MillipascalSeconds).NewtonSecondsPerMeterSquared); + Assert.Equal(3, DynamicViscosity.FromNewtonSecondsPerMeterSquared(newtonsecondpermetersquared.NewtonSecondsPerMeterSquared).NewtonSecondsPerMeterSquared); + Assert.Equal(3, DynamicViscosity.FromPascalSeconds(newtonsecondpermetersquared.PascalSeconds).NewtonSecondsPerMeterSquared); + Assert.Equal(3, DynamicViscosity.FromPoise(newtonsecondpermetersquared.Poise).NewtonSecondsPerMeterSquared); + Assert.Equal(3, DynamicViscosity.FromPoundsForceSecondPerSquareFoot(newtonsecondpermetersquared.PoundsForceSecondPerSquareFoot).NewtonSecondsPerMeterSquared); + Assert.Equal(3, DynamicViscosity.FromPoundsForceSecondPerSquareInch(newtonsecondpermetersquared.PoundsForceSecondPerSquareInch).NewtonSecondsPerMeterSquared); + Assert.Equal(3, DynamicViscosity.FromPoundsPerFootSecond(newtonsecondpermetersquared.PoundsPerFootSecond).NewtonSecondsPerMeterSquared); + Assert.Equal(3, DynamicViscosity.FromReyns(newtonsecondpermetersquared.Reyns).NewtonSecondsPerMeterSquared); } [Fact] public void ArithmeticOperators() { DynamicViscosity v = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1); - AssertEx.EqualTolerance(-1, -v.NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - AssertEx.EqualTolerance(2, (DynamicViscosity.FromNewtonSecondsPerMeterSquared(3)-v).NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - AssertEx.EqualTolerance(2, (v + v).NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - AssertEx.EqualTolerance(10, (v*10).NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - AssertEx.EqualTolerance(10, (10*v).NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - AssertEx.EqualTolerance(2, (DynamicViscosity.FromNewtonSecondsPerMeterSquared(10)/5).NewtonSecondsPerMeterSquared, NewtonSecondsPerMeterSquaredTolerance); - AssertEx.EqualTolerance(2, DynamicViscosity.FromNewtonSecondsPerMeterSquared(10)/DynamicViscosity.FromNewtonSecondsPerMeterSquared(5), NewtonSecondsPerMeterSquaredTolerance); + Assert.Equal(-1, -v.NewtonSecondsPerMeterSquared); + Assert.Equal(2, (DynamicViscosity.FromNewtonSecondsPerMeterSquared(3) - v).NewtonSecondsPerMeterSquared); + Assert.Equal(2, (v + v).NewtonSecondsPerMeterSquared); + Assert.Equal(10, (v * 10).NewtonSecondsPerMeterSquared); + Assert.Equal(10, (10 * v).NewtonSecondsPerMeterSquared); + Assert.Equal(2, (DynamicViscosity.FromNewtonSecondsPerMeterSquared(10) / 5).NewtonSecondsPerMeterSquared); + Assert.Equal(2, DynamicViscosity.FromNewtonSecondsPerMeterSquared(10) / DynamicViscosity.FromNewtonSecondsPerMeterSquared(5)); } [Fact] @@ -705,8 +722,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, DynamicViscosityUnit.NewtonSecondPerMeterSquared, 1, DynamicViscosityUnit.NewtonSecondPerMeterSquared, true)] // Same value and unit. [InlineData(1, DynamicViscosityUnit.NewtonSecondPerMeterSquared, 2, DynamicViscosityUnit.NewtonSecondPerMeterSquared, false)] // Different value. - [InlineData(2, DynamicViscosityUnit.NewtonSecondPerMeterSquared, 1, DynamicViscosityUnit.Centipoise, false)] // Different value and unit. - [InlineData(1, DynamicViscosityUnit.NewtonSecondPerMeterSquared, 1, DynamicViscosityUnit.Centipoise, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, DynamicViscosityUnit unitA, double valueB, DynamicViscosityUnit unitB, bool expectEqual) { var a = new DynamicViscosity(valueA, unitA); @@ -766,8 +781,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(firstValue); var otherQuantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(secondValue); DynamicViscosity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, DynamicViscosity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -786,7 +801,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -799,6 +814,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(DynamicViscosity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(DynamicViscosity.Info.Units, DynamicViscosity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, DynamicViscosity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -879,7 +906,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = DynamicViscosity.FromNewtonSecondsPerMeterSquared(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(DynamicViscosity), quantity.As(DynamicViscosity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs index a112ce9452..4dc13b85ab 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricAdmittanceTestsBase.g.cs @@ -185,6 +185,20 @@ public void ElectricAdmittance_QuantityInfo_ReturnsQuantityInfoDescribingQuantit Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricAdmittanceInfo_CreateWithCustomUnitInfos() + { + ElectricAdmittanceUnit[] expectedUnits = [ElectricAdmittanceUnit.Siemens]; + + ElectricAdmittance.ElectricAdmittanceInfo quantityInfo = ElectricAdmittance.ElectricAdmittanceInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricAdmittance", quantityInfo.Name); + Assert.Equal(ElectricAdmittance.Zero, quantityInfo.Zero); + Assert.Equal(ElectricAdmittance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void SiemensToElectricAdmittanceUnits() { @@ -381,7 +395,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 S", ElectricAdmittanceUnit.Siemens, 4.2)] [InlineData("en-US", "4.2 T℧", ElectricAdmittanceUnit.Teramho, 4.2)] [InlineData("en-US", "4.2 TS", ElectricAdmittanceUnit.Terasiemens, 4.2)] - public void Parse(string culture, string quantityString, ElectricAdmittanceUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricAdmittanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricAdmittance.Parse(quantityString); @@ -406,7 +420,7 @@ public void Parse(string culture, string quantityString, ElectricAdmittanceUnit [InlineData("en-US", "4.2 S", ElectricAdmittanceUnit.Siemens, 4.2)] [InlineData("en-US", "4.2 T℧", ElectricAdmittanceUnit.Teramho, 4.2)] [InlineData("en-US", "4.2 TS", ElectricAdmittanceUnit.Terasiemens, 4.2)] - public void TryParse(string culture, string quantityString, ElectricAdmittanceUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricAdmittanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricAdmittance.TryParse(quantityString, out ElectricAdmittance parsed)); @@ -674,6 +688,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricAdmittan var quantity = ElectricAdmittance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -697,47 +712,49 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricAdmittanceU IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricAdmittance siemens = ElectricAdmittance.FromSiemens(1); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromGigamhos(siemens.Gigamhos).Siemens, GigamhosTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromGigasiemens(siemens.Gigasiemens).Siemens, GigasiemensTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromKilomhos(siemens.Kilomhos).Siemens, KilomhosTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromKilosiemens(siemens.Kilosiemens).Siemens, KilosiemensTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromMegamhos(siemens.Megamhos).Siemens, MegamhosTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromMegasiemens(siemens.Megasiemens).Siemens, MegasiemensTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromMhos(siemens.Mhos).Siemens, MhosTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromMicromhos(siemens.Micromhos).Siemens, MicromhosTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromMicrosiemens(siemens.Microsiemens).Siemens, MicrosiemensTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromMillimhos(siemens.Millimhos).Siemens, MillimhosTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromMillisiemens(siemens.Millisiemens).Siemens, MillisiemensTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromNanomhos(siemens.Nanomhos).Siemens, NanomhosTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromNanosiemens(siemens.Nanosiemens).Siemens, NanosiemensTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromSiemens(siemens.Siemens).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromTeramhos(siemens.Teramhos).Siemens, TeramhosTolerance); - AssertEx.EqualTolerance(1, ElectricAdmittance.FromTerasiemens(siemens.Terasiemens).Siemens, TerasiemensTolerance); + ElectricAdmittance siemens = ElectricAdmittance.FromSiemens(3); + Assert.Equal(3, ElectricAdmittance.FromGigamhos(siemens.Gigamhos).Siemens); + Assert.Equal(3, ElectricAdmittance.FromGigasiemens(siemens.Gigasiemens).Siemens); + Assert.Equal(3, ElectricAdmittance.FromKilomhos(siemens.Kilomhos).Siemens); + Assert.Equal(3, ElectricAdmittance.FromKilosiemens(siemens.Kilosiemens).Siemens); + Assert.Equal(3, ElectricAdmittance.FromMegamhos(siemens.Megamhos).Siemens); + Assert.Equal(3, ElectricAdmittance.FromMegasiemens(siemens.Megasiemens).Siemens); + Assert.Equal(3, ElectricAdmittance.FromMhos(siemens.Mhos).Siemens); + Assert.Equal(3, ElectricAdmittance.FromMicromhos(siemens.Micromhos).Siemens); + Assert.Equal(3, ElectricAdmittance.FromMicrosiemens(siemens.Microsiemens).Siemens); + Assert.Equal(3, ElectricAdmittance.FromMillimhos(siemens.Millimhos).Siemens); + Assert.Equal(3, ElectricAdmittance.FromMillisiemens(siemens.Millisiemens).Siemens); + Assert.Equal(3, ElectricAdmittance.FromNanomhos(siemens.Nanomhos).Siemens); + Assert.Equal(3, ElectricAdmittance.FromNanosiemens(siemens.Nanosiemens).Siemens); + Assert.Equal(3, ElectricAdmittance.FromSiemens(siemens.Siemens).Siemens); + Assert.Equal(3, ElectricAdmittance.FromTeramhos(siemens.Teramhos).Siemens); + Assert.Equal(3, ElectricAdmittance.FromTerasiemens(siemens.Terasiemens).Siemens); } [Fact] public void ArithmeticOperators() { ElectricAdmittance v = ElectricAdmittance.FromSiemens(1); - AssertEx.EqualTolerance(-1, -v.Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, (ElectricAdmittance.FromSiemens(3)-v).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, (v + v).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(10, (v*10).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(10, (10*v).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, (ElectricAdmittance.FromSiemens(10)/5).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, ElectricAdmittance.FromSiemens(10)/ElectricAdmittance.FromSiemens(5), SiemensTolerance); + Assert.Equal(-1, -v.Siemens); + Assert.Equal(2, (ElectricAdmittance.FromSiemens(3) - v).Siemens); + Assert.Equal(2, (v + v).Siemens); + Assert.Equal(10, (v * 10).Siemens); + Assert.Equal(10, (10 * v).Siemens); + Assert.Equal(2, (ElectricAdmittance.FromSiemens(10) / 5).Siemens); + Assert.Equal(2, ElectricAdmittance.FromSiemens(10) / ElectricAdmittance.FromSiemens(5)); } [Fact] @@ -783,8 +800,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricAdmittanceUnit.Siemens, 1, ElectricAdmittanceUnit.Siemens, true)] // Same value and unit. [InlineData(1, ElectricAdmittanceUnit.Siemens, 2, ElectricAdmittanceUnit.Siemens, false)] // Different value. - [InlineData(2, ElectricAdmittanceUnit.Siemens, 1, ElectricAdmittanceUnit.Gigamho, false)] // Different value and unit. - [InlineData(1, ElectricAdmittanceUnit.Siemens, 1, ElectricAdmittanceUnit.Gigamho, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricAdmittanceUnit unitA, double valueB, ElectricAdmittanceUnit unitB, bool expectEqual) { var a = new ElectricAdmittance(valueA, unitA); @@ -844,8 +859,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricAdmittance.FromSiemens(firstValue); var otherQuantity = ElectricAdmittance.FromSiemens(secondValue); ElectricAdmittance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricAdmittance.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -864,7 +879,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -877,6 +892,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricAdmittance.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricAdmittance.Info.Units, ElectricAdmittance.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricAdmittance.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -969,7 +996,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricAdmittance.FromSiemens(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricAdmittance), quantity.As(ElectricAdmittance.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricApparentEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricApparentEnergyTestsBase.g.cs index 43a1c68f0e..66b66fa5fe 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricApparentEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricApparentEnergyTestsBase.g.cs @@ -133,6 +133,20 @@ public void ElectricApparentEnergy_QuantityInfo_ReturnsQuantityInfoDescribingQua Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricApparentEnergyInfo_CreateWithCustomUnitInfos() + { + ElectricApparentEnergyUnit[] expectedUnits = [ElectricApparentEnergyUnit.VoltampereHour]; + + ElectricApparentEnergy.ElectricApparentEnergyInfo quantityInfo = ElectricApparentEnergy.ElectricApparentEnergyInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricApparentEnergy", quantityInfo.Name); + Assert.Equal(ElectricApparentEnergy.Zero, quantityInfo.Zero); + Assert.Equal(ElectricApparentEnergy.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void VoltampereHourToElectricApparentEnergyUnits() { @@ -290,7 +304,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 kVAh", ElectricApparentEnergyUnit.KilovoltampereHour, 4.2)] [InlineData("en-US", "4.2 MVAh", ElectricApparentEnergyUnit.MegavoltampereHour, 4.2)] [InlineData("en-US", "4.2 VAh", ElectricApparentEnergyUnit.VoltampereHour, 4.2)] - public void Parse(string culture, string quantityString, ElectricApparentEnergyUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricApparentEnergyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricApparentEnergy.Parse(quantityString); @@ -302,7 +316,7 @@ public void Parse(string culture, string quantityString, ElectricApparentEnergyU [InlineData("en-US", "4.2 kVAh", ElectricApparentEnergyUnit.KilovoltampereHour, 4.2)] [InlineData("en-US", "4.2 MVAh", ElectricApparentEnergyUnit.MegavoltampereHour, 4.2)] [InlineData("en-US", "4.2 VAh", ElectricApparentEnergyUnit.VoltampereHour, 4.2)] - public void TryParse(string culture, string quantityString, ElectricApparentEnergyUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricApparentEnergyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricApparentEnergy.TryParse(quantityString, out ElectricApparentEnergy parsed)); @@ -453,6 +467,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricApparent var quantity = ElectricApparentEnergy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -476,34 +491,36 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricApparentEne IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricApparentEnergy voltamperehour = ElectricApparentEnergy.FromVoltampereHours(1); - AssertEx.EqualTolerance(1, ElectricApparentEnergy.FromKilovoltampereHours(voltamperehour.KilovoltampereHours).VoltampereHours, KilovoltampereHoursTolerance); - AssertEx.EqualTolerance(1, ElectricApparentEnergy.FromMegavoltampereHours(voltamperehour.MegavoltampereHours).VoltampereHours, MegavoltampereHoursTolerance); - AssertEx.EqualTolerance(1, ElectricApparentEnergy.FromVoltampereHours(voltamperehour.VoltampereHours).VoltampereHours, VoltampereHoursTolerance); + ElectricApparentEnergy voltamperehour = ElectricApparentEnergy.FromVoltampereHours(3); + Assert.Equal(3, ElectricApparentEnergy.FromKilovoltampereHours(voltamperehour.KilovoltampereHours).VoltampereHours); + Assert.Equal(3, ElectricApparentEnergy.FromMegavoltampereHours(voltamperehour.MegavoltampereHours).VoltampereHours); + Assert.Equal(3, ElectricApparentEnergy.FromVoltampereHours(voltamperehour.VoltampereHours).VoltampereHours); } [Fact] public void ArithmeticOperators() { ElectricApparentEnergy v = ElectricApparentEnergy.FromVoltampereHours(1); - AssertEx.EqualTolerance(-1, -v.VoltampereHours, VoltampereHoursTolerance); - AssertEx.EqualTolerance(2, (ElectricApparentEnergy.FromVoltampereHours(3)-v).VoltampereHours, VoltampereHoursTolerance); - AssertEx.EqualTolerance(2, (v + v).VoltampereHours, VoltampereHoursTolerance); - AssertEx.EqualTolerance(10, (v*10).VoltampereHours, VoltampereHoursTolerance); - AssertEx.EqualTolerance(10, (10*v).VoltampereHours, VoltampereHoursTolerance); - AssertEx.EqualTolerance(2, (ElectricApparentEnergy.FromVoltampereHours(10)/5).VoltampereHours, VoltampereHoursTolerance); - AssertEx.EqualTolerance(2, ElectricApparentEnergy.FromVoltampereHours(10)/ElectricApparentEnergy.FromVoltampereHours(5), VoltampereHoursTolerance); + Assert.Equal(-1, -v.VoltampereHours); + Assert.Equal(2, (ElectricApparentEnergy.FromVoltampereHours(3) - v).VoltampereHours); + Assert.Equal(2, (v + v).VoltampereHours); + Assert.Equal(10, (v * 10).VoltampereHours); + Assert.Equal(10, (10 * v).VoltampereHours); + Assert.Equal(2, (ElectricApparentEnergy.FromVoltampereHours(10) / 5).VoltampereHours); + Assert.Equal(2, ElectricApparentEnergy.FromVoltampereHours(10) / ElectricApparentEnergy.FromVoltampereHours(5)); } [Fact] @@ -549,8 +566,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricApparentEnergyUnit.VoltampereHour, 1, ElectricApparentEnergyUnit.VoltampereHour, true)] // Same value and unit. [InlineData(1, ElectricApparentEnergyUnit.VoltampereHour, 2, ElectricApparentEnergyUnit.VoltampereHour, false)] // Different value. - [InlineData(2, ElectricApparentEnergyUnit.VoltampereHour, 1, ElectricApparentEnergyUnit.KilovoltampereHour, false)] // Different value and unit. - [InlineData(1, ElectricApparentEnergyUnit.VoltampereHour, 1, ElectricApparentEnergyUnit.KilovoltampereHour, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricApparentEnergyUnit unitA, double valueB, ElectricApparentEnergyUnit unitB, bool expectEqual) { var a = new ElectricApparentEnergy(valueA, unitA); @@ -610,8 +625,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricApparentEnergy.FromVoltampereHours(firstValue); var otherQuantity = ElectricApparentEnergy.FromVoltampereHours(secondValue); ElectricApparentEnergy maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricApparentEnergy.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -630,7 +645,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -643,6 +658,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricApparentEnergy.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricApparentEnergy.Info.Units, ElectricApparentEnergy.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricApparentEnergy.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -709,7 +736,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricApparentEnergy.FromVoltampereHours(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricApparentEnergy), quantity.As(ElectricApparentEnergy.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricApparentPowerTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricApparentPowerTestsBase.g.cs index 4c5e5960f7..9728a82608 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricApparentPowerTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricApparentPowerTestsBase.g.cs @@ -145,6 +145,20 @@ public void ElectricApparentPower_QuantityInfo_ReturnsQuantityInfoDescribingQuan Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricApparentPowerInfo_CreateWithCustomUnitInfos() + { + ElectricApparentPowerUnit[] expectedUnits = [ElectricApparentPowerUnit.Voltampere]; + + ElectricApparentPower.ElectricApparentPowerInfo quantityInfo = ElectricApparentPower.ElectricApparentPowerInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricApparentPower", quantityInfo.Name); + Assert.Equal(ElectricApparentPower.Zero, quantityInfo.Zero); + Assert.Equal(ElectricApparentPower.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void VoltampereToElectricApparentPowerUnits() { @@ -311,7 +325,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 µVA", ElectricApparentPowerUnit.Microvoltampere, 4.2)] [InlineData("en-US", "4.2 mVA", ElectricApparentPowerUnit.Millivoltampere, 4.2)] [InlineData("en-US", "4.2 VA", ElectricApparentPowerUnit.Voltampere, 4.2)] - public void Parse(string culture, string quantityString, ElectricApparentPowerUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricApparentPowerUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricApparentPower.Parse(quantityString); @@ -326,7 +340,7 @@ public void Parse(string culture, string quantityString, ElectricApparentPowerUn [InlineData("en-US", "4.2 µVA", ElectricApparentPowerUnit.Microvoltampere, 4.2)] [InlineData("en-US", "4.2 mVA", ElectricApparentPowerUnit.Millivoltampere, 4.2)] [InlineData("en-US", "4.2 VA", ElectricApparentPowerUnit.Voltampere, 4.2)] - public void TryParse(string culture, string quantityString, ElectricApparentPowerUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricApparentPowerUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricApparentPower.TryParse(quantityString, out ElectricApparentPower parsed)); @@ -504,6 +518,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricApparent var quantity = ElectricApparentPower.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -527,37 +542,39 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricApparentPow IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricApparentPower voltampere = ElectricApparentPower.FromVoltamperes(1); - AssertEx.EqualTolerance(1, ElectricApparentPower.FromGigavoltamperes(voltampere.Gigavoltamperes).Voltamperes, GigavoltamperesTolerance); - AssertEx.EqualTolerance(1, ElectricApparentPower.FromKilovoltamperes(voltampere.Kilovoltamperes).Voltamperes, KilovoltamperesTolerance); - AssertEx.EqualTolerance(1, ElectricApparentPower.FromMegavoltamperes(voltampere.Megavoltamperes).Voltamperes, MegavoltamperesTolerance); - AssertEx.EqualTolerance(1, ElectricApparentPower.FromMicrovoltamperes(voltampere.Microvoltamperes).Voltamperes, MicrovoltamperesTolerance); - AssertEx.EqualTolerance(1, ElectricApparentPower.FromMillivoltamperes(voltampere.Millivoltamperes).Voltamperes, MillivoltamperesTolerance); - AssertEx.EqualTolerance(1, ElectricApparentPower.FromVoltamperes(voltampere.Voltamperes).Voltamperes, VoltamperesTolerance); + ElectricApparentPower voltampere = ElectricApparentPower.FromVoltamperes(3); + Assert.Equal(3, ElectricApparentPower.FromGigavoltamperes(voltampere.Gigavoltamperes).Voltamperes); + Assert.Equal(3, ElectricApparentPower.FromKilovoltamperes(voltampere.Kilovoltamperes).Voltamperes); + Assert.Equal(3, ElectricApparentPower.FromMegavoltamperes(voltampere.Megavoltamperes).Voltamperes); + Assert.Equal(3, ElectricApparentPower.FromMicrovoltamperes(voltampere.Microvoltamperes).Voltamperes); + Assert.Equal(3, ElectricApparentPower.FromMillivoltamperes(voltampere.Millivoltamperes).Voltamperes); + Assert.Equal(3, ElectricApparentPower.FromVoltamperes(voltampere.Voltamperes).Voltamperes); } [Fact] public void ArithmeticOperators() { ElectricApparentPower v = ElectricApparentPower.FromVoltamperes(1); - AssertEx.EqualTolerance(-1, -v.Voltamperes, VoltamperesTolerance); - AssertEx.EqualTolerance(2, (ElectricApparentPower.FromVoltamperes(3)-v).Voltamperes, VoltamperesTolerance); - AssertEx.EqualTolerance(2, (v + v).Voltamperes, VoltamperesTolerance); - AssertEx.EqualTolerance(10, (v*10).Voltamperes, VoltamperesTolerance); - AssertEx.EqualTolerance(10, (10*v).Voltamperes, VoltamperesTolerance); - AssertEx.EqualTolerance(2, (ElectricApparentPower.FromVoltamperes(10)/5).Voltamperes, VoltamperesTolerance); - AssertEx.EqualTolerance(2, ElectricApparentPower.FromVoltamperes(10)/ElectricApparentPower.FromVoltamperes(5), VoltamperesTolerance); + Assert.Equal(-1, -v.Voltamperes); + Assert.Equal(2, (ElectricApparentPower.FromVoltamperes(3) - v).Voltamperes); + Assert.Equal(2, (v + v).Voltamperes); + Assert.Equal(10, (v * 10).Voltamperes); + Assert.Equal(10, (10 * v).Voltamperes); + Assert.Equal(2, (ElectricApparentPower.FromVoltamperes(10) / 5).Voltamperes); + Assert.Equal(2, ElectricApparentPower.FromVoltamperes(10) / ElectricApparentPower.FromVoltamperes(5)); } [Fact] @@ -603,8 +620,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricApparentPowerUnit.Voltampere, 1, ElectricApparentPowerUnit.Voltampere, true)] // Same value and unit. [InlineData(1, ElectricApparentPowerUnit.Voltampere, 2, ElectricApparentPowerUnit.Voltampere, false)] // Different value. - [InlineData(2, ElectricApparentPowerUnit.Voltampere, 1, ElectricApparentPowerUnit.Gigavoltampere, false)] // Different value and unit. - [InlineData(1, ElectricApparentPowerUnit.Voltampere, 1, ElectricApparentPowerUnit.Gigavoltampere, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricApparentPowerUnit unitA, double valueB, ElectricApparentPowerUnit unitB, bool expectEqual) { var a = new ElectricApparentPower(valueA, unitA); @@ -664,8 +679,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricApparentPower.FromVoltamperes(firstValue); var otherQuantity = ElectricApparentPower.FromVoltamperes(secondValue); ElectricApparentPower maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricApparentPower.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -684,7 +699,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -697,6 +712,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricApparentPower.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricApparentPower.Info.Units, ElectricApparentPower.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricApparentPower.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -769,7 +796,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricApparentPower.FromVoltamperes(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricApparentPower), quantity.As(ElectricApparentPower.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCapacitanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCapacitanceTestsBase.g.cs index c1991c1c5b..f68eb9745b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCapacitanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCapacitanceTestsBase.g.cs @@ -149,6 +149,20 @@ public void ElectricCapacitance_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricCapacitanceInfo_CreateWithCustomUnitInfos() + { + ElectricCapacitanceUnit[] expectedUnits = [ElectricCapacitanceUnit.Farad]; + + ElectricCapacitance.ElectricCapacitanceInfo quantityInfo = ElectricCapacitance.ElectricCapacitanceInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricCapacitance", quantityInfo.Name); + Assert.Equal(ElectricCapacitance.Zero, quantityInfo.Zero); + Assert.Equal(ElectricCapacitance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void FaradToElectricCapacitanceUnits() { @@ -318,7 +332,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 mF", ElectricCapacitanceUnit.Millifarad, 4.2)] [InlineData("en-US", "4.2 nF", ElectricCapacitanceUnit.Nanofarad, 4.2)] [InlineData("en-US", "4.2 pF", ElectricCapacitanceUnit.Picofarad, 4.2)] - public void Parse(string culture, string quantityString, ElectricCapacitanceUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricCapacitanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricCapacitance.Parse(quantityString); @@ -334,7 +348,7 @@ public void Parse(string culture, string quantityString, ElectricCapacitanceUnit [InlineData("en-US", "4.2 mF", ElectricCapacitanceUnit.Millifarad, 4.2)] [InlineData("en-US", "4.2 nF", ElectricCapacitanceUnit.Nanofarad, 4.2)] [InlineData("en-US", "4.2 pF", ElectricCapacitanceUnit.Picofarad, 4.2)] - public void TryParse(string culture, string quantityString, ElectricCapacitanceUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricCapacitanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricCapacitance.TryParse(quantityString, out ElectricCapacitance parsed)); @@ -521,6 +535,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricCapacita var quantity = ElectricCapacitance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -544,38 +559,40 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricCapacitance IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricCapacitance farad = ElectricCapacitance.FromFarads(1); - AssertEx.EqualTolerance(1, ElectricCapacitance.FromFarads(farad.Farads).Farads, FaradsTolerance); - AssertEx.EqualTolerance(1, ElectricCapacitance.FromKilofarads(farad.Kilofarads).Farads, KilofaradsTolerance); - AssertEx.EqualTolerance(1, ElectricCapacitance.FromMegafarads(farad.Megafarads).Farads, MegafaradsTolerance); - AssertEx.EqualTolerance(1, ElectricCapacitance.FromMicrofarads(farad.Microfarads).Farads, MicrofaradsTolerance); - AssertEx.EqualTolerance(1, ElectricCapacitance.FromMillifarads(farad.Millifarads).Farads, MillifaradsTolerance); - AssertEx.EqualTolerance(1, ElectricCapacitance.FromNanofarads(farad.Nanofarads).Farads, NanofaradsTolerance); - AssertEx.EqualTolerance(1, ElectricCapacitance.FromPicofarads(farad.Picofarads).Farads, PicofaradsTolerance); + ElectricCapacitance farad = ElectricCapacitance.FromFarads(3); + Assert.Equal(3, ElectricCapacitance.FromFarads(farad.Farads).Farads); + Assert.Equal(3, ElectricCapacitance.FromKilofarads(farad.Kilofarads).Farads); + Assert.Equal(3, ElectricCapacitance.FromMegafarads(farad.Megafarads).Farads); + Assert.Equal(3, ElectricCapacitance.FromMicrofarads(farad.Microfarads).Farads); + Assert.Equal(3, ElectricCapacitance.FromMillifarads(farad.Millifarads).Farads); + Assert.Equal(3, ElectricCapacitance.FromNanofarads(farad.Nanofarads).Farads); + Assert.Equal(3, ElectricCapacitance.FromPicofarads(farad.Picofarads).Farads); } [Fact] public void ArithmeticOperators() { ElectricCapacitance v = ElectricCapacitance.FromFarads(1); - AssertEx.EqualTolerance(-1, -v.Farads, FaradsTolerance); - AssertEx.EqualTolerance(2, (ElectricCapacitance.FromFarads(3)-v).Farads, FaradsTolerance); - AssertEx.EqualTolerance(2, (v + v).Farads, FaradsTolerance); - AssertEx.EqualTolerance(10, (v*10).Farads, FaradsTolerance); - AssertEx.EqualTolerance(10, (10*v).Farads, FaradsTolerance); - AssertEx.EqualTolerance(2, (ElectricCapacitance.FromFarads(10)/5).Farads, FaradsTolerance); - AssertEx.EqualTolerance(2, ElectricCapacitance.FromFarads(10)/ElectricCapacitance.FromFarads(5), FaradsTolerance); + Assert.Equal(-1, -v.Farads); + Assert.Equal(2, (ElectricCapacitance.FromFarads(3) - v).Farads); + Assert.Equal(2, (v + v).Farads); + Assert.Equal(10, (v * 10).Farads); + Assert.Equal(10, (10 * v).Farads); + Assert.Equal(2, (ElectricCapacitance.FromFarads(10) / 5).Farads); + Assert.Equal(2, ElectricCapacitance.FromFarads(10) / ElectricCapacitance.FromFarads(5)); } [Fact] @@ -621,8 +638,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricCapacitanceUnit.Farad, 1, ElectricCapacitanceUnit.Farad, true)] // Same value and unit. [InlineData(1, ElectricCapacitanceUnit.Farad, 2, ElectricCapacitanceUnit.Farad, false)] // Different value. - [InlineData(2, ElectricCapacitanceUnit.Farad, 1, ElectricCapacitanceUnit.Kilofarad, false)] // Different value and unit. - [InlineData(1, ElectricCapacitanceUnit.Farad, 1, ElectricCapacitanceUnit.Kilofarad, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricCapacitanceUnit unitA, double valueB, ElectricCapacitanceUnit unitB, bool expectEqual) { var a = new ElectricCapacitance(valueA, unitA); @@ -682,8 +697,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricCapacitance.FromFarads(firstValue); var otherQuantity = ElectricCapacitance.FromFarads(secondValue); ElectricCapacitance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricCapacitance.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -702,7 +717,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -715,6 +730,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricCapacitance.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricCapacitance.Info.Units, ElectricCapacitance.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricCapacitance.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -789,7 +816,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricCapacitance.FromFarads(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricCapacitance), quantity.As(ElectricCapacitance.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs index 4b9edbc063..a15f0dab2a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeDensityTestsBase.g.cs @@ -125,6 +125,20 @@ public void ElectricChargeDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuan Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricChargeDensityInfo_CreateWithCustomUnitInfos() + { + ElectricChargeDensityUnit[] expectedUnits = [ElectricChargeDensityUnit.CoulombPerCubicMeter]; + + ElectricChargeDensity.ElectricChargeDensityInfo quantityInfo = ElectricChargeDensity.ElectricChargeDensityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricChargeDensity", quantityInfo.Name); + Assert.Equal(ElectricChargeDensity.Zero, quantityInfo.Zero); + Assert.Equal(ElectricChargeDensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void CoulombPerCubicMeterToElectricChargeDensityUnits() { @@ -276,7 +290,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Theory] [InlineData("en-US", "4.2 C/m³", ElectricChargeDensityUnit.CoulombPerCubicMeter, 4.2)] - public void Parse(string culture, string quantityString, ElectricChargeDensityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricChargeDensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricChargeDensity.Parse(quantityString); @@ -286,7 +300,7 @@ public void Parse(string culture, string quantityString, ElectricChargeDensityUn [Theory] [InlineData("en-US", "4.2 C/m³", ElectricChargeDensityUnit.CoulombPerCubicMeter, 4.2)] - public void TryParse(string culture, string quantityString, ElectricChargeDensityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricChargeDensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricChargeDensity.TryParse(quantityString, out ElectricChargeDensity parsed)); @@ -419,6 +433,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricChargeDe var quantity = ElectricChargeDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -442,32 +457,34 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricChargeDensi IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricChargeDensity coulombpercubicmeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - AssertEx.EqualTolerance(1, ElectricChargeDensity.FromCoulombsPerCubicMeter(coulombpercubicmeter.CoulombsPerCubicMeter).CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); + ElectricChargeDensity coulombpercubicmeter = ElectricChargeDensity.FromCoulombsPerCubicMeter(3); + Assert.Equal(3, ElectricChargeDensity.FromCoulombsPerCubicMeter(coulombpercubicmeter.CoulombsPerCubicMeter).CoulombsPerCubicMeter); } [Fact] public void ArithmeticOperators() { ElectricChargeDensity v = ElectricChargeDensity.FromCoulombsPerCubicMeter(1); - AssertEx.EqualTolerance(-1, -v.CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricChargeDensity.FromCoulombsPerCubicMeter(3)-v).CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricChargeDensity.FromCoulombsPerCubicMeter(10)/5).CoulombsPerCubicMeter, CoulombsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, ElectricChargeDensity.FromCoulombsPerCubicMeter(10)/ElectricChargeDensity.FromCoulombsPerCubicMeter(5), CoulombsPerCubicMeterTolerance); + Assert.Equal(-1, -v.CoulombsPerCubicMeter); + Assert.Equal(2, (ElectricChargeDensity.FromCoulombsPerCubicMeter(3) - v).CoulombsPerCubicMeter); + Assert.Equal(2, (v + v).CoulombsPerCubicMeter); + Assert.Equal(10, (v * 10).CoulombsPerCubicMeter); + Assert.Equal(10, (10 * v).CoulombsPerCubicMeter); + Assert.Equal(2, (ElectricChargeDensity.FromCoulombsPerCubicMeter(10) / 5).CoulombsPerCubicMeter); + Assert.Equal(2, ElectricChargeDensity.FromCoulombsPerCubicMeter(10) / ElectricChargeDensity.FromCoulombsPerCubicMeter(5)); } [Fact] @@ -513,7 +530,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricChargeDensityUnit.CoulombPerCubicMeter, 1, ElectricChargeDensityUnit.CoulombPerCubicMeter, true)] // Same value and unit. [InlineData(1, ElectricChargeDensityUnit.CoulombPerCubicMeter, 2, ElectricChargeDensityUnit.CoulombPerCubicMeter, false)] // Different value. - [InlineData(2, ElectricChargeDensityUnit.CoulombPerCubicMeter, 1, ElectricChargeDensityUnit.CoulombPerCubicMeter, false)] // Different value and unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricChargeDensityUnit unitA, double valueB, ElectricChargeDensityUnit unitB, bool expectEqual) { var a = new ElectricChargeDensity(valueA, unitA); @@ -573,8 +589,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(firstValue); var otherQuantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(secondValue); ElectricChargeDensity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricChargeDensity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -593,7 +609,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -606,6 +622,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricChargeDensity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricChargeDensity.Info.Units, ElectricChargeDensity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricChargeDensity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -668,7 +696,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricChargeDensity.FromCoulombsPerCubicMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricChargeDensity), quantity.As(ElectricChargeDensity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs index a3a09feb14..504d48f73d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricChargeTestsBase.g.cs @@ -165,6 +165,20 @@ public void ElectricCharge_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricChargeInfo_CreateWithCustomUnitInfos() + { + ElectricChargeUnit[] expectedUnits = [ElectricChargeUnit.Coulomb]; + + ElectricCharge.ElectricChargeInfo quantityInfo = ElectricCharge.ElectricChargeInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricCharge", quantityInfo.Name); + Assert.Equal(ElectricCharge.Zero, quantityInfo.Zero); + Assert.Equal(ElectricCharge.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void CoulombToElectricChargeUnits() { @@ -350,7 +364,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 mC", ElectricChargeUnit.Millicoulomb, 4.2)] [InlineData("en-US", "4.2 nC", ElectricChargeUnit.Nanocoulomb, 4.2)] [InlineData("en-US", "4.2 pC", ElectricChargeUnit.Picocoulomb, 4.2)] - public void Parse(string culture, string quantityString, ElectricChargeUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricChargeUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricCharge.Parse(quantityString); @@ -374,7 +388,7 @@ public void Parse(string culture, string quantityString, ElectricChargeUnit expe [InlineData("en-US", "4.2 mC", ElectricChargeUnit.Millicoulomb, 4.2)] [InlineData("en-US", "4.2 nC", ElectricChargeUnit.Nanocoulomb, 4.2)] [InlineData("en-US", "4.2 pC", ElectricChargeUnit.Picocoulomb, 4.2)] - public void TryParse(string culture, string quantityString, ElectricChargeUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricChargeUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricCharge.TryParse(quantityString, out ElectricCharge parsed)); @@ -629,6 +643,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricChargeUn var quantity = ElectricCharge.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -652,42 +667,44 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricChargeUnit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricCharge coulomb = ElectricCharge.FromCoulombs(1); - AssertEx.EqualTolerance(1, ElectricCharge.FromAmpereHours(coulomb.AmpereHours).Coulombs, AmpereHoursTolerance); - AssertEx.EqualTolerance(1, ElectricCharge.FromCoulombs(coulomb.Coulombs).Coulombs, CoulombsTolerance); - AssertEx.EqualTolerance(1, ElectricCharge.FromKiloampereHours(coulomb.KiloampereHours).Coulombs, KiloampereHoursTolerance); - AssertEx.EqualTolerance(1, ElectricCharge.FromKilocoulombs(coulomb.Kilocoulombs).Coulombs, KilocoulombsTolerance); - AssertEx.EqualTolerance(1, ElectricCharge.FromMegaampereHours(coulomb.MegaampereHours).Coulombs, MegaampereHoursTolerance); - AssertEx.EqualTolerance(1, ElectricCharge.FromMegacoulombs(coulomb.Megacoulombs).Coulombs, MegacoulombsTolerance); - AssertEx.EqualTolerance(1, ElectricCharge.FromMicrocoulombs(coulomb.Microcoulombs).Coulombs, MicrocoulombsTolerance); - AssertEx.EqualTolerance(1, ElectricCharge.FromMilliampereHours(coulomb.MilliampereHours).Coulombs, MilliampereHoursTolerance); - AssertEx.EqualTolerance(1, ElectricCharge.FromMillicoulombs(coulomb.Millicoulombs).Coulombs, MillicoulombsTolerance); - AssertEx.EqualTolerance(1, ElectricCharge.FromNanocoulombs(coulomb.Nanocoulombs).Coulombs, NanocoulombsTolerance); - AssertEx.EqualTolerance(1, ElectricCharge.FromPicocoulombs(coulomb.Picocoulombs).Coulombs, PicocoulombsTolerance); + ElectricCharge coulomb = ElectricCharge.FromCoulombs(3); + Assert.Equal(3, ElectricCharge.FromAmpereHours(coulomb.AmpereHours).Coulombs); + Assert.Equal(3, ElectricCharge.FromCoulombs(coulomb.Coulombs).Coulombs); + Assert.Equal(3, ElectricCharge.FromKiloampereHours(coulomb.KiloampereHours).Coulombs); + Assert.Equal(3, ElectricCharge.FromKilocoulombs(coulomb.Kilocoulombs).Coulombs); + Assert.Equal(3, ElectricCharge.FromMegaampereHours(coulomb.MegaampereHours).Coulombs); + Assert.Equal(3, ElectricCharge.FromMegacoulombs(coulomb.Megacoulombs).Coulombs); + Assert.Equal(3, ElectricCharge.FromMicrocoulombs(coulomb.Microcoulombs).Coulombs); + Assert.Equal(3, ElectricCharge.FromMilliampereHours(coulomb.MilliampereHours).Coulombs); + Assert.Equal(3, ElectricCharge.FromMillicoulombs(coulomb.Millicoulombs).Coulombs); + Assert.Equal(3, ElectricCharge.FromNanocoulombs(coulomb.Nanocoulombs).Coulombs); + Assert.Equal(3, ElectricCharge.FromPicocoulombs(coulomb.Picocoulombs).Coulombs); } [Fact] public void ArithmeticOperators() { ElectricCharge v = ElectricCharge.FromCoulombs(1); - AssertEx.EqualTolerance(-1, -v.Coulombs, CoulombsTolerance); - AssertEx.EqualTolerance(2, (ElectricCharge.FromCoulombs(3)-v).Coulombs, CoulombsTolerance); - AssertEx.EqualTolerance(2, (v + v).Coulombs, CoulombsTolerance); - AssertEx.EqualTolerance(10, (v*10).Coulombs, CoulombsTolerance); - AssertEx.EqualTolerance(10, (10*v).Coulombs, CoulombsTolerance); - AssertEx.EqualTolerance(2, (ElectricCharge.FromCoulombs(10)/5).Coulombs, CoulombsTolerance); - AssertEx.EqualTolerance(2, ElectricCharge.FromCoulombs(10)/ElectricCharge.FromCoulombs(5), CoulombsTolerance); + Assert.Equal(-1, -v.Coulombs); + Assert.Equal(2, (ElectricCharge.FromCoulombs(3) - v).Coulombs); + Assert.Equal(2, (v + v).Coulombs); + Assert.Equal(10, (v * 10).Coulombs); + Assert.Equal(10, (10 * v).Coulombs); + Assert.Equal(2, (ElectricCharge.FromCoulombs(10) / 5).Coulombs); + Assert.Equal(2, ElectricCharge.FromCoulombs(10) / ElectricCharge.FromCoulombs(5)); } [Fact] @@ -733,8 +750,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricChargeUnit.Coulomb, 1, ElectricChargeUnit.Coulomb, true)] // Same value and unit. [InlineData(1, ElectricChargeUnit.Coulomb, 2, ElectricChargeUnit.Coulomb, false)] // Different value. - [InlineData(2, ElectricChargeUnit.Coulomb, 1, ElectricChargeUnit.AmpereHour, false)] // Different value and unit. - [InlineData(1, ElectricChargeUnit.Coulomb, 1, ElectricChargeUnit.AmpereHour, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricChargeUnit unitA, double valueB, ElectricChargeUnit unitB, bool expectEqual) { var a = new ElectricCharge(valueA, unitA); @@ -794,8 +809,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricCharge.FromCoulombs(firstValue); var otherQuantity = ElectricCharge.FromCoulombs(secondValue); ElectricCharge maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricCharge.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -814,7 +829,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -827,6 +842,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricCharge.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricCharge.Info.Units, ElectricCharge.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricCharge.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -909,7 +936,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricCharge.FromCoulombs(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricCharge), quantity.As(ElectricCharge.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs index c25f98abf5..542ecb720c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductanceTestsBase.g.cs @@ -185,6 +185,20 @@ public void ElectricConductance_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricConductanceInfo_CreateWithCustomUnitInfos() + { + ElectricConductanceUnit[] expectedUnits = [ElectricConductanceUnit.Siemens]; + + ElectricConductance.ElectricConductanceInfo quantityInfo = ElectricConductance.ElectricConductanceInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricConductance", quantityInfo.Name); + Assert.Equal(ElectricConductance.Zero, quantityInfo.Zero); + Assert.Equal(ElectricConductance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void SiemensToElectricConductanceUnits() { @@ -381,7 +395,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 S", ElectricConductanceUnit.Siemens, 4.2)] [InlineData("en-US", "4.2 T℧", ElectricConductanceUnit.Teramho, 4.2)] [InlineData("en-US", "4.2 TS", ElectricConductanceUnit.Terasiemens, 4.2)] - public void Parse(string culture, string quantityString, ElectricConductanceUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricConductanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricConductance.Parse(quantityString); @@ -406,7 +420,7 @@ public void Parse(string culture, string quantityString, ElectricConductanceUnit [InlineData("en-US", "4.2 S", ElectricConductanceUnit.Siemens, 4.2)] [InlineData("en-US", "4.2 T℧", ElectricConductanceUnit.Teramho, 4.2)] [InlineData("en-US", "4.2 TS", ElectricConductanceUnit.Terasiemens, 4.2)] - public void TryParse(string culture, string quantityString, ElectricConductanceUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricConductanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricConductance.TryParse(quantityString, out ElectricConductance parsed)); @@ -674,6 +688,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricConducta var quantity = ElectricConductance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -697,47 +712,49 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricConductance IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricConductance siemens = ElectricConductance.FromSiemens(1); - AssertEx.EqualTolerance(1, ElectricConductance.FromGigamhos(siemens.Gigamhos).Siemens, GigamhosTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.FromGigasiemens(siemens.Gigasiemens).Siemens, GigasiemensTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.FromKilomhos(siemens.Kilomhos).Siemens, KilomhosTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.FromKilosiemens(siemens.Kilosiemens).Siemens, KilosiemensTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.FromMegamhos(siemens.Megamhos).Siemens, MegamhosTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.FromMegasiemens(siemens.Megasiemens).Siemens, MegasiemensTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.FromMhos(siemens.Mhos).Siemens, MhosTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.FromMicromhos(siemens.Micromhos).Siemens, MicromhosTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.FromMicrosiemens(siemens.Microsiemens).Siemens, MicrosiemensTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.FromMillimhos(siemens.Millimhos).Siemens, MillimhosTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.FromMillisiemens(siemens.Millisiemens).Siemens, MillisiemensTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.FromNanomhos(siemens.Nanomhos).Siemens, NanomhosTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.FromNanosiemens(siemens.Nanosiemens).Siemens, NanosiemensTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.FromSiemens(siemens.Siemens).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.FromTeramhos(siemens.Teramhos).Siemens, TeramhosTolerance); - AssertEx.EqualTolerance(1, ElectricConductance.FromTerasiemens(siemens.Terasiemens).Siemens, TerasiemensTolerance); + ElectricConductance siemens = ElectricConductance.FromSiemens(3); + Assert.Equal(3, ElectricConductance.FromGigamhos(siemens.Gigamhos).Siemens); + Assert.Equal(3, ElectricConductance.FromGigasiemens(siemens.Gigasiemens).Siemens); + Assert.Equal(3, ElectricConductance.FromKilomhos(siemens.Kilomhos).Siemens); + Assert.Equal(3, ElectricConductance.FromKilosiemens(siemens.Kilosiemens).Siemens); + Assert.Equal(3, ElectricConductance.FromMegamhos(siemens.Megamhos).Siemens); + Assert.Equal(3, ElectricConductance.FromMegasiemens(siemens.Megasiemens).Siemens); + Assert.Equal(3, ElectricConductance.FromMhos(siemens.Mhos).Siemens); + Assert.Equal(3, ElectricConductance.FromMicromhos(siemens.Micromhos).Siemens); + Assert.Equal(3, ElectricConductance.FromMicrosiemens(siemens.Microsiemens).Siemens); + Assert.Equal(3, ElectricConductance.FromMillimhos(siemens.Millimhos).Siemens); + Assert.Equal(3, ElectricConductance.FromMillisiemens(siemens.Millisiemens).Siemens); + Assert.Equal(3, ElectricConductance.FromNanomhos(siemens.Nanomhos).Siemens); + Assert.Equal(3, ElectricConductance.FromNanosiemens(siemens.Nanosiemens).Siemens); + Assert.Equal(3, ElectricConductance.FromSiemens(siemens.Siemens).Siemens); + Assert.Equal(3, ElectricConductance.FromTeramhos(siemens.Teramhos).Siemens); + Assert.Equal(3, ElectricConductance.FromTerasiemens(siemens.Terasiemens).Siemens); } [Fact] public void ArithmeticOperators() { ElectricConductance v = ElectricConductance.FromSiemens(1); - AssertEx.EqualTolerance(-1, -v.Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, (ElectricConductance.FromSiemens(3)-v).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, (v + v).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(10, (v*10).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(10, (10*v).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, (ElectricConductance.FromSiemens(10)/5).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, ElectricConductance.FromSiemens(10)/ElectricConductance.FromSiemens(5), SiemensTolerance); + Assert.Equal(-1, -v.Siemens); + Assert.Equal(2, (ElectricConductance.FromSiemens(3) - v).Siemens); + Assert.Equal(2, (v + v).Siemens); + Assert.Equal(10, (v * 10).Siemens); + Assert.Equal(10, (10 * v).Siemens); + Assert.Equal(2, (ElectricConductance.FromSiemens(10) / 5).Siemens); + Assert.Equal(2, ElectricConductance.FromSiemens(10) / ElectricConductance.FromSiemens(5)); } [Fact] @@ -783,8 +800,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricConductanceUnit.Siemens, 1, ElectricConductanceUnit.Siemens, true)] // Same value and unit. [InlineData(1, ElectricConductanceUnit.Siemens, 2, ElectricConductanceUnit.Siemens, false)] // Different value. - [InlineData(2, ElectricConductanceUnit.Siemens, 1, ElectricConductanceUnit.Gigamho, false)] // Different value and unit. - [InlineData(1, ElectricConductanceUnit.Siemens, 1, ElectricConductanceUnit.Gigamho, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricConductanceUnit unitA, double valueB, ElectricConductanceUnit unitB, bool expectEqual) { var a = new ElectricConductance(valueA, unitA); @@ -844,8 +859,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricConductance.FromSiemens(firstValue); var otherQuantity = ElectricConductance.FromSiemens(secondValue); ElectricConductance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricConductance.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -864,7 +879,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -877,6 +892,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricConductance.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricConductance.Info.Units, ElectricConductance.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricConductance.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -969,7 +996,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricConductance.FromSiemens(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricConductance), quantity.As(ElectricConductance.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs index de41dc4d00..5c203e6c4b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricConductivityTestsBase.g.cs @@ -145,6 +145,20 @@ public void ElectricConductivity_QuantityInfo_ReturnsQuantityInfoDescribingQuant Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricConductivityInfo_CreateWithCustomUnitInfos() + { + ElectricConductivityUnit[] expectedUnits = [ElectricConductivityUnit.SiemensPerMeter]; + + ElectricConductivity.ElectricConductivityInfo quantityInfo = ElectricConductivity.ElectricConductivityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricConductivity", quantityInfo.Name); + Assert.Equal(ElectricConductivity.Zero, quantityInfo.Zero); + Assert.Equal(ElectricConductivity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void SiemensPerMeterToElectricConductivityUnits() { @@ -311,7 +325,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 S/ft", ElectricConductivityUnit.SiemensPerFoot, 4.2)] [InlineData("en-US", "4.2 S/in", ElectricConductivityUnit.SiemensPerInch, 4.2)] [InlineData("en-US", "4.2 S/m", ElectricConductivityUnit.SiemensPerMeter, 4.2)] - public void Parse(string culture, string quantityString, ElectricConductivityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricConductivityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricConductivity.Parse(quantityString); @@ -326,7 +340,7 @@ public void Parse(string culture, string quantityString, ElectricConductivityUni [InlineData("en-US", "4.2 S/ft", ElectricConductivityUnit.SiemensPerFoot, 4.2)] [InlineData("en-US", "4.2 S/in", ElectricConductivityUnit.SiemensPerInch, 4.2)] [InlineData("en-US", "4.2 S/m", ElectricConductivityUnit.SiemensPerMeter, 4.2)] - public void TryParse(string culture, string quantityString, ElectricConductivityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricConductivityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricConductivity.TryParse(quantityString, out ElectricConductivity parsed)); @@ -504,6 +518,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricConducti var quantity = ElectricConductivity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -527,37 +542,39 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricConductivit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricConductivity siemenspermeter = ElectricConductivity.FromSiemensPerMeter(1); - AssertEx.EqualTolerance(1, ElectricConductivity.FromMicrosiemensPerCentimeter(siemenspermeter.MicrosiemensPerCentimeter).SiemensPerMeter, MicrosiemensPerCentimeterTolerance); - AssertEx.EqualTolerance(1, ElectricConductivity.FromMillisiemensPerCentimeter(siemenspermeter.MillisiemensPerCentimeter).SiemensPerMeter, MillisiemensPerCentimeterTolerance); - AssertEx.EqualTolerance(1, ElectricConductivity.FromSiemensPerCentimeter(siemenspermeter.SiemensPerCentimeter).SiemensPerMeter, SiemensPerCentimeterTolerance); - AssertEx.EqualTolerance(1, ElectricConductivity.FromSiemensPerFoot(siemenspermeter.SiemensPerFoot).SiemensPerMeter, SiemensPerFootTolerance); - AssertEx.EqualTolerance(1, ElectricConductivity.FromSiemensPerInch(siemenspermeter.SiemensPerInch).SiemensPerMeter, SiemensPerInchTolerance); - AssertEx.EqualTolerance(1, ElectricConductivity.FromSiemensPerMeter(siemenspermeter.SiemensPerMeter).SiemensPerMeter, SiemensPerMeterTolerance); + ElectricConductivity siemenspermeter = ElectricConductivity.FromSiemensPerMeter(3); + Assert.Equal(3, ElectricConductivity.FromMicrosiemensPerCentimeter(siemenspermeter.MicrosiemensPerCentimeter).SiemensPerMeter); + Assert.Equal(3, ElectricConductivity.FromMillisiemensPerCentimeter(siemenspermeter.MillisiemensPerCentimeter).SiemensPerMeter); + Assert.Equal(3, ElectricConductivity.FromSiemensPerCentimeter(siemenspermeter.SiemensPerCentimeter).SiemensPerMeter); + Assert.Equal(3, ElectricConductivity.FromSiemensPerFoot(siemenspermeter.SiemensPerFoot).SiemensPerMeter); + Assert.Equal(3, ElectricConductivity.FromSiemensPerInch(siemenspermeter.SiemensPerInch).SiemensPerMeter); + Assert.Equal(3, ElectricConductivity.FromSiemensPerMeter(siemenspermeter.SiemensPerMeter).SiemensPerMeter); } [Fact] public void ArithmeticOperators() { ElectricConductivity v = ElectricConductivity.FromSiemensPerMeter(1); - AssertEx.EqualTolerance(-1, -v.SiemensPerMeter, SiemensPerMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricConductivity.FromSiemensPerMeter(3)-v).SiemensPerMeter, SiemensPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).SiemensPerMeter, SiemensPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).SiemensPerMeter, SiemensPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).SiemensPerMeter, SiemensPerMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricConductivity.FromSiemensPerMeter(10)/5).SiemensPerMeter, SiemensPerMeterTolerance); - AssertEx.EqualTolerance(2, ElectricConductivity.FromSiemensPerMeter(10)/ElectricConductivity.FromSiemensPerMeter(5), SiemensPerMeterTolerance); + Assert.Equal(-1, -v.SiemensPerMeter); + Assert.Equal(2, (ElectricConductivity.FromSiemensPerMeter(3) - v).SiemensPerMeter); + Assert.Equal(2, (v + v).SiemensPerMeter); + Assert.Equal(10, (v * 10).SiemensPerMeter); + Assert.Equal(10, (10 * v).SiemensPerMeter); + Assert.Equal(2, (ElectricConductivity.FromSiemensPerMeter(10) / 5).SiemensPerMeter); + Assert.Equal(2, ElectricConductivity.FromSiemensPerMeter(10) / ElectricConductivity.FromSiemensPerMeter(5)); } [Fact] @@ -603,8 +620,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricConductivityUnit.SiemensPerMeter, 1, ElectricConductivityUnit.SiemensPerMeter, true)] // Same value and unit. [InlineData(1, ElectricConductivityUnit.SiemensPerMeter, 2, ElectricConductivityUnit.SiemensPerMeter, false)] // Different value. - [InlineData(2, ElectricConductivityUnit.SiemensPerMeter, 1, ElectricConductivityUnit.MicrosiemensPerCentimeter, false)] // Different value and unit. - [InlineData(1, ElectricConductivityUnit.SiemensPerMeter, 1, ElectricConductivityUnit.MicrosiemensPerCentimeter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricConductivityUnit unitA, double valueB, ElectricConductivityUnit unitB, bool expectEqual) { var a = new ElectricConductivity(valueA, unitA); @@ -664,8 +679,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricConductivity.FromSiemensPerMeter(firstValue); var otherQuantity = ElectricConductivity.FromSiemensPerMeter(secondValue); ElectricConductivity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricConductivity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -684,7 +699,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -697,6 +712,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricConductivity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricConductivity.Info.Units, ElectricConductivity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricConductivity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -769,7 +796,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricConductivity.FromSiemensPerMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricConductivity), quantity.As(ElectricConductivity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs index 511752812c..57caada418 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentDensityTestsBase.g.cs @@ -133,6 +133,20 @@ public void ElectricCurrentDensity_QuantityInfo_ReturnsQuantityInfoDescribingQua Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricCurrentDensityInfo_CreateWithCustomUnitInfos() + { + ElectricCurrentDensityUnit[] expectedUnits = [ElectricCurrentDensityUnit.AmperePerSquareMeter]; + + ElectricCurrentDensity.ElectricCurrentDensityInfo quantityInfo = ElectricCurrentDensity.ElectricCurrentDensityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricCurrentDensity", quantityInfo.Name); + Assert.Equal(ElectricCurrentDensity.Zero, quantityInfo.Zero); + Assert.Equal(ElectricCurrentDensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void AmperePerSquareMeterToElectricCurrentDensityUnits() { @@ -290,7 +304,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 A/ft²", ElectricCurrentDensityUnit.AmperePerSquareFoot, 4.2)] [InlineData("en-US", "4.2 A/in²", ElectricCurrentDensityUnit.AmperePerSquareInch, 4.2)] [InlineData("en-US", "4.2 A/m²", ElectricCurrentDensityUnit.AmperePerSquareMeter, 4.2)] - public void Parse(string culture, string quantityString, ElectricCurrentDensityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricCurrentDensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricCurrentDensity.Parse(quantityString); @@ -302,7 +316,7 @@ public void Parse(string culture, string quantityString, ElectricCurrentDensityU [InlineData("en-US", "4.2 A/ft²", ElectricCurrentDensityUnit.AmperePerSquareFoot, 4.2)] [InlineData("en-US", "4.2 A/in²", ElectricCurrentDensityUnit.AmperePerSquareInch, 4.2)] [InlineData("en-US", "4.2 A/m²", ElectricCurrentDensityUnit.AmperePerSquareMeter, 4.2)] - public void TryParse(string culture, string quantityString, ElectricCurrentDensityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricCurrentDensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricCurrentDensity.TryParse(quantityString, out ElectricCurrentDensity parsed)); @@ -453,6 +467,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricCurrentD var quantity = ElectricCurrentDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -476,34 +491,36 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricCurrentDens IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricCurrentDensity amperepersquaremeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - AssertEx.EqualTolerance(1, ElectricCurrentDensity.FromAmperesPerSquareFoot(amperepersquaremeter.AmperesPerSquareFoot).AmperesPerSquareMeter, AmperesPerSquareFootTolerance); - AssertEx.EqualTolerance(1, ElectricCurrentDensity.FromAmperesPerSquareInch(amperepersquaremeter.AmperesPerSquareInch).AmperesPerSquareMeter, AmperesPerSquareInchTolerance); - AssertEx.EqualTolerance(1, ElectricCurrentDensity.FromAmperesPerSquareMeter(amperepersquaremeter.AmperesPerSquareMeter).AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); + ElectricCurrentDensity amperepersquaremeter = ElectricCurrentDensity.FromAmperesPerSquareMeter(3); + Assert.Equal(3, ElectricCurrentDensity.FromAmperesPerSquareFoot(amperepersquaremeter.AmperesPerSquareFoot).AmperesPerSquareMeter); + Assert.Equal(3, ElectricCurrentDensity.FromAmperesPerSquareInch(amperepersquaremeter.AmperesPerSquareInch).AmperesPerSquareMeter); + Assert.Equal(3, ElectricCurrentDensity.FromAmperesPerSquareMeter(amperepersquaremeter.AmperesPerSquareMeter).AmperesPerSquareMeter); } [Fact] public void ArithmeticOperators() { ElectricCurrentDensity v = ElectricCurrentDensity.FromAmperesPerSquareMeter(1); - AssertEx.EqualTolerance(-1, -v.AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricCurrentDensity.FromAmperesPerSquareMeter(3)-v).AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricCurrentDensity.FromAmperesPerSquareMeter(10)/5).AmperesPerSquareMeter, AmperesPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, ElectricCurrentDensity.FromAmperesPerSquareMeter(10)/ElectricCurrentDensity.FromAmperesPerSquareMeter(5), AmperesPerSquareMeterTolerance); + Assert.Equal(-1, -v.AmperesPerSquareMeter); + Assert.Equal(2, (ElectricCurrentDensity.FromAmperesPerSquareMeter(3) - v).AmperesPerSquareMeter); + Assert.Equal(2, (v + v).AmperesPerSquareMeter); + Assert.Equal(10, (v * 10).AmperesPerSquareMeter); + Assert.Equal(10, (10 * v).AmperesPerSquareMeter); + Assert.Equal(2, (ElectricCurrentDensity.FromAmperesPerSquareMeter(10) / 5).AmperesPerSquareMeter); + Assert.Equal(2, ElectricCurrentDensity.FromAmperesPerSquareMeter(10) / ElectricCurrentDensity.FromAmperesPerSquareMeter(5)); } [Fact] @@ -549,8 +566,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricCurrentDensityUnit.AmperePerSquareMeter, 1, ElectricCurrentDensityUnit.AmperePerSquareMeter, true)] // Same value and unit. [InlineData(1, ElectricCurrentDensityUnit.AmperePerSquareMeter, 2, ElectricCurrentDensityUnit.AmperePerSquareMeter, false)] // Different value. - [InlineData(2, ElectricCurrentDensityUnit.AmperePerSquareMeter, 1, ElectricCurrentDensityUnit.AmperePerSquareFoot, false)] // Different value and unit. - [InlineData(1, ElectricCurrentDensityUnit.AmperePerSquareMeter, 1, ElectricCurrentDensityUnit.AmperePerSquareFoot, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricCurrentDensityUnit unitA, double valueB, ElectricCurrentDensityUnit unitB, bool expectEqual) { var a = new ElectricCurrentDensity(valueA, unitA); @@ -610,8 +625,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(firstValue); var otherQuantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(secondValue); ElectricCurrentDensity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricCurrentDensity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -630,7 +645,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -643,6 +658,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricCurrentDensity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricCurrentDensity.Info.Units, ElectricCurrentDensity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricCurrentDensity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -709,7 +736,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricCurrentDensity.FromAmperesPerSquareMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricCurrentDensity), quantity.As(ElectricCurrentDensity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs index 06ffb5ed6a..2e25fdc44d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentGradientTestsBase.g.cs @@ -149,6 +149,20 @@ public void ElectricCurrentGradient_QuantityInfo_ReturnsQuantityInfoDescribingQu Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricCurrentGradientInfo_CreateWithCustomUnitInfos() + { + ElectricCurrentGradientUnit[] expectedUnits = [ElectricCurrentGradientUnit.AmperePerSecond]; + + ElectricCurrentGradient.ElectricCurrentGradientInfo quantityInfo = ElectricCurrentGradient.ElectricCurrentGradientInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricCurrentGradient", quantityInfo.Name); + Assert.Equal(ElectricCurrentGradient.Zero, quantityInfo.Zero); + Assert.Equal(ElectricCurrentGradient.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void AmperePerSecondToElectricCurrentGradientUnits() { @@ -318,7 +332,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 A/s", ElectricCurrentGradientUnit.AmperePerSecond, 4.2)] [InlineData("en-US", "4.2 mA/min", ElectricCurrentGradientUnit.MilliamperePerMinute, 4.2)] [InlineData("en-US", "4.2 mA/s", ElectricCurrentGradientUnit.MilliamperePerSecond, 4.2)] - public void Parse(string culture, string quantityString, ElectricCurrentGradientUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricCurrentGradientUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricCurrentGradient.Parse(quantityString); @@ -334,7 +348,7 @@ public void Parse(string culture, string quantityString, ElectricCurrentGradient [InlineData("en-US", "4.2 A/s", ElectricCurrentGradientUnit.AmperePerSecond, 4.2)] [InlineData("en-US", "4.2 mA/min", ElectricCurrentGradientUnit.MilliamperePerMinute, 4.2)] [InlineData("en-US", "4.2 mA/s", ElectricCurrentGradientUnit.MilliamperePerSecond, 4.2)] - public void TryParse(string culture, string quantityString, ElectricCurrentGradientUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricCurrentGradientUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricCurrentGradient.TryParse(quantityString, out ElectricCurrentGradient parsed)); @@ -521,6 +535,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricCurrentG var quantity = ElectricCurrentGradient.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -544,38 +559,40 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricCurrentGrad IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricCurrentGradient amperepersecond = ElectricCurrentGradient.FromAmperesPerSecond(1); - AssertEx.EqualTolerance(1, ElectricCurrentGradient.FromAmperesPerMicrosecond(amperepersecond.AmperesPerMicrosecond).AmperesPerSecond, AmperesPerMicrosecondTolerance); - AssertEx.EqualTolerance(1, ElectricCurrentGradient.FromAmperesPerMillisecond(amperepersecond.AmperesPerMillisecond).AmperesPerSecond, AmperesPerMillisecondTolerance); - AssertEx.EqualTolerance(1, ElectricCurrentGradient.FromAmperesPerMinute(amperepersecond.AmperesPerMinute).AmperesPerSecond, AmperesPerMinuteTolerance); - AssertEx.EqualTolerance(1, ElectricCurrentGradient.FromAmperesPerNanosecond(amperepersecond.AmperesPerNanosecond).AmperesPerSecond, AmperesPerNanosecondTolerance); - AssertEx.EqualTolerance(1, ElectricCurrentGradient.FromAmperesPerSecond(amperepersecond.AmperesPerSecond).AmperesPerSecond, AmperesPerSecondTolerance); - AssertEx.EqualTolerance(1, ElectricCurrentGradient.FromMilliamperesPerMinute(amperepersecond.MilliamperesPerMinute).AmperesPerSecond, MilliamperesPerMinuteTolerance); - AssertEx.EqualTolerance(1, ElectricCurrentGradient.FromMilliamperesPerSecond(amperepersecond.MilliamperesPerSecond).AmperesPerSecond, MilliamperesPerSecondTolerance); + ElectricCurrentGradient amperepersecond = ElectricCurrentGradient.FromAmperesPerSecond(3); + Assert.Equal(3, ElectricCurrentGradient.FromAmperesPerMicrosecond(amperepersecond.AmperesPerMicrosecond).AmperesPerSecond); + Assert.Equal(3, ElectricCurrentGradient.FromAmperesPerMillisecond(amperepersecond.AmperesPerMillisecond).AmperesPerSecond); + Assert.Equal(3, ElectricCurrentGradient.FromAmperesPerMinute(amperepersecond.AmperesPerMinute).AmperesPerSecond); + Assert.Equal(3, ElectricCurrentGradient.FromAmperesPerNanosecond(amperepersecond.AmperesPerNanosecond).AmperesPerSecond); + Assert.Equal(3, ElectricCurrentGradient.FromAmperesPerSecond(amperepersecond.AmperesPerSecond).AmperesPerSecond); + Assert.Equal(3, ElectricCurrentGradient.FromMilliamperesPerMinute(amperepersecond.MilliamperesPerMinute).AmperesPerSecond); + Assert.Equal(3, ElectricCurrentGradient.FromMilliamperesPerSecond(amperepersecond.MilliamperesPerSecond).AmperesPerSecond); } [Fact] public void ArithmeticOperators() { ElectricCurrentGradient v = ElectricCurrentGradient.FromAmperesPerSecond(1); - AssertEx.EqualTolerance(-1, -v.AmperesPerSecond, AmperesPerSecondTolerance); - AssertEx.EqualTolerance(2, (ElectricCurrentGradient.FromAmperesPerSecond(3)-v).AmperesPerSecond, AmperesPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).AmperesPerSecond, AmperesPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).AmperesPerSecond, AmperesPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).AmperesPerSecond, AmperesPerSecondTolerance); - AssertEx.EqualTolerance(2, (ElectricCurrentGradient.FromAmperesPerSecond(10)/5).AmperesPerSecond, AmperesPerSecondTolerance); - AssertEx.EqualTolerance(2, ElectricCurrentGradient.FromAmperesPerSecond(10)/ElectricCurrentGradient.FromAmperesPerSecond(5), AmperesPerSecondTolerance); + Assert.Equal(-1, -v.AmperesPerSecond); + Assert.Equal(2, (ElectricCurrentGradient.FromAmperesPerSecond(3) - v).AmperesPerSecond); + Assert.Equal(2, (v + v).AmperesPerSecond); + Assert.Equal(10, (v * 10).AmperesPerSecond); + Assert.Equal(10, (10 * v).AmperesPerSecond); + Assert.Equal(2, (ElectricCurrentGradient.FromAmperesPerSecond(10) / 5).AmperesPerSecond); + Assert.Equal(2, ElectricCurrentGradient.FromAmperesPerSecond(10) / ElectricCurrentGradient.FromAmperesPerSecond(5)); } [Fact] @@ -621,8 +638,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricCurrentGradientUnit.AmperePerSecond, 1, ElectricCurrentGradientUnit.AmperePerSecond, true)] // Same value and unit. [InlineData(1, ElectricCurrentGradientUnit.AmperePerSecond, 2, ElectricCurrentGradientUnit.AmperePerSecond, false)] // Different value. - [InlineData(2, ElectricCurrentGradientUnit.AmperePerSecond, 1, ElectricCurrentGradientUnit.AmperePerMicrosecond, false)] // Different value and unit. - [InlineData(1, ElectricCurrentGradientUnit.AmperePerSecond, 1, ElectricCurrentGradientUnit.AmperePerMicrosecond, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricCurrentGradientUnit unitA, double valueB, ElectricCurrentGradientUnit unitB, bool expectEqual) { var a = new ElectricCurrentGradient(valueA, unitA); @@ -682,8 +697,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricCurrentGradient.FromAmperesPerSecond(firstValue); var otherQuantity = ElectricCurrentGradient.FromAmperesPerSecond(secondValue); ElectricCurrentGradient maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricCurrentGradient.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -702,7 +717,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -715,6 +730,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricCurrentGradient.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricCurrentGradient.Info.Units, ElectricCurrentGradient.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricCurrentGradient.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -789,7 +816,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricCurrentGradient.FromAmperesPerSecond(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricCurrentGradient), quantity.As(ElectricCurrentGradient.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs index 7f57094893..5db29a253c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricCurrentTestsBase.g.cs @@ -157,6 +157,20 @@ public void ElectricCurrent_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricCurrentInfo_CreateWithCustomUnitInfos() + { + ElectricCurrentUnit[] expectedUnits = [ElectricCurrentUnit.Ampere]; + + ElectricCurrent.ElectricCurrentInfo quantityInfo = ElectricCurrent.ElectricCurrentInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricCurrent", quantityInfo.Name); + Assert.Equal(ElectricCurrent.Zero, quantityInfo.Zero); + Assert.Equal(ElectricCurrent.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void AmpereToElectricCurrentUnits() { @@ -332,7 +346,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 mA", ElectricCurrentUnit.Milliampere, 4.2)] [InlineData("en-US", "4.2 nA", ElectricCurrentUnit.Nanoampere, 4.2)] [InlineData("en-US", "4.2 pA", ElectricCurrentUnit.Picoampere, 4.2)] - public void Parse(string culture, string quantityString, ElectricCurrentUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricCurrentUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricCurrent.Parse(quantityString); @@ -350,7 +364,7 @@ public void Parse(string culture, string quantityString, ElectricCurrentUnit exp [InlineData("en-US", "4.2 mA", ElectricCurrentUnit.Milliampere, 4.2)] [InlineData("en-US", "4.2 nA", ElectricCurrentUnit.Nanoampere, 4.2)] [InlineData("en-US", "4.2 pA", ElectricCurrentUnit.Picoampere, 4.2)] - public void TryParse(string culture, string quantityString, ElectricCurrentUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricCurrentUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricCurrent.TryParse(quantityString, out ElectricCurrent parsed)); @@ -555,6 +569,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricCurrentU var quantity = ElectricCurrent.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -578,40 +593,42 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricCurrentUnit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricCurrent ampere = ElectricCurrent.FromAmperes(1); - AssertEx.EqualTolerance(1, ElectricCurrent.FromAmperes(ampere.Amperes).Amperes, AmperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.FromCentiamperes(ampere.Centiamperes).Amperes, CentiamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.FromFemtoamperes(ampere.Femtoamperes).Amperes, FemtoamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.FromKiloamperes(ampere.Kiloamperes).Amperes, KiloamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.FromMegaamperes(ampere.Megaamperes).Amperes, MegaamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.FromMicroamperes(ampere.Microamperes).Amperes, MicroamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.FromMilliamperes(ampere.Milliamperes).Amperes, MilliamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.FromNanoamperes(ampere.Nanoamperes).Amperes, NanoamperesTolerance); - AssertEx.EqualTolerance(1, ElectricCurrent.FromPicoamperes(ampere.Picoamperes).Amperes, PicoamperesTolerance); + ElectricCurrent ampere = ElectricCurrent.FromAmperes(3); + Assert.Equal(3, ElectricCurrent.FromAmperes(ampere.Amperes).Amperes); + Assert.Equal(3, ElectricCurrent.FromCentiamperes(ampere.Centiamperes).Amperes); + Assert.Equal(3, ElectricCurrent.FromFemtoamperes(ampere.Femtoamperes).Amperes); + Assert.Equal(3, ElectricCurrent.FromKiloamperes(ampere.Kiloamperes).Amperes); + Assert.Equal(3, ElectricCurrent.FromMegaamperes(ampere.Megaamperes).Amperes); + Assert.Equal(3, ElectricCurrent.FromMicroamperes(ampere.Microamperes).Amperes); + Assert.Equal(3, ElectricCurrent.FromMilliamperes(ampere.Milliamperes).Amperes); + Assert.Equal(3, ElectricCurrent.FromNanoamperes(ampere.Nanoamperes).Amperes); + Assert.Equal(3, ElectricCurrent.FromPicoamperes(ampere.Picoamperes).Amperes); } [Fact] public void ArithmeticOperators() { ElectricCurrent v = ElectricCurrent.FromAmperes(1); - AssertEx.EqualTolerance(-1, -v.Amperes, AmperesTolerance); - AssertEx.EqualTolerance(2, (ElectricCurrent.FromAmperes(3)-v).Amperes, AmperesTolerance); - AssertEx.EqualTolerance(2, (v + v).Amperes, AmperesTolerance); - AssertEx.EqualTolerance(10, (v*10).Amperes, AmperesTolerance); - AssertEx.EqualTolerance(10, (10*v).Amperes, AmperesTolerance); - AssertEx.EqualTolerance(2, (ElectricCurrent.FromAmperes(10)/5).Amperes, AmperesTolerance); - AssertEx.EqualTolerance(2, ElectricCurrent.FromAmperes(10)/ElectricCurrent.FromAmperes(5), AmperesTolerance); + Assert.Equal(-1, -v.Amperes); + Assert.Equal(2, (ElectricCurrent.FromAmperes(3) - v).Amperes); + Assert.Equal(2, (v + v).Amperes); + Assert.Equal(10, (v * 10).Amperes); + Assert.Equal(10, (10 * v).Amperes); + Assert.Equal(2, (ElectricCurrent.FromAmperes(10) / 5).Amperes); + Assert.Equal(2, ElectricCurrent.FromAmperes(10) / ElectricCurrent.FromAmperes(5)); } [Fact] @@ -657,8 +674,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricCurrentUnit.Ampere, 1, ElectricCurrentUnit.Ampere, true)] // Same value and unit. [InlineData(1, ElectricCurrentUnit.Ampere, 2, ElectricCurrentUnit.Ampere, false)] // Different value. - [InlineData(2, ElectricCurrentUnit.Ampere, 1, ElectricCurrentUnit.Centiampere, false)] // Different value and unit. - [InlineData(1, ElectricCurrentUnit.Ampere, 1, ElectricCurrentUnit.Centiampere, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricCurrentUnit unitA, double valueB, ElectricCurrentUnit unitB, bool expectEqual) { var a = new ElectricCurrent(valueA, unitA); @@ -718,8 +733,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricCurrent.FromAmperes(firstValue); var otherQuantity = ElectricCurrent.FromAmperes(secondValue); ElectricCurrent maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricCurrent.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -738,7 +753,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -751,6 +766,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricCurrent.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricCurrent.Info.Units, ElectricCurrent.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricCurrent.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -829,7 +856,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricCurrent.FromAmperes(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricCurrent), quantity.As(ElectricCurrent.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs index 22cd463564..6a42204a78 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricFieldTestsBase.g.cs @@ -125,6 +125,20 @@ public void ElectricField_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricFieldInfo_CreateWithCustomUnitInfos() + { + ElectricFieldUnit[] expectedUnits = [ElectricFieldUnit.VoltPerMeter]; + + ElectricField.ElectricFieldInfo quantityInfo = ElectricField.ElectricFieldInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricField", quantityInfo.Name); + Assert.Equal(ElectricField.Zero, quantityInfo.Zero); + Assert.Equal(ElectricField.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void VoltPerMeterToElectricFieldUnits() { @@ -276,7 +290,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Theory] [InlineData("en-US", "4.2 V/m", ElectricFieldUnit.VoltPerMeter, 4.2)] - public void Parse(string culture, string quantityString, ElectricFieldUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricFieldUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricField.Parse(quantityString); @@ -286,7 +300,7 @@ public void Parse(string culture, string quantityString, ElectricFieldUnit expec [Theory] [InlineData("en-US", "4.2 V/m", ElectricFieldUnit.VoltPerMeter, 4.2)] - public void TryParse(string culture, string quantityString, ElectricFieldUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricFieldUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricField.TryParse(quantityString, out ElectricField parsed)); @@ -419,6 +433,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricFieldUni var quantity = ElectricField.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -442,32 +457,34 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricFieldUnit u IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricField voltpermeter = ElectricField.FromVoltsPerMeter(1); - AssertEx.EqualTolerance(1, ElectricField.FromVoltsPerMeter(voltpermeter.VoltsPerMeter).VoltsPerMeter, VoltsPerMeterTolerance); + ElectricField voltpermeter = ElectricField.FromVoltsPerMeter(3); + Assert.Equal(3, ElectricField.FromVoltsPerMeter(voltpermeter.VoltsPerMeter).VoltsPerMeter); } [Fact] public void ArithmeticOperators() { ElectricField v = ElectricField.FromVoltsPerMeter(1); - AssertEx.EqualTolerance(-1, -v.VoltsPerMeter, VoltsPerMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricField.FromVoltsPerMeter(3)-v).VoltsPerMeter, VoltsPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).VoltsPerMeter, VoltsPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).VoltsPerMeter, VoltsPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).VoltsPerMeter, VoltsPerMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricField.FromVoltsPerMeter(10)/5).VoltsPerMeter, VoltsPerMeterTolerance); - AssertEx.EqualTolerance(2, ElectricField.FromVoltsPerMeter(10)/ElectricField.FromVoltsPerMeter(5), VoltsPerMeterTolerance); + Assert.Equal(-1, -v.VoltsPerMeter); + Assert.Equal(2, (ElectricField.FromVoltsPerMeter(3) - v).VoltsPerMeter); + Assert.Equal(2, (v + v).VoltsPerMeter); + Assert.Equal(10, (v * 10).VoltsPerMeter); + Assert.Equal(10, (10 * v).VoltsPerMeter); + Assert.Equal(2, (ElectricField.FromVoltsPerMeter(10) / 5).VoltsPerMeter); + Assert.Equal(2, ElectricField.FromVoltsPerMeter(10) / ElectricField.FromVoltsPerMeter(5)); } [Fact] @@ -513,7 +530,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricFieldUnit.VoltPerMeter, 1, ElectricFieldUnit.VoltPerMeter, true)] // Same value and unit. [InlineData(1, ElectricFieldUnit.VoltPerMeter, 2, ElectricFieldUnit.VoltPerMeter, false)] // Different value. - [InlineData(2, ElectricFieldUnit.VoltPerMeter, 1, ElectricFieldUnit.VoltPerMeter, false)] // Different value and unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricFieldUnit unitA, double valueB, ElectricFieldUnit unitB, bool expectEqual) { var a = new ElectricField(valueA, unitA); @@ -573,8 +589,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricField.FromVoltsPerMeter(firstValue); var otherQuantity = ElectricField.FromVoltsPerMeter(secondValue); ElectricField maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricField.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -593,7 +609,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -606,6 +622,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricField.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricField.Info.Units, ElectricField.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricField.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -668,7 +696,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricField.FromVoltsPerMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricField), quantity.As(ElectricField.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricImpedanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricImpedanceTestsBase.g.cs index 2817aa9799..70d5dfb46b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricImpedanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricImpedanceTestsBase.g.cs @@ -153,6 +153,20 @@ public void ElectricImpedance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricImpedanceInfo_CreateWithCustomUnitInfos() + { + ElectricImpedanceUnit[] expectedUnits = [ElectricImpedanceUnit.Ohm]; + + ElectricImpedance.ElectricImpedanceInfo quantityInfo = ElectricImpedance.ElectricImpedanceInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricImpedance", quantityInfo.Name); + Assert.Equal(ElectricImpedance.Zero, quantityInfo.Zero); + Assert.Equal(ElectricImpedance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void OhmToElectricImpedanceUnits() { @@ -325,7 +339,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 nΩ", ElectricImpedanceUnit.Nanoohm, 4.2)] [InlineData("en-US", "4.2 Ω", ElectricImpedanceUnit.Ohm, 4.2)] [InlineData("en-US", "4.2 TΩ", ElectricImpedanceUnit.Teraohm, 4.2)] - public void Parse(string culture, string quantityString, ElectricImpedanceUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricImpedanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricImpedance.Parse(quantityString); @@ -342,7 +356,7 @@ public void Parse(string culture, string quantityString, ElectricImpedanceUnit e [InlineData("en-US", "4.2 nΩ", ElectricImpedanceUnit.Nanoohm, 4.2)] [InlineData("en-US", "4.2 Ω", ElectricImpedanceUnit.Ohm, 4.2)] [InlineData("en-US", "4.2 TΩ", ElectricImpedanceUnit.Teraohm, 4.2)] - public void TryParse(string culture, string quantityString, ElectricImpedanceUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricImpedanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricImpedance.TryParse(quantityString, out ElectricImpedance parsed)); @@ -538,6 +552,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricImpedanc var quantity = ElectricImpedance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -561,39 +576,41 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricImpedanceUn IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricImpedance ohm = ElectricImpedance.FromOhms(1); - AssertEx.EqualTolerance(1, ElectricImpedance.FromGigaohms(ohm.Gigaohms).Ohms, GigaohmsTolerance); - AssertEx.EqualTolerance(1, ElectricImpedance.FromKiloohms(ohm.Kiloohms).Ohms, KiloohmsTolerance); - AssertEx.EqualTolerance(1, ElectricImpedance.FromMegaohms(ohm.Megaohms).Ohms, MegaohmsTolerance); - AssertEx.EqualTolerance(1, ElectricImpedance.FromMicroohms(ohm.Microohms).Ohms, MicroohmsTolerance); - AssertEx.EqualTolerance(1, ElectricImpedance.FromMilliohms(ohm.Milliohms).Ohms, MilliohmsTolerance); - AssertEx.EqualTolerance(1, ElectricImpedance.FromNanoohms(ohm.Nanoohms).Ohms, NanoohmsTolerance); - AssertEx.EqualTolerance(1, ElectricImpedance.FromOhms(ohm.Ohms).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(1, ElectricImpedance.FromTeraohms(ohm.Teraohms).Ohms, TeraohmsTolerance); + ElectricImpedance ohm = ElectricImpedance.FromOhms(3); + Assert.Equal(3, ElectricImpedance.FromGigaohms(ohm.Gigaohms).Ohms); + Assert.Equal(3, ElectricImpedance.FromKiloohms(ohm.Kiloohms).Ohms); + Assert.Equal(3, ElectricImpedance.FromMegaohms(ohm.Megaohms).Ohms); + Assert.Equal(3, ElectricImpedance.FromMicroohms(ohm.Microohms).Ohms); + Assert.Equal(3, ElectricImpedance.FromMilliohms(ohm.Milliohms).Ohms); + Assert.Equal(3, ElectricImpedance.FromNanoohms(ohm.Nanoohms).Ohms); + Assert.Equal(3, ElectricImpedance.FromOhms(ohm.Ohms).Ohms); + Assert.Equal(3, ElectricImpedance.FromTeraohms(ohm.Teraohms).Ohms); } [Fact] public void ArithmeticOperators() { ElectricImpedance v = ElectricImpedance.FromOhms(1); - AssertEx.EqualTolerance(-1, -v.Ohms, OhmsTolerance); - AssertEx.EqualTolerance(2, (ElectricImpedance.FromOhms(3)-v).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(2, (v + v).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(10, (v*10).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(10, (10*v).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(2, (ElectricImpedance.FromOhms(10)/5).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(2, ElectricImpedance.FromOhms(10)/ElectricImpedance.FromOhms(5), OhmsTolerance); + Assert.Equal(-1, -v.Ohms); + Assert.Equal(2, (ElectricImpedance.FromOhms(3) - v).Ohms); + Assert.Equal(2, (v + v).Ohms); + Assert.Equal(10, (v * 10).Ohms); + Assert.Equal(10, (10 * v).Ohms); + Assert.Equal(2, (ElectricImpedance.FromOhms(10) / 5).Ohms); + Assert.Equal(2, ElectricImpedance.FromOhms(10) / ElectricImpedance.FromOhms(5)); } [Fact] @@ -639,8 +656,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricImpedanceUnit.Ohm, 1, ElectricImpedanceUnit.Ohm, true)] // Same value and unit. [InlineData(1, ElectricImpedanceUnit.Ohm, 2, ElectricImpedanceUnit.Ohm, false)] // Different value. - [InlineData(2, ElectricImpedanceUnit.Ohm, 1, ElectricImpedanceUnit.Gigaohm, false)] // Different value and unit. - [InlineData(1, ElectricImpedanceUnit.Ohm, 1, ElectricImpedanceUnit.Gigaohm, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricImpedanceUnit unitA, double valueB, ElectricImpedanceUnit unitB, bool expectEqual) { var a = new ElectricImpedance(valueA, unitA); @@ -700,8 +715,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricImpedance.FromOhms(firstValue); var otherQuantity = ElectricImpedance.FromOhms(secondValue); ElectricImpedance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricImpedance.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -720,7 +735,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -733,6 +748,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricImpedance.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricImpedance.Info.Units, ElectricImpedance.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricImpedance.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -809,7 +836,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricImpedance.FromOhms(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricImpedance), quantity.As(ElectricImpedance.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs index 53a5eac00c..ce3be58b34 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricInductanceTestsBase.g.cs @@ -141,6 +141,20 @@ public void ElectricInductance_QuantityInfo_ReturnsQuantityInfoDescribingQuantit Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricInductanceInfo_CreateWithCustomUnitInfos() + { + ElectricInductanceUnit[] expectedUnits = [ElectricInductanceUnit.Henry]; + + ElectricInductance.ElectricInductanceInfo quantityInfo = ElectricInductance.ElectricInductanceInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricInductance", quantityInfo.Name); + Assert.Equal(ElectricInductance.Zero, quantityInfo.Zero); + Assert.Equal(ElectricInductance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void HenryToElectricInductanceUnits() { @@ -304,7 +318,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 mH", ElectricInductanceUnit.Millihenry, 4.2)] [InlineData("en-US", "4.2 nH", ElectricInductanceUnit.Nanohenry, 4.2)] [InlineData("en-US", "4.2 pH", ElectricInductanceUnit.Picohenry, 4.2)] - public void Parse(string culture, string quantityString, ElectricInductanceUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricInductanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricInductance.Parse(quantityString); @@ -318,7 +332,7 @@ public void Parse(string culture, string quantityString, ElectricInductanceUnit [InlineData("en-US", "4.2 mH", ElectricInductanceUnit.Millihenry, 4.2)] [InlineData("en-US", "4.2 nH", ElectricInductanceUnit.Nanohenry, 4.2)] [InlineData("en-US", "4.2 pH", ElectricInductanceUnit.Picohenry, 4.2)] - public void TryParse(string culture, string quantityString, ElectricInductanceUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricInductanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricInductance.TryParse(quantityString, out ElectricInductance parsed)); @@ -487,6 +501,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricInductan var quantity = ElectricInductance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -510,36 +525,38 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricInductanceU IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricInductance henry = ElectricInductance.FromHenries(1); - AssertEx.EqualTolerance(1, ElectricInductance.FromHenries(henry.Henries).Henries, HenriesTolerance); - AssertEx.EqualTolerance(1, ElectricInductance.FromMicrohenries(henry.Microhenries).Henries, MicrohenriesTolerance); - AssertEx.EqualTolerance(1, ElectricInductance.FromMillihenries(henry.Millihenries).Henries, MillihenriesTolerance); - AssertEx.EqualTolerance(1, ElectricInductance.FromNanohenries(henry.Nanohenries).Henries, NanohenriesTolerance); - AssertEx.EqualTolerance(1, ElectricInductance.FromPicohenries(henry.Picohenries).Henries, PicohenriesTolerance); + ElectricInductance henry = ElectricInductance.FromHenries(3); + Assert.Equal(3, ElectricInductance.FromHenries(henry.Henries).Henries); + Assert.Equal(3, ElectricInductance.FromMicrohenries(henry.Microhenries).Henries); + Assert.Equal(3, ElectricInductance.FromMillihenries(henry.Millihenries).Henries); + Assert.Equal(3, ElectricInductance.FromNanohenries(henry.Nanohenries).Henries); + Assert.Equal(3, ElectricInductance.FromPicohenries(henry.Picohenries).Henries); } [Fact] public void ArithmeticOperators() { ElectricInductance v = ElectricInductance.FromHenries(1); - AssertEx.EqualTolerance(-1, -v.Henries, HenriesTolerance); - AssertEx.EqualTolerance(2, (ElectricInductance.FromHenries(3)-v).Henries, HenriesTolerance); - AssertEx.EqualTolerance(2, (v + v).Henries, HenriesTolerance); - AssertEx.EqualTolerance(10, (v*10).Henries, HenriesTolerance); - AssertEx.EqualTolerance(10, (10*v).Henries, HenriesTolerance); - AssertEx.EqualTolerance(2, (ElectricInductance.FromHenries(10)/5).Henries, HenriesTolerance); - AssertEx.EqualTolerance(2, ElectricInductance.FromHenries(10)/ElectricInductance.FromHenries(5), HenriesTolerance); + Assert.Equal(-1, -v.Henries); + Assert.Equal(2, (ElectricInductance.FromHenries(3) - v).Henries); + Assert.Equal(2, (v + v).Henries); + Assert.Equal(10, (v * 10).Henries); + Assert.Equal(10, (10 * v).Henries); + Assert.Equal(2, (ElectricInductance.FromHenries(10) / 5).Henries); + Assert.Equal(2, ElectricInductance.FromHenries(10) / ElectricInductance.FromHenries(5)); } [Fact] @@ -585,8 +602,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricInductanceUnit.Henry, 1, ElectricInductanceUnit.Henry, true)] // Same value and unit. [InlineData(1, ElectricInductanceUnit.Henry, 2, ElectricInductanceUnit.Henry, false)] // Different value. - [InlineData(2, ElectricInductanceUnit.Henry, 1, ElectricInductanceUnit.Microhenry, false)] // Different value and unit. - [InlineData(1, ElectricInductanceUnit.Henry, 1, ElectricInductanceUnit.Microhenry, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricInductanceUnit unitA, double valueB, ElectricInductanceUnit unitB, bool expectEqual) { var a = new ElectricInductance(valueA, unitA); @@ -646,8 +661,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricInductance.FromHenries(firstValue); var otherQuantity = ElectricInductance.FromHenries(secondValue); ElectricInductance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricInductance.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -666,7 +681,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -679,6 +694,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricInductance.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricInductance.Info.Units, ElectricInductance.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricInductance.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -749,7 +776,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricInductance.FromHenries(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricInductance), quantity.As(ElectricInductance.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs index 98b93a6825..3a740799a1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialChangeRateTestsBase.g.cs @@ -201,6 +201,20 @@ public void ElectricPotentialChangeRate_QuantityInfo_ReturnsQuantityInfoDescribi Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricPotentialChangeRateInfo_CreateWithCustomUnitInfos() + { + ElectricPotentialChangeRateUnit[] expectedUnits = [ElectricPotentialChangeRateUnit.VoltPerSecond]; + + ElectricPotentialChangeRate.ElectricPotentialChangeRateInfo quantityInfo = ElectricPotentialChangeRate.ElectricPotentialChangeRateInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricPotentialChangeRate", quantityInfo.Name); + Assert.Equal(ElectricPotentialChangeRate.Zero, quantityInfo.Zero); + Assert.Equal(ElectricPotentialChangeRate.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void VoltPerSecondToElectricPotentialChangeRateUnits() { @@ -409,7 +423,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 V/μs", ElectricPotentialChangeRateUnit.VoltPerMicrosecond, 4.2)] [InlineData("en-US", "4.2 V/min", ElectricPotentialChangeRateUnit.VoltPerMinute, 4.2)] [InlineData("en-US", "4.2 V/s", ElectricPotentialChangeRateUnit.VoltPerSecond, 4.2)] - public void Parse(string culture, string quantityString, ElectricPotentialChangeRateUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricPotentialChangeRateUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricPotentialChangeRate.Parse(quantityString); @@ -438,7 +452,7 @@ public void Parse(string culture, string quantityString, ElectricPotentialChange [InlineData("en-US", "4.2 V/μs", ElectricPotentialChangeRateUnit.VoltPerMicrosecond, 4.2)] [InlineData("en-US", "4.2 V/min", ElectricPotentialChangeRateUnit.VoltPerMinute, 4.2)] [InlineData("en-US", "4.2 V/s", ElectricPotentialChangeRateUnit.VoltPerSecond, 4.2)] - public void TryParse(string culture, string quantityString, ElectricPotentialChangeRateUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricPotentialChangeRateUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricPotentialChangeRate.TryParse(quantityString, out ElectricPotentialChangeRate parsed)); @@ -742,6 +756,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricPotentia var quantity = ElectricPotentialChangeRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -765,51 +780,53 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricPotentialCh IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricPotentialChangeRate voltpersecond = ElectricPotentialChangeRate.FromVoltsPerSecond(1); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromKilovoltsPerHour(voltpersecond.KilovoltsPerHour).VoltsPerSecond, KilovoltsPerHourTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromKilovoltsPerMicrosecond(voltpersecond.KilovoltsPerMicrosecond).VoltsPerSecond, KilovoltsPerMicrosecondTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromKilovoltsPerMinute(voltpersecond.KilovoltsPerMinute).VoltsPerSecond, KilovoltsPerMinuteTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromKilovoltsPerSecond(voltpersecond.KilovoltsPerSecond).VoltsPerSecond, KilovoltsPerSecondTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromMegavoltsPerHour(voltpersecond.MegavoltsPerHour).VoltsPerSecond, MegavoltsPerHourTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromMegavoltsPerMicrosecond(voltpersecond.MegavoltsPerMicrosecond).VoltsPerSecond, MegavoltsPerMicrosecondTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromMegavoltsPerMinute(voltpersecond.MegavoltsPerMinute).VoltsPerSecond, MegavoltsPerMinuteTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromMegavoltsPerSecond(voltpersecond.MegavoltsPerSecond).VoltsPerSecond, MegavoltsPerSecondTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromMicrovoltsPerHour(voltpersecond.MicrovoltsPerHour).VoltsPerSecond, MicrovoltsPerHourTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromMicrovoltsPerMicrosecond(voltpersecond.MicrovoltsPerMicrosecond).VoltsPerSecond, MicrovoltsPerMicrosecondTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromMicrovoltsPerMinute(voltpersecond.MicrovoltsPerMinute).VoltsPerSecond, MicrovoltsPerMinuteTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromMicrovoltsPerSecond(voltpersecond.MicrovoltsPerSecond).VoltsPerSecond, MicrovoltsPerSecondTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromMillivoltsPerHour(voltpersecond.MillivoltsPerHour).VoltsPerSecond, MillivoltsPerHourTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromMillivoltsPerMicrosecond(voltpersecond.MillivoltsPerMicrosecond).VoltsPerSecond, MillivoltsPerMicrosecondTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromMillivoltsPerMinute(voltpersecond.MillivoltsPerMinute).VoltsPerSecond, MillivoltsPerMinuteTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromMillivoltsPerSecond(voltpersecond.MillivoltsPerSecond).VoltsPerSecond, MillivoltsPerSecondTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromVoltsPerHour(voltpersecond.VoltsPerHour).VoltsPerSecond, VoltsPerHourTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromVoltsPerMicrosecond(voltpersecond.VoltsPerMicrosecond).VoltsPerSecond, VoltsPerMicrosecondTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromVoltsPerMinute(voltpersecond.VoltsPerMinute).VoltsPerSecond, VoltsPerMinuteTolerance); - AssertEx.EqualTolerance(1, ElectricPotentialChangeRate.FromVoltsPerSecond(voltpersecond.VoltsPerSecond).VoltsPerSecond, VoltsPerSecondTolerance); + ElectricPotentialChangeRate voltpersecond = ElectricPotentialChangeRate.FromVoltsPerSecond(3); + Assert.Equal(3, ElectricPotentialChangeRate.FromKilovoltsPerHour(voltpersecond.KilovoltsPerHour).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromKilovoltsPerMicrosecond(voltpersecond.KilovoltsPerMicrosecond).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromKilovoltsPerMinute(voltpersecond.KilovoltsPerMinute).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromKilovoltsPerSecond(voltpersecond.KilovoltsPerSecond).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromMegavoltsPerHour(voltpersecond.MegavoltsPerHour).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromMegavoltsPerMicrosecond(voltpersecond.MegavoltsPerMicrosecond).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromMegavoltsPerMinute(voltpersecond.MegavoltsPerMinute).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromMegavoltsPerSecond(voltpersecond.MegavoltsPerSecond).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromMicrovoltsPerHour(voltpersecond.MicrovoltsPerHour).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromMicrovoltsPerMicrosecond(voltpersecond.MicrovoltsPerMicrosecond).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromMicrovoltsPerMinute(voltpersecond.MicrovoltsPerMinute).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromMicrovoltsPerSecond(voltpersecond.MicrovoltsPerSecond).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromMillivoltsPerHour(voltpersecond.MillivoltsPerHour).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromMillivoltsPerMicrosecond(voltpersecond.MillivoltsPerMicrosecond).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromMillivoltsPerMinute(voltpersecond.MillivoltsPerMinute).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromMillivoltsPerSecond(voltpersecond.MillivoltsPerSecond).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromVoltsPerHour(voltpersecond.VoltsPerHour).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromVoltsPerMicrosecond(voltpersecond.VoltsPerMicrosecond).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromVoltsPerMinute(voltpersecond.VoltsPerMinute).VoltsPerSecond); + Assert.Equal(3, ElectricPotentialChangeRate.FromVoltsPerSecond(voltpersecond.VoltsPerSecond).VoltsPerSecond); } [Fact] public void ArithmeticOperators() { ElectricPotentialChangeRate v = ElectricPotentialChangeRate.FromVoltsPerSecond(1); - AssertEx.EqualTolerance(-1, -v.VoltsPerSecond, VoltsPerSecondTolerance); - AssertEx.EqualTolerance(2, (ElectricPotentialChangeRate.FromVoltsPerSecond(3)-v).VoltsPerSecond, VoltsPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).VoltsPerSecond, VoltsPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).VoltsPerSecond, VoltsPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).VoltsPerSecond, VoltsPerSecondTolerance); - AssertEx.EqualTolerance(2, (ElectricPotentialChangeRate.FromVoltsPerSecond(10)/5).VoltsPerSecond, VoltsPerSecondTolerance); - AssertEx.EqualTolerance(2, ElectricPotentialChangeRate.FromVoltsPerSecond(10)/ElectricPotentialChangeRate.FromVoltsPerSecond(5), VoltsPerSecondTolerance); + Assert.Equal(-1, -v.VoltsPerSecond); + Assert.Equal(2, (ElectricPotentialChangeRate.FromVoltsPerSecond(3) - v).VoltsPerSecond); + Assert.Equal(2, (v + v).VoltsPerSecond); + Assert.Equal(10, (v * 10).VoltsPerSecond); + Assert.Equal(10, (10 * v).VoltsPerSecond); + Assert.Equal(2, (ElectricPotentialChangeRate.FromVoltsPerSecond(10) / 5).VoltsPerSecond); + Assert.Equal(2, ElectricPotentialChangeRate.FromVoltsPerSecond(10) / ElectricPotentialChangeRate.FromVoltsPerSecond(5)); } [Fact] @@ -855,8 +872,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricPotentialChangeRateUnit.VoltPerSecond, 1, ElectricPotentialChangeRateUnit.VoltPerSecond, true)] // Same value and unit. [InlineData(1, ElectricPotentialChangeRateUnit.VoltPerSecond, 2, ElectricPotentialChangeRateUnit.VoltPerSecond, false)] // Different value. - [InlineData(2, ElectricPotentialChangeRateUnit.VoltPerSecond, 1, ElectricPotentialChangeRateUnit.KilovoltPerHour, false)] // Different value and unit. - [InlineData(1, ElectricPotentialChangeRateUnit.VoltPerSecond, 1, ElectricPotentialChangeRateUnit.KilovoltPerHour, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricPotentialChangeRateUnit unitA, double valueB, ElectricPotentialChangeRateUnit unitB, bool expectEqual) { var a = new ElectricPotentialChangeRate(valueA, unitA); @@ -916,8 +931,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(firstValue); var otherQuantity = ElectricPotentialChangeRate.FromVoltsPerSecond(secondValue); ElectricPotentialChangeRate maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricPotentialChangeRate.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -936,7 +951,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -949,6 +964,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricPotentialChangeRate.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricPotentialChangeRate.Info.Units, ElectricPotentialChangeRate.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricPotentialChangeRate.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1049,7 +1076,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricPotentialChangeRate.FromVoltsPerSecond(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricPotentialChangeRate), quantity.As(ElectricPotentialChangeRate.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs index 2228b09a0d..db3ede4a40 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricPotentialTestsBase.g.cs @@ -145,6 +145,20 @@ public void ElectricPotential_QuantityInfo_ReturnsQuantityInfoDescribingQuantity Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricPotentialInfo_CreateWithCustomUnitInfos() + { + ElectricPotentialUnit[] expectedUnits = [ElectricPotentialUnit.Volt]; + + ElectricPotential.ElectricPotentialInfo quantityInfo = ElectricPotential.ElectricPotentialInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricPotential", quantityInfo.Name); + Assert.Equal(ElectricPotential.Zero, quantityInfo.Zero); + Assert.Equal(ElectricPotential.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void VoltToElectricPotentialUnits() { @@ -317,7 +331,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 мВ", ElectricPotentialUnit.Millivolt, 4.2)] [InlineData("ru-RU", "4,2 нВ", ElectricPotentialUnit.Nanovolt, 4.2)] [InlineData("ru-RU", "4,2 В", ElectricPotentialUnit.Volt, 4.2)] - public void Parse(string culture, string quantityString, ElectricPotentialUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricPotentialUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricPotential.Parse(quantityString); @@ -338,7 +352,7 @@ public void Parse(string culture, string quantityString, ElectricPotentialUnit e [InlineData("ru-RU", "4,2 мВ", ElectricPotentialUnit.Millivolt, 4.2)] [InlineData("ru-RU", "4,2 нВ", ElectricPotentialUnit.Nanovolt, 4.2)] [InlineData("ru-RU", "4,2 В", ElectricPotentialUnit.Volt, 4.2)] - public void TryParse(string culture, string quantityString, ElectricPotentialUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricPotentialUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricPotential.TryParse(quantityString, out ElectricPotential parsed)); @@ -546,6 +560,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricPotentia var quantity = ElectricPotential.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -569,37 +584,39 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricPotentialUn IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricPotential volt = ElectricPotential.FromVolts(1); - AssertEx.EqualTolerance(1, ElectricPotential.FromKilovolts(volt.Kilovolts).Volts, KilovoltsTolerance); - AssertEx.EqualTolerance(1, ElectricPotential.FromMegavolts(volt.Megavolts).Volts, MegavoltsTolerance); - AssertEx.EqualTolerance(1, ElectricPotential.FromMicrovolts(volt.Microvolts).Volts, MicrovoltsTolerance); - AssertEx.EqualTolerance(1, ElectricPotential.FromMillivolts(volt.Millivolts).Volts, MillivoltsTolerance); - AssertEx.EqualTolerance(1, ElectricPotential.FromNanovolts(volt.Nanovolts).Volts, NanovoltsTolerance); - AssertEx.EqualTolerance(1, ElectricPotential.FromVolts(volt.Volts).Volts, VoltsTolerance); + ElectricPotential volt = ElectricPotential.FromVolts(3); + Assert.Equal(3, ElectricPotential.FromKilovolts(volt.Kilovolts).Volts); + Assert.Equal(3, ElectricPotential.FromMegavolts(volt.Megavolts).Volts); + Assert.Equal(3, ElectricPotential.FromMicrovolts(volt.Microvolts).Volts); + Assert.Equal(3, ElectricPotential.FromMillivolts(volt.Millivolts).Volts); + Assert.Equal(3, ElectricPotential.FromNanovolts(volt.Nanovolts).Volts); + Assert.Equal(3, ElectricPotential.FromVolts(volt.Volts).Volts); } [Fact] public void ArithmeticOperators() { ElectricPotential v = ElectricPotential.FromVolts(1); - AssertEx.EqualTolerance(-1, -v.Volts, VoltsTolerance); - AssertEx.EqualTolerance(2, (ElectricPotential.FromVolts(3)-v).Volts, VoltsTolerance); - AssertEx.EqualTolerance(2, (v + v).Volts, VoltsTolerance); - AssertEx.EqualTolerance(10, (v*10).Volts, VoltsTolerance); - AssertEx.EqualTolerance(10, (10*v).Volts, VoltsTolerance); - AssertEx.EqualTolerance(2, (ElectricPotential.FromVolts(10)/5).Volts, VoltsTolerance); - AssertEx.EqualTolerance(2, ElectricPotential.FromVolts(10)/ElectricPotential.FromVolts(5), VoltsTolerance); + Assert.Equal(-1, -v.Volts); + Assert.Equal(2, (ElectricPotential.FromVolts(3) - v).Volts); + Assert.Equal(2, (v + v).Volts); + Assert.Equal(10, (v * 10).Volts); + Assert.Equal(10, (10 * v).Volts); + Assert.Equal(2, (ElectricPotential.FromVolts(10) / 5).Volts); + Assert.Equal(2, ElectricPotential.FromVolts(10) / ElectricPotential.FromVolts(5)); } [Fact] @@ -645,8 +662,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricPotentialUnit.Volt, 1, ElectricPotentialUnit.Volt, true)] // Same value and unit. [InlineData(1, ElectricPotentialUnit.Volt, 2, ElectricPotentialUnit.Volt, false)] // Different value. - [InlineData(2, ElectricPotentialUnit.Volt, 1, ElectricPotentialUnit.Kilovolt, false)] // Different value and unit. - [InlineData(1, ElectricPotentialUnit.Volt, 1, ElectricPotentialUnit.Kilovolt, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricPotentialUnit unitA, double valueB, ElectricPotentialUnit unitB, bool expectEqual) { var a = new ElectricPotential(valueA, unitA); @@ -706,8 +721,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricPotential.FromVolts(firstValue); var otherQuantity = ElectricPotential.FromVolts(secondValue); ElectricPotential maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricPotential.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -726,7 +741,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -739,6 +754,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricPotential.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricPotential.Info.Units, ElectricPotential.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricPotential.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -811,7 +838,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricPotential.FromVolts(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricPotential), quantity.As(ElectricPotential.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactanceTestsBase.g.cs index e78bdbda65..d383807344 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactanceTestsBase.g.cs @@ -153,6 +153,20 @@ public void ElectricReactance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricReactanceInfo_CreateWithCustomUnitInfos() + { + ElectricReactanceUnit[] expectedUnits = [ElectricReactanceUnit.Ohm]; + + ElectricReactance.ElectricReactanceInfo quantityInfo = ElectricReactance.ElectricReactanceInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricReactance", quantityInfo.Name); + Assert.Equal(ElectricReactance.Zero, quantityInfo.Zero); + Assert.Equal(ElectricReactance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void OhmToElectricReactanceUnits() { @@ -325,7 +339,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 nΩ", ElectricReactanceUnit.Nanoohm, 4.2)] [InlineData("en-US", "4.2 Ω", ElectricReactanceUnit.Ohm, 4.2)] [InlineData("en-US", "4.2 TΩ", ElectricReactanceUnit.Teraohm, 4.2)] - public void Parse(string culture, string quantityString, ElectricReactanceUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricReactanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricReactance.Parse(quantityString); @@ -342,7 +356,7 @@ public void Parse(string culture, string quantityString, ElectricReactanceUnit e [InlineData("en-US", "4.2 nΩ", ElectricReactanceUnit.Nanoohm, 4.2)] [InlineData("en-US", "4.2 Ω", ElectricReactanceUnit.Ohm, 4.2)] [InlineData("en-US", "4.2 TΩ", ElectricReactanceUnit.Teraohm, 4.2)] - public void TryParse(string culture, string quantityString, ElectricReactanceUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricReactanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricReactance.TryParse(quantityString, out ElectricReactance parsed)); @@ -538,6 +552,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricReactanc var quantity = ElectricReactance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -561,39 +576,41 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricReactanceUn IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricReactance ohm = ElectricReactance.FromOhms(1); - AssertEx.EqualTolerance(1, ElectricReactance.FromGigaohms(ohm.Gigaohms).Ohms, GigaohmsTolerance); - AssertEx.EqualTolerance(1, ElectricReactance.FromKiloohms(ohm.Kiloohms).Ohms, KiloohmsTolerance); - AssertEx.EqualTolerance(1, ElectricReactance.FromMegaohms(ohm.Megaohms).Ohms, MegaohmsTolerance); - AssertEx.EqualTolerance(1, ElectricReactance.FromMicroohms(ohm.Microohms).Ohms, MicroohmsTolerance); - AssertEx.EqualTolerance(1, ElectricReactance.FromMilliohms(ohm.Milliohms).Ohms, MilliohmsTolerance); - AssertEx.EqualTolerance(1, ElectricReactance.FromNanoohms(ohm.Nanoohms).Ohms, NanoohmsTolerance); - AssertEx.EqualTolerance(1, ElectricReactance.FromOhms(ohm.Ohms).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(1, ElectricReactance.FromTeraohms(ohm.Teraohms).Ohms, TeraohmsTolerance); + ElectricReactance ohm = ElectricReactance.FromOhms(3); + Assert.Equal(3, ElectricReactance.FromGigaohms(ohm.Gigaohms).Ohms); + Assert.Equal(3, ElectricReactance.FromKiloohms(ohm.Kiloohms).Ohms); + Assert.Equal(3, ElectricReactance.FromMegaohms(ohm.Megaohms).Ohms); + Assert.Equal(3, ElectricReactance.FromMicroohms(ohm.Microohms).Ohms); + Assert.Equal(3, ElectricReactance.FromMilliohms(ohm.Milliohms).Ohms); + Assert.Equal(3, ElectricReactance.FromNanoohms(ohm.Nanoohms).Ohms); + Assert.Equal(3, ElectricReactance.FromOhms(ohm.Ohms).Ohms); + Assert.Equal(3, ElectricReactance.FromTeraohms(ohm.Teraohms).Ohms); } [Fact] public void ArithmeticOperators() { ElectricReactance v = ElectricReactance.FromOhms(1); - AssertEx.EqualTolerance(-1, -v.Ohms, OhmsTolerance); - AssertEx.EqualTolerance(2, (ElectricReactance.FromOhms(3)-v).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(2, (v + v).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(10, (v*10).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(10, (10*v).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(2, (ElectricReactance.FromOhms(10)/5).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(2, ElectricReactance.FromOhms(10)/ElectricReactance.FromOhms(5), OhmsTolerance); + Assert.Equal(-1, -v.Ohms); + Assert.Equal(2, (ElectricReactance.FromOhms(3) - v).Ohms); + Assert.Equal(2, (v + v).Ohms); + Assert.Equal(10, (v * 10).Ohms); + Assert.Equal(10, (10 * v).Ohms); + Assert.Equal(2, (ElectricReactance.FromOhms(10) / 5).Ohms); + Assert.Equal(2, ElectricReactance.FromOhms(10) / ElectricReactance.FromOhms(5)); } [Fact] @@ -639,8 +656,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricReactanceUnit.Ohm, 1, ElectricReactanceUnit.Ohm, true)] // Same value and unit. [InlineData(1, ElectricReactanceUnit.Ohm, 2, ElectricReactanceUnit.Ohm, false)] // Different value. - [InlineData(2, ElectricReactanceUnit.Ohm, 1, ElectricReactanceUnit.Gigaohm, false)] // Different value and unit. - [InlineData(1, ElectricReactanceUnit.Ohm, 1, ElectricReactanceUnit.Gigaohm, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricReactanceUnit unitA, double valueB, ElectricReactanceUnit unitB, bool expectEqual) { var a = new ElectricReactance(valueA, unitA); @@ -700,8 +715,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricReactance.FromOhms(firstValue); var otherQuantity = ElectricReactance.FromOhms(secondValue); ElectricReactance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricReactance.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -720,7 +735,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -733,6 +748,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricReactance.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricReactance.Info.Units, ElectricReactance.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricReactance.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -809,7 +836,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricReactance.FromOhms(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricReactance), quantity.As(ElectricReactance.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactiveEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactiveEnergyTestsBase.g.cs index 5492ac3d4d..fb2dfbad45 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactiveEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactiveEnergyTestsBase.g.cs @@ -133,6 +133,20 @@ public void ElectricReactiveEnergy_QuantityInfo_ReturnsQuantityInfoDescribingQua Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricReactiveEnergyInfo_CreateWithCustomUnitInfos() + { + ElectricReactiveEnergyUnit[] expectedUnits = [ElectricReactiveEnergyUnit.VoltampereReactiveHour]; + + ElectricReactiveEnergy.ElectricReactiveEnergyInfo quantityInfo = ElectricReactiveEnergy.ElectricReactiveEnergyInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricReactiveEnergy", quantityInfo.Name); + Assert.Equal(ElectricReactiveEnergy.Zero, quantityInfo.Zero); + Assert.Equal(ElectricReactiveEnergy.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void VoltampereReactiveHourToElectricReactiveEnergyUnits() { @@ -290,7 +304,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 kvarh", ElectricReactiveEnergyUnit.KilovoltampereReactiveHour, 4.2)] [InlineData("en-US", "4.2 Mvarh", ElectricReactiveEnergyUnit.MegavoltampereReactiveHour, 4.2)] [InlineData("en-US", "4.2 varh", ElectricReactiveEnergyUnit.VoltampereReactiveHour, 4.2)] - public void Parse(string culture, string quantityString, ElectricReactiveEnergyUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricReactiveEnergyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricReactiveEnergy.Parse(quantityString); @@ -302,7 +316,7 @@ public void Parse(string culture, string quantityString, ElectricReactiveEnergyU [InlineData("en-US", "4.2 kvarh", ElectricReactiveEnergyUnit.KilovoltampereReactiveHour, 4.2)] [InlineData("en-US", "4.2 Mvarh", ElectricReactiveEnergyUnit.MegavoltampereReactiveHour, 4.2)] [InlineData("en-US", "4.2 varh", ElectricReactiveEnergyUnit.VoltampereReactiveHour, 4.2)] - public void TryParse(string culture, string quantityString, ElectricReactiveEnergyUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricReactiveEnergyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricReactiveEnergy.TryParse(quantityString, out ElectricReactiveEnergy parsed)); @@ -453,6 +467,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricReactive var quantity = ElectricReactiveEnergy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -476,34 +491,36 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricReactiveEne IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricReactiveEnergy voltamperereactivehour = ElectricReactiveEnergy.FromVoltampereReactiveHours(1); - AssertEx.EqualTolerance(1, ElectricReactiveEnergy.FromKilovoltampereReactiveHours(voltamperereactivehour.KilovoltampereReactiveHours).VoltampereReactiveHours, KilovoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(1, ElectricReactiveEnergy.FromMegavoltampereReactiveHours(voltamperereactivehour.MegavoltampereReactiveHours).VoltampereReactiveHours, MegavoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(1, ElectricReactiveEnergy.FromVoltampereReactiveHours(voltamperereactivehour.VoltampereReactiveHours).VoltampereReactiveHours, VoltampereReactiveHoursTolerance); + ElectricReactiveEnergy voltamperereactivehour = ElectricReactiveEnergy.FromVoltampereReactiveHours(3); + Assert.Equal(3, ElectricReactiveEnergy.FromKilovoltampereReactiveHours(voltamperereactivehour.KilovoltampereReactiveHours).VoltampereReactiveHours); + Assert.Equal(3, ElectricReactiveEnergy.FromMegavoltampereReactiveHours(voltamperereactivehour.MegavoltampereReactiveHours).VoltampereReactiveHours); + Assert.Equal(3, ElectricReactiveEnergy.FromVoltampereReactiveHours(voltamperereactivehour.VoltampereReactiveHours).VoltampereReactiveHours); } [Fact] public void ArithmeticOperators() { ElectricReactiveEnergy v = ElectricReactiveEnergy.FromVoltampereReactiveHours(1); - AssertEx.EqualTolerance(-1, -v.VoltampereReactiveHours, VoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(2, (ElectricReactiveEnergy.FromVoltampereReactiveHours(3)-v).VoltampereReactiveHours, VoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(2, (v + v).VoltampereReactiveHours, VoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(10, (v*10).VoltampereReactiveHours, VoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(10, (10*v).VoltampereReactiveHours, VoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(2, (ElectricReactiveEnergy.FromVoltampereReactiveHours(10)/5).VoltampereReactiveHours, VoltampereReactiveHoursTolerance); - AssertEx.EqualTolerance(2, ElectricReactiveEnergy.FromVoltampereReactiveHours(10)/ElectricReactiveEnergy.FromVoltampereReactiveHours(5), VoltampereReactiveHoursTolerance); + Assert.Equal(-1, -v.VoltampereReactiveHours); + Assert.Equal(2, (ElectricReactiveEnergy.FromVoltampereReactiveHours(3) - v).VoltampereReactiveHours); + Assert.Equal(2, (v + v).VoltampereReactiveHours); + Assert.Equal(10, (v * 10).VoltampereReactiveHours); + Assert.Equal(10, (10 * v).VoltampereReactiveHours); + Assert.Equal(2, (ElectricReactiveEnergy.FromVoltampereReactiveHours(10) / 5).VoltampereReactiveHours); + Assert.Equal(2, ElectricReactiveEnergy.FromVoltampereReactiveHours(10) / ElectricReactiveEnergy.FromVoltampereReactiveHours(5)); } [Fact] @@ -549,8 +566,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricReactiveEnergyUnit.VoltampereReactiveHour, 1, ElectricReactiveEnergyUnit.VoltampereReactiveHour, true)] // Same value and unit. [InlineData(1, ElectricReactiveEnergyUnit.VoltampereReactiveHour, 2, ElectricReactiveEnergyUnit.VoltampereReactiveHour, false)] // Different value. - [InlineData(2, ElectricReactiveEnergyUnit.VoltampereReactiveHour, 1, ElectricReactiveEnergyUnit.KilovoltampereReactiveHour, false)] // Different value and unit. - [InlineData(1, ElectricReactiveEnergyUnit.VoltampereReactiveHour, 1, ElectricReactiveEnergyUnit.KilovoltampereReactiveHour, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricReactiveEnergyUnit unitA, double valueB, ElectricReactiveEnergyUnit unitB, bool expectEqual) { var a = new ElectricReactiveEnergy(valueA, unitA); @@ -610,8 +625,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(firstValue); var otherQuantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(secondValue); ElectricReactiveEnergy maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricReactiveEnergy.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -630,7 +645,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -643,6 +658,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricReactiveEnergy.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricReactiveEnergy.Info.Units, ElectricReactiveEnergy.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricReactiveEnergy.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -709,7 +736,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricReactiveEnergy.FromVoltampereReactiveHours(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricReactiveEnergy), quantity.As(ElectricReactiveEnergy.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactivePowerTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactivePowerTestsBase.g.cs index 53fb2f0c3b..c16985590d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactivePowerTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricReactivePowerTestsBase.g.cs @@ -137,6 +137,20 @@ public void ElectricReactivePower_QuantityInfo_ReturnsQuantityInfoDescribingQuan Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricReactivePowerInfo_CreateWithCustomUnitInfos() + { + ElectricReactivePowerUnit[] expectedUnits = [ElectricReactivePowerUnit.VoltampereReactive]; + + ElectricReactivePower.ElectricReactivePowerInfo quantityInfo = ElectricReactivePower.ElectricReactivePowerInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricReactivePower", quantityInfo.Name); + Assert.Equal(ElectricReactivePower.Zero, quantityInfo.Zero); + Assert.Equal(ElectricReactivePower.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void VoltampereReactiveToElectricReactivePowerUnits() { @@ -297,7 +311,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 kvar", ElectricReactivePowerUnit.KilovoltampereReactive, 4.2)] [InlineData("en-US", "4.2 Mvar", ElectricReactivePowerUnit.MegavoltampereReactive, 4.2)] [InlineData("en-US", "4.2 var", ElectricReactivePowerUnit.VoltampereReactive, 4.2)] - public void Parse(string culture, string quantityString, ElectricReactivePowerUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricReactivePowerUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricReactivePower.Parse(quantityString); @@ -310,7 +324,7 @@ public void Parse(string culture, string quantityString, ElectricReactivePowerUn [InlineData("en-US", "4.2 kvar", ElectricReactivePowerUnit.KilovoltampereReactive, 4.2)] [InlineData("en-US", "4.2 Mvar", ElectricReactivePowerUnit.MegavoltampereReactive, 4.2)] [InlineData("en-US", "4.2 var", ElectricReactivePowerUnit.VoltampereReactive, 4.2)] - public void TryParse(string culture, string quantityString, ElectricReactivePowerUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricReactivePowerUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricReactivePower.TryParse(quantityString, out ElectricReactivePower parsed)); @@ -470,6 +484,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricReactive var quantity = ElectricReactivePower.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -493,35 +508,37 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricReactivePow IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricReactivePower voltamperereactive = ElectricReactivePower.FromVoltamperesReactive(1); - AssertEx.EqualTolerance(1, ElectricReactivePower.FromGigavoltamperesReactive(voltamperereactive.GigavoltamperesReactive).VoltamperesReactive, GigavoltamperesReactiveTolerance); - AssertEx.EqualTolerance(1, ElectricReactivePower.FromKilovoltamperesReactive(voltamperereactive.KilovoltamperesReactive).VoltamperesReactive, KilovoltamperesReactiveTolerance); - AssertEx.EqualTolerance(1, ElectricReactivePower.FromMegavoltamperesReactive(voltamperereactive.MegavoltamperesReactive).VoltamperesReactive, MegavoltamperesReactiveTolerance); - AssertEx.EqualTolerance(1, ElectricReactivePower.FromVoltamperesReactive(voltamperereactive.VoltamperesReactive).VoltamperesReactive, VoltamperesReactiveTolerance); + ElectricReactivePower voltamperereactive = ElectricReactivePower.FromVoltamperesReactive(3); + Assert.Equal(3, ElectricReactivePower.FromGigavoltamperesReactive(voltamperereactive.GigavoltamperesReactive).VoltamperesReactive); + Assert.Equal(3, ElectricReactivePower.FromKilovoltamperesReactive(voltamperereactive.KilovoltamperesReactive).VoltamperesReactive); + Assert.Equal(3, ElectricReactivePower.FromMegavoltamperesReactive(voltamperereactive.MegavoltamperesReactive).VoltamperesReactive); + Assert.Equal(3, ElectricReactivePower.FromVoltamperesReactive(voltamperereactive.VoltamperesReactive).VoltamperesReactive); } [Fact] public void ArithmeticOperators() { ElectricReactivePower v = ElectricReactivePower.FromVoltamperesReactive(1); - AssertEx.EqualTolerance(-1, -v.VoltamperesReactive, VoltamperesReactiveTolerance); - AssertEx.EqualTolerance(2, (ElectricReactivePower.FromVoltamperesReactive(3)-v).VoltamperesReactive, VoltamperesReactiveTolerance); - AssertEx.EqualTolerance(2, (v + v).VoltamperesReactive, VoltamperesReactiveTolerance); - AssertEx.EqualTolerance(10, (v*10).VoltamperesReactive, VoltamperesReactiveTolerance); - AssertEx.EqualTolerance(10, (10*v).VoltamperesReactive, VoltamperesReactiveTolerance); - AssertEx.EqualTolerance(2, (ElectricReactivePower.FromVoltamperesReactive(10)/5).VoltamperesReactive, VoltamperesReactiveTolerance); - AssertEx.EqualTolerance(2, ElectricReactivePower.FromVoltamperesReactive(10)/ElectricReactivePower.FromVoltamperesReactive(5), VoltamperesReactiveTolerance); + Assert.Equal(-1, -v.VoltamperesReactive); + Assert.Equal(2, (ElectricReactivePower.FromVoltamperesReactive(3) - v).VoltamperesReactive); + Assert.Equal(2, (v + v).VoltamperesReactive); + Assert.Equal(10, (v * 10).VoltamperesReactive); + Assert.Equal(10, (10 * v).VoltamperesReactive); + Assert.Equal(2, (ElectricReactivePower.FromVoltamperesReactive(10) / 5).VoltamperesReactive); + Assert.Equal(2, ElectricReactivePower.FromVoltamperesReactive(10) / ElectricReactivePower.FromVoltamperesReactive(5)); } [Fact] @@ -567,8 +584,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricReactivePowerUnit.VoltampereReactive, 1, ElectricReactivePowerUnit.VoltampereReactive, true)] // Same value and unit. [InlineData(1, ElectricReactivePowerUnit.VoltampereReactive, 2, ElectricReactivePowerUnit.VoltampereReactive, false)] // Different value. - [InlineData(2, ElectricReactivePowerUnit.VoltampereReactive, 1, ElectricReactivePowerUnit.GigavoltampereReactive, false)] // Different value and unit. - [InlineData(1, ElectricReactivePowerUnit.VoltampereReactive, 1, ElectricReactivePowerUnit.GigavoltampereReactive, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricReactivePowerUnit unitA, double valueB, ElectricReactivePowerUnit unitB, bool expectEqual) { var a = new ElectricReactivePower(valueA, unitA); @@ -628,8 +643,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricReactivePower.FromVoltamperesReactive(firstValue); var otherQuantity = ElectricReactivePower.FromVoltamperesReactive(secondValue); ElectricReactivePower maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricReactivePower.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -648,7 +663,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -661,6 +676,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricReactivePower.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricReactivePower.Info.Units, ElectricReactivePower.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricReactivePower.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -729,7 +756,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricReactivePower.FromVoltamperesReactive(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricReactivePower), quantity.As(ElectricReactivePower.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs index c3b231005b..eab4ad140f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistanceTestsBase.g.cs @@ -153,6 +153,20 @@ public void ElectricResistance_QuantityInfo_ReturnsQuantityInfoDescribingQuantit Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricResistanceInfo_CreateWithCustomUnitInfos() + { + ElectricResistanceUnit[] expectedUnits = [ElectricResistanceUnit.Ohm]; + + ElectricResistance.ElectricResistanceInfo quantityInfo = ElectricResistance.ElectricResistanceInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricResistance", quantityInfo.Name); + Assert.Equal(ElectricResistance.Zero, quantityInfo.Zero); + Assert.Equal(ElectricResistance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void OhmToElectricResistanceUnits() { @@ -325,7 +339,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 nΩ", ElectricResistanceUnit.Nanoohm, 4.2)] [InlineData("en-US", "4.2 Ω", ElectricResistanceUnit.Ohm, 4.2)] [InlineData("en-US", "4.2 TΩ", ElectricResistanceUnit.Teraohm, 4.2)] - public void Parse(string culture, string quantityString, ElectricResistanceUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricResistanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricResistance.Parse(quantityString); @@ -342,7 +356,7 @@ public void Parse(string culture, string quantityString, ElectricResistanceUnit [InlineData("en-US", "4.2 nΩ", ElectricResistanceUnit.Nanoohm, 4.2)] [InlineData("en-US", "4.2 Ω", ElectricResistanceUnit.Ohm, 4.2)] [InlineData("en-US", "4.2 TΩ", ElectricResistanceUnit.Teraohm, 4.2)] - public void TryParse(string culture, string quantityString, ElectricResistanceUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricResistanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricResistance.TryParse(quantityString, out ElectricResistance parsed)); @@ -538,6 +552,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricResistan var quantity = ElectricResistance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -561,39 +576,41 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricResistanceU IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricResistance ohm = ElectricResistance.FromOhms(1); - AssertEx.EqualTolerance(1, ElectricResistance.FromGigaohms(ohm.Gigaohms).Ohms, GigaohmsTolerance); - AssertEx.EqualTolerance(1, ElectricResistance.FromKiloohms(ohm.Kiloohms).Ohms, KiloohmsTolerance); - AssertEx.EqualTolerance(1, ElectricResistance.FromMegaohms(ohm.Megaohms).Ohms, MegaohmsTolerance); - AssertEx.EqualTolerance(1, ElectricResistance.FromMicroohms(ohm.Microohms).Ohms, MicroohmsTolerance); - AssertEx.EqualTolerance(1, ElectricResistance.FromMilliohms(ohm.Milliohms).Ohms, MilliohmsTolerance); - AssertEx.EqualTolerance(1, ElectricResistance.FromNanoohms(ohm.Nanoohms).Ohms, NanoohmsTolerance); - AssertEx.EqualTolerance(1, ElectricResistance.FromOhms(ohm.Ohms).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(1, ElectricResistance.FromTeraohms(ohm.Teraohms).Ohms, TeraohmsTolerance); + ElectricResistance ohm = ElectricResistance.FromOhms(3); + Assert.Equal(3, ElectricResistance.FromGigaohms(ohm.Gigaohms).Ohms); + Assert.Equal(3, ElectricResistance.FromKiloohms(ohm.Kiloohms).Ohms); + Assert.Equal(3, ElectricResistance.FromMegaohms(ohm.Megaohms).Ohms); + Assert.Equal(3, ElectricResistance.FromMicroohms(ohm.Microohms).Ohms); + Assert.Equal(3, ElectricResistance.FromMilliohms(ohm.Milliohms).Ohms); + Assert.Equal(3, ElectricResistance.FromNanoohms(ohm.Nanoohms).Ohms); + Assert.Equal(3, ElectricResistance.FromOhms(ohm.Ohms).Ohms); + Assert.Equal(3, ElectricResistance.FromTeraohms(ohm.Teraohms).Ohms); } [Fact] public void ArithmeticOperators() { ElectricResistance v = ElectricResistance.FromOhms(1); - AssertEx.EqualTolerance(-1, -v.Ohms, OhmsTolerance); - AssertEx.EqualTolerance(2, (ElectricResistance.FromOhms(3)-v).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(2, (v + v).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(10, (v*10).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(10, (10*v).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(2, (ElectricResistance.FromOhms(10)/5).Ohms, OhmsTolerance); - AssertEx.EqualTolerance(2, ElectricResistance.FromOhms(10)/ElectricResistance.FromOhms(5), OhmsTolerance); + Assert.Equal(-1, -v.Ohms); + Assert.Equal(2, (ElectricResistance.FromOhms(3) - v).Ohms); + Assert.Equal(2, (v + v).Ohms); + Assert.Equal(10, (v * 10).Ohms); + Assert.Equal(10, (10 * v).Ohms); + Assert.Equal(2, (ElectricResistance.FromOhms(10) / 5).Ohms); + Assert.Equal(2, ElectricResistance.FromOhms(10) / ElectricResistance.FromOhms(5)); } [Fact] @@ -639,8 +656,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricResistanceUnit.Ohm, 1, ElectricResistanceUnit.Ohm, true)] // Same value and unit. [InlineData(1, ElectricResistanceUnit.Ohm, 2, ElectricResistanceUnit.Ohm, false)] // Different value. - [InlineData(2, ElectricResistanceUnit.Ohm, 1, ElectricResistanceUnit.Gigaohm, false)] // Different value and unit. - [InlineData(1, ElectricResistanceUnit.Ohm, 1, ElectricResistanceUnit.Gigaohm, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricResistanceUnit unitA, double valueB, ElectricResistanceUnit unitB, bool expectEqual) { var a = new ElectricResistance(valueA, unitA); @@ -700,8 +715,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricResistance.FromOhms(firstValue); var otherQuantity = ElectricResistance.FromOhms(secondValue); ElectricResistance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricResistance.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -720,7 +735,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -733,6 +748,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricResistance.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricResistance.Info.Units, ElectricResistance.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricResistance.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -809,7 +836,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricResistance.FromOhms(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricResistance), quantity.As(ElectricResistance.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs index 06b830d917..e1ba48eb00 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricResistivityTestsBase.g.cs @@ -177,6 +177,20 @@ public void ElectricResistivity_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricResistivityInfo_CreateWithCustomUnitInfos() + { + ElectricResistivityUnit[] expectedUnits = [ElectricResistivityUnit.OhmMeter]; + + ElectricResistivity.ElectricResistivityInfo quantityInfo = ElectricResistivity.ElectricResistivityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricResistivity", quantityInfo.Name); + Assert.Equal(ElectricResistivity.Zero, quantityInfo.Zero); + Assert.Equal(ElectricResistivity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void OhmMeterToElectricResistivityUnits() { @@ -367,7 +381,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 Ω·m", ElectricResistivityUnit.OhmMeter, 4.2)] [InlineData("en-US", "4.2 pΩ·cm", ElectricResistivityUnit.PicoohmCentimeter, 4.2)] [InlineData("en-US", "4.2 pΩ·m", ElectricResistivityUnit.PicoohmMeter, 4.2)] - public void Parse(string culture, string quantityString, ElectricResistivityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricResistivityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricResistivity.Parse(quantityString); @@ -390,7 +404,7 @@ public void Parse(string culture, string quantityString, ElectricResistivityUnit [InlineData("en-US", "4.2 Ω·m", ElectricResistivityUnit.OhmMeter, 4.2)] [InlineData("en-US", "4.2 pΩ·cm", ElectricResistivityUnit.PicoohmCentimeter, 4.2)] [InlineData("en-US", "4.2 pΩ·m", ElectricResistivityUnit.PicoohmMeter, 4.2)] - public void TryParse(string culture, string quantityString, ElectricResistivityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricResistivityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricResistivity.TryParse(quantityString, out ElectricResistivity parsed)); @@ -640,6 +654,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricResistiv var quantity = ElectricResistivity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -663,45 +678,47 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricResistivity IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricResistivity ohmmeter = ElectricResistivity.FromOhmMeters(1); - AssertEx.EqualTolerance(1, ElectricResistivity.FromKiloohmsCentimeter(ohmmeter.KiloohmsCentimeter).OhmMeters, KiloohmsCentimeterTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.FromKiloohmMeters(ohmmeter.KiloohmMeters).OhmMeters, KiloohmMetersTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.FromMegaohmsCentimeter(ohmmeter.MegaohmsCentimeter).OhmMeters, MegaohmsCentimeterTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.FromMegaohmMeters(ohmmeter.MegaohmMeters).OhmMeters, MegaohmMetersTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.FromMicroohmsCentimeter(ohmmeter.MicroohmsCentimeter).OhmMeters, MicroohmsCentimeterTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.FromMicroohmMeters(ohmmeter.MicroohmMeters).OhmMeters, MicroohmMetersTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.FromMilliohmsCentimeter(ohmmeter.MilliohmsCentimeter).OhmMeters, MilliohmsCentimeterTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.FromMilliohmMeters(ohmmeter.MilliohmMeters).OhmMeters, MilliohmMetersTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.FromNanoohmsCentimeter(ohmmeter.NanoohmsCentimeter).OhmMeters, NanoohmsCentimeterTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.FromNanoohmMeters(ohmmeter.NanoohmMeters).OhmMeters, NanoohmMetersTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.FromOhmsCentimeter(ohmmeter.OhmsCentimeter).OhmMeters, OhmsCentimeterTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.FromOhmMeters(ohmmeter.OhmMeters).OhmMeters, OhmMetersTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.FromPicoohmsCentimeter(ohmmeter.PicoohmsCentimeter).OhmMeters, PicoohmsCentimeterTolerance); - AssertEx.EqualTolerance(1, ElectricResistivity.FromPicoohmMeters(ohmmeter.PicoohmMeters).OhmMeters, PicoohmMetersTolerance); + ElectricResistivity ohmmeter = ElectricResistivity.FromOhmMeters(3); + Assert.Equal(3, ElectricResistivity.FromKiloohmsCentimeter(ohmmeter.KiloohmsCentimeter).OhmMeters); + Assert.Equal(3, ElectricResistivity.FromKiloohmMeters(ohmmeter.KiloohmMeters).OhmMeters); + Assert.Equal(3, ElectricResistivity.FromMegaohmsCentimeter(ohmmeter.MegaohmsCentimeter).OhmMeters); + Assert.Equal(3, ElectricResistivity.FromMegaohmMeters(ohmmeter.MegaohmMeters).OhmMeters); + Assert.Equal(3, ElectricResistivity.FromMicroohmsCentimeter(ohmmeter.MicroohmsCentimeter).OhmMeters); + Assert.Equal(3, ElectricResistivity.FromMicroohmMeters(ohmmeter.MicroohmMeters).OhmMeters); + Assert.Equal(3, ElectricResistivity.FromMilliohmsCentimeter(ohmmeter.MilliohmsCentimeter).OhmMeters); + Assert.Equal(3, ElectricResistivity.FromMilliohmMeters(ohmmeter.MilliohmMeters).OhmMeters); + Assert.Equal(3, ElectricResistivity.FromNanoohmsCentimeter(ohmmeter.NanoohmsCentimeter).OhmMeters); + Assert.Equal(3, ElectricResistivity.FromNanoohmMeters(ohmmeter.NanoohmMeters).OhmMeters); + Assert.Equal(3, ElectricResistivity.FromOhmsCentimeter(ohmmeter.OhmsCentimeter).OhmMeters); + Assert.Equal(3, ElectricResistivity.FromOhmMeters(ohmmeter.OhmMeters).OhmMeters); + Assert.Equal(3, ElectricResistivity.FromPicoohmsCentimeter(ohmmeter.PicoohmsCentimeter).OhmMeters); + Assert.Equal(3, ElectricResistivity.FromPicoohmMeters(ohmmeter.PicoohmMeters).OhmMeters); } [Fact] public void ArithmeticOperators() { ElectricResistivity v = ElectricResistivity.FromOhmMeters(1); - AssertEx.EqualTolerance(-1, -v.OhmMeters, OhmMetersTolerance); - AssertEx.EqualTolerance(2, (ElectricResistivity.FromOhmMeters(3)-v).OhmMeters, OhmMetersTolerance); - AssertEx.EqualTolerance(2, (v + v).OhmMeters, OhmMetersTolerance); - AssertEx.EqualTolerance(10, (v*10).OhmMeters, OhmMetersTolerance); - AssertEx.EqualTolerance(10, (10*v).OhmMeters, OhmMetersTolerance); - AssertEx.EqualTolerance(2, (ElectricResistivity.FromOhmMeters(10)/5).OhmMeters, OhmMetersTolerance); - AssertEx.EqualTolerance(2, ElectricResistivity.FromOhmMeters(10)/ElectricResistivity.FromOhmMeters(5), OhmMetersTolerance); + Assert.Equal(-1, -v.OhmMeters); + Assert.Equal(2, (ElectricResistivity.FromOhmMeters(3) - v).OhmMeters); + Assert.Equal(2, (v + v).OhmMeters); + Assert.Equal(10, (v * 10).OhmMeters); + Assert.Equal(10, (10 * v).OhmMeters); + Assert.Equal(2, (ElectricResistivity.FromOhmMeters(10) / 5).OhmMeters); + Assert.Equal(2, ElectricResistivity.FromOhmMeters(10) / ElectricResistivity.FromOhmMeters(5)); } [Fact] @@ -747,8 +764,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricResistivityUnit.OhmMeter, 1, ElectricResistivityUnit.OhmMeter, true)] // Same value and unit. [InlineData(1, ElectricResistivityUnit.OhmMeter, 2, ElectricResistivityUnit.OhmMeter, false)] // Different value. - [InlineData(2, ElectricResistivityUnit.OhmMeter, 1, ElectricResistivityUnit.KiloohmCentimeter, false)] // Different value and unit. - [InlineData(1, ElectricResistivityUnit.OhmMeter, 1, ElectricResistivityUnit.KiloohmCentimeter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricResistivityUnit unitA, double valueB, ElectricResistivityUnit unitB, bool expectEqual) { var a = new ElectricResistivity(valueA, unitA); @@ -808,8 +823,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricResistivity.FromOhmMeters(firstValue); var otherQuantity = ElectricResistivity.FromOhmMeters(secondValue); ElectricResistivity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricResistivity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -828,7 +843,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -841,6 +856,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricResistivity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricResistivity.Info.Units, ElectricResistivity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricResistivity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -929,7 +956,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricResistivity.FromOhmMeters(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricResistivity), quantity.As(ElectricResistivity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs index b46171b986..4e5b23d371 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSurfaceChargeDensityTestsBase.g.cs @@ -133,6 +133,20 @@ public void ElectricSurfaceChargeDensity_QuantityInfo_ReturnsQuantityInfoDescrib Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricSurfaceChargeDensityInfo_CreateWithCustomUnitInfos() + { + ElectricSurfaceChargeDensityUnit[] expectedUnits = [ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter]; + + ElectricSurfaceChargeDensity.ElectricSurfaceChargeDensityInfo quantityInfo = ElectricSurfaceChargeDensity.ElectricSurfaceChargeDensityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricSurfaceChargeDensity", quantityInfo.Name); + Assert.Equal(ElectricSurfaceChargeDensity.Zero, quantityInfo.Zero); + Assert.Equal(ElectricSurfaceChargeDensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void CoulombPerSquareMeterToElectricSurfaceChargeDensityUnits() { @@ -290,7 +304,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 C/cm²", ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, 4.2)] [InlineData("en-US", "4.2 C/in²", ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, 4.2)] [InlineData("en-US", "4.2 C/m²", ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, 4.2)] - public void Parse(string culture, string quantityString, ElectricSurfaceChargeDensityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricSurfaceChargeDensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricSurfaceChargeDensity.Parse(quantityString); @@ -302,7 +316,7 @@ public void Parse(string culture, string quantityString, ElectricSurfaceChargeDe [InlineData("en-US", "4.2 C/cm²", ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, 4.2)] [InlineData("en-US", "4.2 C/in²", ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, 4.2)] [InlineData("en-US", "4.2 C/m²", ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, 4.2)] - public void TryParse(string culture, string quantityString, ElectricSurfaceChargeDensityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricSurfaceChargeDensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricSurfaceChargeDensity.TryParse(quantityString, out ElectricSurfaceChargeDensity parsed)); @@ -453,6 +467,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricSurfaceC var quantity = ElectricSurfaceChargeDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -476,34 +491,36 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricSurfaceChar IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricSurfaceChargeDensity coulombpersquaremeter = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1); - AssertEx.EqualTolerance(1, ElectricSurfaceChargeDensity.FromCoulombsPerSquareCentimeter(coulombpersquaremeter.CoulombsPerSquareCentimeter).CoulombsPerSquareMeter, CoulombsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, ElectricSurfaceChargeDensity.FromCoulombsPerSquareInch(coulombpersquaremeter.CoulombsPerSquareInch).CoulombsPerSquareMeter, CoulombsPerSquareInchTolerance); - AssertEx.EqualTolerance(1, ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(coulombpersquaremeter.CoulombsPerSquareMeter).CoulombsPerSquareMeter, CoulombsPerSquareMeterTolerance); + ElectricSurfaceChargeDensity coulombpersquaremeter = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(3); + Assert.Equal(3, ElectricSurfaceChargeDensity.FromCoulombsPerSquareCentimeter(coulombpersquaremeter.CoulombsPerSquareCentimeter).CoulombsPerSquareMeter); + Assert.Equal(3, ElectricSurfaceChargeDensity.FromCoulombsPerSquareInch(coulombpersquaremeter.CoulombsPerSquareInch).CoulombsPerSquareMeter); + Assert.Equal(3, ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(coulombpersquaremeter.CoulombsPerSquareMeter).CoulombsPerSquareMeter); } [Fact] public void ArithmeticOperators() { ElectricSurfaceChargeDensity v = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1); - AssertEx.EqualTolerance(-1, -v.CoulombsPerSquareMeter, CoulombsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(3)-v).CoulombsPerSquareMeter, CoulombsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).CoulombsPerSquareMeter, CoulombsPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).CoulombsPerSquareMeter, CoulombsPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).CoulombsPerSquareMeter, CoulombsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(10)/5).CoulombsPerSquareMeter, CoulombsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(10)/ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(5), CoulombsPerSquareMeterTolerance); + Assert.Equal(-1, -v.CoulombsPerSquareMeter); + Assert.Equal(2, (ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(3) - v).CoulombsPerSquareMeter); + Assert.Equal(2, (v + v).CoulombsPerSquareMeter); + Assert.Equal(10, (v * 10).CoulombsPerSquareMeter); + Assert.Equal(10, (10 * v).CoulombsPerSquareMeter); + Assert.Equal(2, (ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(10) / 5).CoulombsPerSquareMeter); + Assert.Equal(2, ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(10) / ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(5)); } [Fact] @@ -549,8 +566,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, 1, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, true)] // Same value and unit. [InlineData(1, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, 2, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, false)] // Different value. - [InlineData(2, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, 1, ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, false)] // Different value and unit. - [InlineData(1, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, 1, ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricSurfaceChargeDensityUnit unitA, double valueB, ElectricSurfaceChargeDensityUnit unitB, bool expectEqual) { var a = new ElectricSurfaceChargeDensity(valueA, unitA); @@ -610,8 +625,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(firstValue); var otherQuantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(secondValue); ElectricSurfaceChargeDensity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricSurfaceChargeDensity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -630,7 +645,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -643,6 +658,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricSurfaceChargeDensity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricSurfaceChargeDensity.Info.Units, ElectricSurfaceChargeDensity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricSurfaceChargeDensity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -709,7 +736,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricSurfaceChargeDensity.FromCoulombsPerSquareMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricSurfaceChargeDensity), quantity.As(ElectricSurfaceChargeDensity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSusceptanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSusceptanceTestsBase.g.cs index c5cb0afe1c..c9ecd70d55 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSusceptanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ElectricSusceptanceTestsBase.g.cs @@ -185,6 +185,20 @@ public void ElectricSusceptance_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ElectricSusceptanceInfo_CreateWithCustomUnitInfos() + { + ElectricSusceptanceUnit[] expectedUnits = [ElectricSusceptanceUnit.Siemens]; + + ElectricSusceptance.ElectricSusceptanceInfo quantityInfo = ElectricSusceptance.ElectricSusceptanceInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ElectricSusceptance", quantityInfo.Name); + Assert.Equal(ElectricSusceptance.Zero, quantityInfo.Zero); + Assert.Equal(ElectricSusceptance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void SiemensToElectricSusceptanceUnits() { @@ -381,7 +395,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 S", ElectricSusceptanceUnit.Siemens, 4.2)] [InlineData("en-US", "4.2 T℧", ElectricSusceptanceUnit.Teramho, 4.2)] [InlineData("en-US", "4.2 TS", ElectricSusceptanceUnit.Terasiemens, 4.2)] - public void Parse(string culture, string quantityString, ElectricSusceptanceUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ElectricSusceptanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ElectricSusceptance.Parse(quantityString); @@ -406,7 +420,7 @@ public void Parse(string culture, string quantityString, ElectricSusceptanceUnit [InlineData("en-US", "4.2 S", ElectricSusceptanceUnit.Siemens, 4.2)] [InlineData("en-US", "4.2 T℧", ElectricSusceptanceUnit.Teramho, 4.2)] [InlineData("en-US", "4.2 TS", ElectricSusceptanceUnit.Terasiemens, 4.2)] - public void TryParse(string culture, string quantityString, ElectricSusceptanceUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ElectricSusceptanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ElectricSusceptance.TryParse(quantityString, out ElectricSusceptance parsed)); @@ -674,6 +688,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ElectricSuscepta var quantity = ElectricSusceptance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -697,47 +712,49 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ElectricSusceptance IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ElectricSusceptance siemens = ElectricSusceptance.FromSiemens(1); - AssertEx.EqualTolerance(1, ElectricSusceptance.FromGigamhos(siemens.Gigamhos).Siemens, GigamhosTolerance); - AssertEx.EqualTolerance(1, ElectricSusceptance.FromGigasiemens(siemens.Gigasiemens).Siemens, GigasiemensTolerance); - AssertEx.EqualTolerance(1, ElectricSusceptance.FromKilomhos(siemens.Kilomhos).Siemens, KilomhosTolerance); - AssertEx.EqualTolerance(1, ElectricSusceptance.FromKilosiemens(siemens.Kilosiemens).Siemens, KilosiemensTolerance); - AssertEx.EqualTolerance(1, ElectricSusceptance.FromMegamhos(siemens.Megamhos).Siemens, MegamhosTolerance); - AssertEx.EqualTolerance(1, ElectricSusceptance.FromMegasiemens(siemens.Megasiemens).Siemens, MegasiemensTolerance); - AssertEx.EqualTolerance(1, ElectricSusceptance.FromMhos(siemens.Mhos).Siemens, MhosTolerance); - AssertEx.EqualTolerance(1, ElectricSusceptance.FromMicromhos(siemens.Micromhos).Siemens, MicromhosTolerance); - AssertEx.EqualTolerance(1, ElectricSusceptance.FromMicrosiemens(siemens.Microsiemens).Siemens, MicrosiemensTolerance); - AssertEx.EqualTolerance(1, ElectricSusceptance.FromMillimhos(siemens.Millimhos).Siemens, MillimhosTolerance); - AssertEx.EqualTolerance(1, ElectricSusceptance.FromMillisiemens(siemens.Millisiemens).Siemens, MillisiemensTolerance); - AssertEx.EqualTolerance(1, ElectricSusceptance.FromNanomhos(siemens.Nanomhos).Siemens, NanomhosTolerance); - AssertEx.EqualTolerance(1, ElectricSusceptance.FromNanosiemens(siemens.Nanosiemens).Siemens, NanosiemensTolerance); - AssertEx.EqualTolerance(1, ElectricSusceptance.FromSiemens(siemens.Siemens).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(1, ElectricSusceptance.FromTeramhos(siemens.Teramhos).Siemens, TeramhosTolerance); - AssertEx.EqualTolerance(1, ElectricSusceptance.FromTerasiemens(siemens.Terasiemens).Siemens, TerasiemensTolerance); + ElectricSusceptance siemens = ElectricSusceptance.FromSiemens(3); + Assert.Equal(3, ElectricSusceptance.FromGigamhos(siemens.Gigamhos).Siemens); + Assert.Equal(3, ElectricSusceptance.FromGigasiemens(siemens.Gigasiemens).Siemens); + Assert.Equal(3, ElectricSusceptance.FromKilomhos(siemens.Kilomhos).Siemens); + Assert.Equal(3, ElectricSusceptance.FromKilosiemens(siemens.Kilosiemens).Siemens); + Assert.Equal(3, ElectricSusceptance.FromMegamhos(siemens.Megamhos).Siemens); + Assert.Equal(3, ElectricSusceptance.FromMegasiemens(siemens.Megasiemens).Siemens); + Assert.Equal(3, ElectricSusceptance.FromMhos(siemens.Mhos).Siemens); + Assert.Equal(3, ElectricSusceptance.FromMicromhos(siemens.Micromhos).Siemens); + Assert.Equal(3, ElectricSusceptance.FromMicrosiemens(siemens.Microsiemens).Siemens); + Assert.Equal(3, ElectricSusceptance.FromMillimhos(siemens.Millimhos).Siemens); + Assert.Equal(3, ElectricSusceptance.FromMillisiemens(siemens.Millisiemens).Siemens); + Assert.Equal(3, ElectricSusceptance.FromNanomhos(siemens.Nanomhos).Siemens); + Assert.Equal(3, ElectricSusceptance.FromNanosiemens(siemens.Nanosiemens).Siemens); + Assert.Equal(3, ElectricSusceptance.FromSiemens(siemens.Siemens).Siemens); + Assert.Equal(3, ElectricSusceptance.FromTeramhos(siemens.Teramhos).Siemens); + Assert.Equal(3, ElectricSusceptance.FromTerasiemens(siemens.Terasiemens).Siemens); } [Fact] public void ArithmeticOperators() { ElectricSusceptance v = ElectricSusceptance.FromSiemens(1); - AssertEx.EqualTolerance(-1, -v.Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, (ElectricSusceptance.FromSiemens(3)-v).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, (v + v).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(10, (v*10).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(10, (10*v).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, (ElectricSusceptance.FromSiemens(10)/5).Siemens, SiemensTolerance); - AssertEx.EqualTolerance(2, ElectricSusceptance.FromSiemens(10)/ElectricSusceptance.FromSiemens(5), SiemensTolerance); + Assert.Equal(-1, -v.Siemens); + Assert.Equal(2, (ElectricSusceptance.FromSiemens(3) - v).Siemens); + Assert.Equal(2, (v + v).Siemens); + Assert.Equal(10, (v * 10).Siemens); + Assert.Equal(10, (10 * v).Siemens); + Assert.Equal(2, (ElectricSusceptance.FromSiemens(10) / 5).Siemens); + Assert.Equal(2, ElectricSusceptance.FromSiemens(10) / ElectricSusceptance.FromSiemens(5)); } [Fact] @@ -783,8 +800,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ElectricSusceptanceUnit.Siemens, 1, ElectricSusceptanceUnit.Siemens, true)] // Same value and unit. [InlineData(1, ElectricSusceptanceUnit.Siemens, 2, ElectricSusceptanceUnit.Siemens, false)] // Different value. - [InlineData(2, ElectricSusceptanceUnit.Siemens, 1, ElectricSusceptanceUnit.Gigamho, false)] // Different value and unit. - [InlineData(1, ElectricSusceptanceUnit.Siemens, 1, ElectricSusceptanceUnit.Gigamho, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ElectricSusceptanceUnit unitA, double valueB, ElectricSusceptanceUnit unitB, bool expectEqual) { var a = new ElectricSusceptance(valueA, unitA); @@ -844,8 +859,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ElectricSusceptance.FromSiemens(firstValue); var otherQuantity = ElectricSusceptance.FromSiemens(secondValue); ElectricSusceptance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ElectricSusceptance.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -864,7 +879,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -877,6 +892,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ElectricSusceptance.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ElectricSusceptance.Info.Units, ElectricSusceptance.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ElectricSusceptance.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -969,7 +996,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ElectricSusceptance.FromSiemens(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ElectricSusceptance), quantity.As(ElectricSusceptance.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyDensityTestsBase.g.cs index bb8333bb12..38ebff1c6f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyDensityTestsBase.g.cs @@ -169,6 +169,20 @@ public void EnergyDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void EnergyDensityInfo_CreateWithCustomUnitInfos() + { + EnergyDensityUnit[] expectedUnits = [EnergyDensityUnit.JoulePerCubicMeter]; + + EnergyDensity.EnergyDensityInfo quantityInfo = EnergyDensity.EnergyDensityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("EnergyDensity", quantityInfo.Name); + Assert.Equal(EnergyDensity.Zero, quantityInfo.Zero); + Assert.Equal(EnergyDensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void JoulePerCubicMeterToEnergyDensityUnits() { @@ -353,7 +367,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 TJ/m³", EnergyDensityUnit.TerajoulePerCubicMeter, 4.2)] [InlineData("en-US", "4.2 TWh/m³", EnergyDensityUnit.TerawattHourPerCubicMeter, 4.2)] [InlineData("en-US", "4.2 Wh/m³", EnergyDensityUnit.WattHourPerCubicMeter, 4.2)] - public void Parse(string culture, string quantityString, EnergyDensityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, EnergyDensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = EnergyDensity.Parse(quantityString); @@ -374,7 +388,7 @@ public void Parse(string culture, string quantityString, EnergyDensityUnit expec [InlineData("en-US", "4.2 TJ/m³", EnergyDensityUnit.TerajoulePerCubicMeter, 4.2)] [InlineData("en-US", "4.2 TWh/m³", EnergyDensityUnit.TerawattHourPerCubicMeter, 4.2)] [InlineData("en-US", "4.2 Wh/m³", EnergyDensityUnit.WattHourPerCubicMeter, 4.2)] - public void TryParse(string culture, string quantityString, EnergyDensityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, EnergyDensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(EnergyDensity.TryParse(quantityString, out EnergyDensity parsed)); @@ -606,6 +620,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(EnergyDensityUni var quantity = EnergyDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -629,43 +644,45 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(EnergyDensityUnit u IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - EnergyDensity joulepercubicmeter = EnergyDensity.FromJoulesPerCubicMeter(1); - AssertEx.EqualTolerance(1, EnergyDensity.FromGigajoulesPerCubicMeter(joulepercubicmeter.GigajoulesPerCubicMeter).JoulesPerCubicMeter, GigajoulesPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, EnergyDensity.FromGigawattHoursPerCubicMeter(joulepercubicmeter.GigawattHoursPerCubicMeter).JoulesPerCubicMeter, GigawattHoursPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, EnergyDensity.FromJoulesPerCubicMeter(joulepercubicmeter.JoulesPerCubicMeter).JoulesPerCubicMeter, JoulesPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, EnergyDensity.FromKilojoulesPerCubicMeter(joulepercubicmeter.KilojoulesPerCubicMeter).JoulesPerCubicMeter, KilojoulesPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, EnergyDensity.FromKilowattHoursPerCubicMeter(joulepercubicmeter.KilowattHoursPerCubicMeter).JoulesPerCubicMeter, KilowattHoursPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, EnergyDensity.FromMegajoulesPerCubicMeter(joulepercubicmeter.MegajoulesPerCubicMeter).JoulesPerCubicMeter, MegajoulesPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, EnergyDensity.FromMegawattHoursPerCubicMeter(joulepercubicmeter.MegawattHoursPerCubicMeter).JoulesPerCubicMeter, MegawattHoursPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, EnergyDensity.FromPetajoulesPerCubicMeter(joulepercubicmeter.PetajoulesPerCubicMeter).JoulesPerCubicMeter, PetajoulesPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, EnergyDensity.FromPetawattHoursPerCubicMeter(joulepercubicmeter.PetawattHoursPerCubicMeter).JoulesPerCubicMeter, PetawattHoursPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, EnergyDensity.FromTerajoulesPerCubicMeter(joulepercubicmeter.TerajoulesPerCubicMeter).JoulesPerCubicMeter, TerajoulesPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, EnergyDensity.FromTerawattHoursPerCubicMeter(joulepercubicmeter.TerawattHoursPerCubicMeter).JoulesPerCubicMeter, TerawattHoursPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, EnergyDensity.FromWattHoursPerCubicMeter(joulepercubicmeter.WattHoursPerCubicMeter).JoulesPerCubicMeter, WattHoursPerCubicMeterTolerance); + EnergyDensity joulepercubicmeter = EnergyDensity.FromJoulesPerCubicMeter(3); + Assert.Equal(3, EnergyDensity.FromGigajoulesPerCubicMeter(joulepercubicmeter.GigajoulesPerCubicMeter).JoulesPerCubicMeter); + Assert.Equal(3, EnergyDensity.FromGigawattHoursPerCubicMeter(joulepercubicmeter.GigawattHoursPerCubicMeter).JoulesPerCubicMeter); + Assert.Equal(3, EnergyDensity.FromJoulesPerCubicMeter(joulepercubicmeter.JoulesPerCubicMeter).JoulesPerCubicMeter); + Assert.Equal(3, EnergyDensity.FromKilojoulesPerCubicMeter(joulepercubicmeter.KilojoulesPerCubicMeter).JoulesPerCubicMeter); + Assert.Equal(3, EnergyDensity.FromKilowattHoursPerCubicMeter(joulepercubicmeter.KilowattHoursPerCubicMeter).JoulesPerCubicMeter); + Assert.Equal(3, EnergyDensity.FromMegajoulesPerCubicMeter(joulepercubicmeter.MegajoulesPerCubicMeter).JoulesPerCubicMeter); + Assert.Equal(3, EnergyDensity.FromMegawattHoursPerCubicMeter(joulepercubicmeter.MegawattHoursPerCubicMeter).JoulesPerCubicMeter); + Assert.Equal(3, EnergyDensity.FromPetajoulesPerCubicMeter(joulepercubicmeter.PetajoulesPerCubicMeter).JoulesPerCubicMeter); + Assert.Equal(3, EnergyDensity.FromPetawattHoursPerCubicMeter(joulepercubicmeter.PetawattHoursPerCubicMeter).JoulesPerCubicMeter); + Assert.Equal(3, EnergyDensity.FromTerajoulesPerCubicMeter(joulepercubicmeter.TerajoulesPerCubicMeter).JoulesPerCubicMeter); + Assert.Equal(3, EnergyDensity.FromTerawattHoursPerCubicMeter(joulepercubicmeter.TerawattHoursPerCubicMeter).JoulesPerCubicMeter); + Assert.Equal(3, EnergyDensity.FromWattHoursPerCubicMeter(joulepercubicmeter.WattHoursPerCubicMeter).JoulesPerCubicMeter); } [Fact] public void ArithmeticOperators() { EnergyDensity v = EnergyDensity.FromJoulesPerCubicMeter(1); - AssertEx.EqualTolerance(-1, -v.JoulesPerCubicMeter, JoulesPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (EnergyDensity.FromJoulesPerCubicMeter(3)-v).JoulesPerCubicMeter, JoulesPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).JoulesPerCubicMeter, JoulesPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).JoulesPerCubicMeter, JoulesPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).JoulesPerCubicMeter, JoulesPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (EnergyDensity.FromJoulesPerCubicMeter(10)/5).JoulesPerCubicMeter, JoulesPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, EnergyDensity.FromJoulesPerCubicMeter(10)/EnergyDensity.FromJoulesPerCubicMeter(5), JoulesPerCubicMeterTolerance); + Assert.Equal(-1, -v.JoulesPerCubicMeter); + Assert.Equal(2, (EnergyDensity.FromJoulesPerCubicMeter(3) - v).JoulesPerCubicMeter); + Assert.Equal(2, (v + v).JoulesPerCubicMeter); + Assert.Equal(10, (v * 10).JoulesPerCubicMeter); + Assert.Equal(10, (10 * v).JoulesPerCubicMeter); + Assert.Equal(2, (EnergyDensity.FromJoulesPerCubicMeter(10) / 5).JoulesPerCubicMeter); + Assert.Equal(2, EnergyDensity.FromJoulesPerCubicMeter(10) / EnergyDensity.FromJoulesPerCubicMeter(5)); } [Fact] @@ -711,8 +728,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, EnergyDensityUnit.JoulePerCubicMeter, 1, EnergyDensityUnit.JoulePerCubicMeter, true)] // Same value and unit. [InlineData(1, EnergyDensityUnit.JoulePerCubicMeter, 2, EnergyDensityUnit.JoulePerCubicMeter, false)] // Different value. - [InlineData(2, EnergyDensityUnit.JoulePerCubicMeter, 1, EnergyDensityUnit.GigajoulePerCubicMeter, false)] // Different value and unit. - [InlineData(1, EnergyDensityUnit.JoulePerCubicMeter, 1, EnergyDensityUnit.GigajoulePerCubicMeter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, EnergyDensityUnit unitA, double valueB, EnergyDensityUnit unitB, bool expectEqual) { var a = new EnergyDensity(valueA, unitA); @@ -772,8 +787,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = EnergyDensity.FromJoulesPerCubicMeter(firstValue); var otherQuantity = EnergyDensity.FromJoulesPerCubicMeter(secondValue); EnergyDensity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, EnergyDensity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -792,7 +807,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -805,6 +820,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(EnergyDensity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(EnergyDensity.Info.Units, EnergyDensity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, EnergyDensity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -889,7 +916,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = EnergyDensity.FromJoulesPerCubicMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(EnergyDensity), quantity.As(EnergyDensity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs index 7b293ea315..3a3ff80e8e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/EnergyTestsBase.g.cs @@ -281,6 +281,20 @@ public void Energy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void EnergyInfo_CreateWithCustomUnitInfos() + { + EnergyUnit[] expectedUnits = [EnergyUnit.Joule]; + + Energy.EnergyInfo quantityInfo = Energy.EnergyInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Energy", quantityInfo.Name); + Assert.Equal(Energy.Zero, quantityInfo.Zero); + Assert.Equal(Energy.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void JouleToEnergyUnits() { @@ -570,7 +584,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 Американский терм", EnergyUnit.ThermUs, 4.2)] [InlineData("ru-RU", "4,2 Вт/д", EnergyUnit.WattDay, 4.2)] [InlineData("ru-RU", "4,2 Вт/ч", EnergyUnit.WattHour, 4.2)] - public void Parse(string culture, string quantityString, EnergyUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, EnergyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Energy.Parse(quantityString); @@ -640,7 +654,7 @@ public void Parse(string culture, string quantityString, EnergyUnit expectedUnit [InlineData("ru-RU", "4,2 Американский терм", EnergyUnit.ThermUs, 4.2)] [InlineData("ru-RU", "4,2 Вт/д", EnergyUnit.WattDay, 4.2)] [InlineData("ru-RU", "4,2 Вт/ч", EnergyUnit.WattHour, 4.2)] - public void TryParse(string culture, string quantityString, EnergyUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, EnergyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Energy.TryParse(quantityString, out Energy parsed)); @@ -1229,6 +1243,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(EnergyUnit unit) var quantity = Energy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -1252,71 +1267,73 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(EnergyUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Energy joule = Energy.FromJoules(1); - AssertEx.EqualTolerance(1, Energy.FromBritishThermalUnits(joule.BritishThermalUnits).Joules, BritishThermalUnitsTolerance); - AssertEx.EqualTolerance(1, Energy.FromCalories(joule.Calories).Joules, CaloriesTolerance); - AssertEx.EqualTolerance(1, Energy.FromDecathermsEc(joule.DecathermsEc).Joules, DecathermsEcTolerance); - AssertEx.EqualTolerance(1, Energy.FromDecathermsImperial(joule.DecathermsImperial).Joules, DecathermsImperialTolerance); - AssertEx.EqualTolerance(1, Energy.FromDecathermsUs(joule.DecathermsUs).Joules, DecathermsUsTolerance); - AssertEx.EqualTolerance(1, Energy.FromElectronVolts(joule.ElectronVolts).Joules, ElectronVoltsTolerance); - AssertEx.EqualTolerance(1, Energy.FromErgs(joule.Ergs).Joules, ErgsTolerance); - AssertEx.EqualTolerance(1, Energy.FromFootPounds(joule.FootPounds).Joules, FootPoundsTolerance); - AssertEx.EqualTolerance(1, Energy.FromGigabritishThermalUnits(joule.GigabritishThermalUnits).Joules, GigabritishThermalUnitsTolerance); - AssertEx.EqualTolerance(1, Energy.FromGigaelectronVolts(joule.GigaelectronVolts).Joules, GigaelectronVoltsTolerance); - AssertEx.EqualTolerance(1, Energy.FromGigajoules(joule.Gigajoules).Joules, GigajoulesTolerance); - AssertEx.EqualTolerance(1, Energy.FromGigawattDays(joule.GigawattDays).Joules, GigawattDaysTolerance); - AssertEx.EqualTolerance(1, Energy.FromGigawattHours(joule.GigawattHours).Joules, GigawattHoursTolerance); - AssertEx.EqualTolerance(1, Energy.FromHorsepowerHours(joule.HorsepowerHours).Joules, HorsepowerHoursTolerance); - AssertEx.EqualTolerance(1, Energy.FromJoules(joule.Joules).Joules, JoulesTolerance); - AssertEx.EqualTolerance(1, Energy.FromKilobritishThermalUnits(joule.KilobritishThermalUnits).Joules, KilobritishThermalUnitsTolerance); - AssertEx.EqualTolerance(1, Energy.FromKilocalories(joule.Kilocalories).Joules, KilocaloriesTolerance); - AssertEx.EqualTolerance(1, Energy.FromKiloelectronVolts(joule.KiloelectronVolts).Joules, KiloelectronVoltsTolerance); - AssertEx.EqualTolerance(1, Energy.FromKilojoules(joule.Kilojoules).Joules, KilojoulesTolerance); - AssertEx.EqualTolerance(1, Energy.FromKilowattDays(joule.KilowattDays).Joules, KilowattDaysTolerance); - AssertEx.EqualTolerance(1, Energy.FromKilowattHours(joule.KilowattHours).Joules, KilowattHoursTolerance); - AssertEx.EqualTolerance(1, Energy.FromMegabritishThermalUnits(joule.MegabritishThermalUnits).Joules, MegabritishThermalUnitsTolerance); - AssertEx.EqualTolerance(1, Energy.FromMegacalories(joule.Megacalories).Joules, MegacaloriesTolerance); - AssertEx.EqualTolerance(1, Energy.FromMegaelectronVolts(joule.MegaelectronVolts).Joules, MegaelectronVoltsTolerance); - AssertEx.EqualTolerance(1, Energy.FromMegajoules(joule.Megajoules).Joules, MegajoulesTolerance); - AssertEx.EqualTolerance(1, Energy.FromMegawattDays(joule.MegawattDays).Joules, MegawattDaysTolerance); - AssertEx.EqualTolerance(1, Energy.FromMegawattHours(joule.MegawattHours).Joules, MegawattHoursTolerance); - AssertEx.EqualTolerance(1, Energy.FromMicrojoules(joule.Microjoules).Joules, MicrojoulesTolerance); - AssertEx.EqualTolerance(1, Energy.FromMillijoules(joule.Millijoules).Joules, MillijoulesTolerance); - AssertEx.EqualTolerance(1, Energy.FromNanojoules(joule.Nanojoules).Joules, NanojoulesTolerance); - AssertEx.EqualTolerance(1, Energy.FromPetajoules(joule.Petajoules).Joules, PetajoulesTolerance); - AssertEx.EqualTolerance(1, Energy.FromTeraelectronVolts(joule.TeraelectronVolts).Joules, TeraelectronVoltsTolerance); - AssertEx.EqualTolerance(1, Energy.FromTerajoules(joule.Terajoules).Joules, TerajoulesTolerance); - AssertEx.EqualTolerance(1, Energy.FromTerawattDays(joule.TerawattDays).Joules, TerawattDaysTolerance); - AssertEx.EqualTolerance(1, Energy.FromTerawattHours(joule.TerawattHours).Joules, TerawattHoursTolerance); - AssertEx.EqualTolerance(1, Energy.FromThermsEc(joule.ThermsEc).Joules, ThermsEcTolerance); - AssertEx.EqualTolerance(1, Energy.FromThermsImperial(joule.ThermsImperial).Joules, ThermsImperialTolerance); - AssertEx.EqualTolerance(1, Energy.FromThermsUs(joule.ThermsUs).Joules, ThermsUsTolerance); - AssertEx.EqualTolerance(1, Energy.FromWattDays(joule.WattDays).Joules, WattDaysTolerance); - AssertEx.EqualTolerance(1, Energy.FromWattHours(joule.WattHours).Joules, WattHoursTolerance); + Energy joule = Energy.FromJoules(3); + Assert.Equal(3, Energy.FromBritishThermalUnits(joule.BritishThermalUnits).Joules); + Assert.Equal(3, Energy.FromCalories(joule.Calories).Joules); + Assert.Equal(3, Energy.FromDecathermsEc(joule.DecathermsEc).Joules); + Assert.Equal(3, Energy.FromDecathermsImperial(joule.DecathermsImperial).Joules); + Assert.Equal(3, Energy.FromDecathermsUs(joule.DecathermsUs).Joules); + Assert.Equal(3, Energy.FromElectronVolts(joule.ElectronVolts).Joules); + Assert.Equal(3, Energy.FromErgs(joule.Ergs).Joules); + Assert.Equal(3, Energy.FromFootPounds(joule.FootPounds).Joules); + Assert.Equal(3, Energy.FromGigabritishThermalUnits(joule.GigabritishThermalUnits).Joules); + Assert.Equal(3, Energy.FromGigaelectronVolts(joule.GigaelectronVolts).Joules); + Assert.Equal(3, Energy.FromGigajoules(joule.Gigajoules).Joules); + Assert.Equal(3, Energy.FromGigawattDays(joule.GigawattDays).Joules); + Assert.Equal(3, Energy.FromGigawattHours(joule.GigawattHours).Joules); + Assert.Equal(3, Energy.FromHorsepowerHours(joule.HorsepowerHours).Joules); + Assert.Equal(3, Energy.FromJoules(joule.Joules).Joules); + Assert.Equal(3, Energy.FromKilobritishThermalUnits(joule.KilobritishThermalUnits).Joules); + Assert.Equal(3, Energy.FromKilocalories(joule.Kilocalories).Joules); + Assert.Equal(3, Energy.FromKiloelectronVolts(joule.KiloelectronVolts).Joules); + Assert.Equal(3, Energy.FromKilojoules(joule.Kilojoules).Joules); + Assert.Equal(3, Energy.FromKilowattDays(joule.KilowattDays).Joules); + Assert.Equal(3, Energy.FromKilowattHours(joule.KilowattHours).Joules); + Assert.Equal(3, Energy.FromMegabritishThermalUnits(joule.MegabritishThermalUnits).Joules); + Assert.Equal(3, Energy.FromMegacalories(joule.Megacalories).Joules); + Assert.Equal(3, Energy.FromMegaelectronVolts(joule.MegaelectronVolts).Joules); + Assert.Equal(3, Energy.FromMegajoules(joule.Megajoules).Joules); + Assert.Equal(3, Energy.FromMegawattDays(joule.MegawattDays).Joules); + Assert.Equal(3, Energy.FromMegawattHours(joule.MegawattHours).Joules); + Assert.Equal(3, Energy.FromMicrojoules(joule.Microjoules).Joules); + Assert.Equal(3, Energy.FromMillijoules(joule.Millijoules).Joules); + Assert.Equal(3, Energy.FromNanojoules(joule.Nanojoules).Joules); + Assert.Equal(3, Energy.FromPetajoules(joule.Petajoules).Joules); + Assert.Equal(3, Energy.FromTeraelectronVolts(joule.TeraelectronVolts).Joules); + Assert.Equal(3, Energy.FromTerajoules(joule.Terajoules).Joules); + Assert.Equal(3, Energy.FromTerawattDays(joule.TerawattDays).Joules); + Assert.Equal(3, Energy.FromTerawattHours(joule.TerawattHours).Joules); + Assert.Equal(3, Energy.FromThermsEc(joule.ThermsEc).Joules); + Assert.Equal(3, Energy.FromThermsImperial(joule.ThermsImperial).Joules); + Assert.Equal(3, Energy.FromThermsUs(joule.ThermsUs).Joules); + Assert.Equal(3, Energy.FromWattDays(joule.WattDays).Joules); + Assert.Equal(3, Energy.FromWattHours(joule.WattHours).Joules); } [Fact] public void ArithmeticOperators() { Energy v = Energy.FromJoules(1); - AssertEx.EqualTolerance(-1, -v.Joules, JoulesTolerance); - AssertEx.EqualTolerance(2, (Energy.FromJoules(3)-v).Joules, JoulesTolerance); - AssertEx.EqualTolerance(2, (v + v).Joules, JoulesTolerance); - AssertEx.EqualTolerance(10, (v*10).Joules, JoulesTolerance); - AssertEx.EqualTolerance(10, (10*v).Joules, JoulesTolerance); - AssertEx.EqualTolerance(2, (Energy.FromJoules(10)/5).Joules, JoulesTolerance); - AssertEx.EqualTolerance(2, Energy.FromJoules(10)/Energy.FromJoules(5), JoulesTolerance); + Assert.Equal(-1, -v.Joules); + Assert.Equal(2, (Energy.FromJoules(3) - v).Joules); + Assert.Equal(2, (v + v).Joules); + Assert.Equal(10, (v * 10).Joules); + Assert.Equal(10, (10 * v).Joules); + Assert.Equal(2, (Energy.FromJoules(10) / 5).Joules); + Assert.Equal(2, Energy.FromJoules(10) / Energy.FromJoules(5)); } [Fact] @@ -1362,8 +1379,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, EnergyUnit.Joule, 1, EnergyUnit.Joule, true)] // Same value and unit. [InlineData(1, EnergyUnit.Joule, 2, EnergyUnit.Joule, false)] // Different value. - [InlineData(2, EnergyUnit.Joule, 1, EnergyUnit.BritishThermalUnit, false)] // Different value and unit. - [InlineData(1, EnergyUnit.Joule, 1, EnergyUnit.BritishThermalUnit, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, EnergyUnit unitA, double valueB, EnergyUnit unitB, bool expectEqual) { var a = new Energy(valueA, unitA); @@ -1423,8 +1438,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Energy.FromJoules(firstValue); var otherQuantity = Energy.FromJoules(secondValue); Energy maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Energy.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1443,7 +1458,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1456,6 +1471,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Energy.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Energy.Info.Units, Energy.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Energy.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1596,7 +1623,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Energy.FromJoules(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Energy), quantity.As(Energy.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs index 5fe95c5db1..67c125f4e6 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/EntropyTestsBase.g.cs @@ -149,6 +149,20 @@ public void Entropy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void EntropyInfo_CreateWithCustomUnitInfos() + { + EntropyUnit[] expectedUnits = [EntropyUnit.JoulePerKelvin]; + + Entropy.EntropyInfo quantityInfo = Entropy.EntropyInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Entropy", quantityInfo.Name); + Assert.Equal(Entropy.Zero, quantityInfo.Zero); + Assert.Equal(Entropy.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void JoulePerKelvinToEntropyUnits() { @@ -318,7 +332,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 kJ/°C", EntropyUnit.KilojoulePerDegreeCelsius, 4.2)] [InlineData("en-US", "4.2 kJ/K", EntropyUnit.KilojoulePerKelvin, 4.2)] [InlineData("en-US", "4.2 MJ/K", EntropyUnit.MegajoulePerKelvin, 4.2)] - public void Parse(string culture, string quantityString, EntropyUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, EntropyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Entropy.Parse(quantityString); @@ -334,7 +348,7 @@ public void Parse(string culture, string quantityString, EntropyUnit expectedUni [InlineData("en-US", "4.2 kJ/°C", EntropyUnit.KilojoulePerDegreeCelsius, 4.2)] [InlineData("en-US", "4.2 kJ/K", EntropyUnit.KilojoulePerKelvin, 4.2)] [InlineData("en-US", "4.2 MJ/K", EntropyUnit.MegajoulePerKelvin, 4.2)] - public void TryParse(string culture, string quantityString, EntropyUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, EntropyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Entropy.TryParse(quantityString, out Entropy parsed)); @@ -521,6 +535,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(EntropyUnit unit var quantity = Entropy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -544,38 +559,40 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(EntropyUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Entropy jouleperkelvin = Entropy.FromJoulesPerKelvin(1); - AssertEx.EqualTolerance(1, Entropy.FromCaloriesPerKelvin(jouleperkelvin.CaloriesPerKelvin).JoulesPerKelvin, CaloriesPerKelvinTolerance); - AssertEx.EqualTolerance(1, Entropy.FromJoulesPerDegreeCelsius(jouleperkelvin.JoulesPerDegreeCelsius).JoulesPerKelvin, JoulesPerDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, Entropy.FromJoulesPerKelvin(jouleperkelvin.JoulesPerKelvin).JoulesPerKelvin, JoulesPerKelvinTolerance); - AssertEx.EqualTolerance(1, Entropy.FromKilocaloriesPerKelvin(jouleperkelvin.KilocaloriesPerKelvin).JoulesPerKelvin, KilocaloriesPerKelvinTolerance); - AssertEx.EqualTolerance(1, Entropy.FromKilojoulesPerDegreeCelsius(jouleperkelvin.KilojoulesPerDegreeCelsius).JoulesPerKelvin, KilojoulesPerDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, Entropy.FromKilojoulesPerKelvin(jouleperkelvin.KilojoulesPerKelvin).JoulesPerKelvin, KilojoulesPerKelvinTolerance); - AssertEx.EqualTolerance(1, Entropy.FromMegajoulesPerKelvin(jouleperkelvin.MegajoulesPerKelvin).JoulesPerKelvin, MegajoulesPerKelvinTolerance); + Entropy jouleperkelvin = Entropy.FromJoulesPerKelvin(3); + Assert.Equal(3, Entropy.FromCaloriesPerKelvin(jouleperkelvin.CaloriesPerKelvin).JoulesPerKelvin); + Assert.Equal(3, Entropy.FromJoulesPerDegreeCelsius(jouleperkelvin.JoulesPerDegreeCelsius).JoulesPerKelvin); + Assert.Equal(3, Entropy.FromJoulesPerKelvin(jouleperkelvin.JoulesPerKelvin).JoulesPerKelvin); + Assert.Equal(3, Entropy.FromKilocaloriesPerKelvin(jouleperkelvin.KilocaloriesPerKelvin).JoulesPerKelvin); + Assert.Equal(3, Entropy.FromKilojoulesPerDegreeCelsius(jouleperkelvin.KilojoulesPerDegreeCelsius).JoulesPerKelvin); + Assert.Equal(3, Entropy.FromKilojoulesPerKelvin(jouleperkelvin.KilojoulesPerKelvin).JoulesPerKelvin); + Assert.Equal(3, Entropy.FromMegajoulesPerKelvin(jouleperkelvin.MegajoulesPerKelvin).JoulesPerKelvin); } [Fact] public void ArithmeticOperators() { Entropy v = Entropy.FromJoulesPerKelvin(1); - AssertEx.EqualTolerance(-1, -v.JoulesPerKelvin, JoulesPerKelvinTolerance); - AssertEx.EqualTolerance(2, (Entropy.FromJoulesPerKelvin(3)-v).JoulesPerKelvin, JoulesPerKelvinTolerance); - AssertEx.EqualTolerance(2, (v + v).JoulesPerKelvin, JoulesPerKelvinTolerance); - AssertEx.EqualTolerance(10, (v*10).JoulesPerKelvin, JoulesPerKelvinTolerance); - AssertEx.EqualTolerance(10, (10*v).JoulesPerKelvin, JoulesPerKelvinTolerance); - AssertEx.EqualTolerance(2, (Entropy.FromJoulesPerKelvin(10)/5).JoulesPerKelvin, JoulesPerKelvinTolerance); - AssertEx.EqualTolerance(2, Entropy.FromJoulesPerKelvin(10)/Entropy.FromJoulesPerKelvin(5), JoulesPerKelvinTolerance); + Assert.Equal(-1, -v.JoulesPerKelvin); + Assert.Equal(2, (Entropy.FromJoulesPerKelvin(3) - v).JoulesPerKelvin); + Assert.Equal(2, (v + v).JoulesPerKelvin); + Assert.Equal(10, (v * 10).JoulesPerKelvin); + Assert.Equal(10, (10 * v).JoulesPerKelvin); + Assert.Equal(2, (Entropy.FromJoulesPerKelvin(10) / 5).JoulesPerKelvin); + Assert.Equal(2, Entropy.FromJoulesPerKelvin(10) / Entropy.FromJoulesPerKelvin(5)); } [Fact] @@ -621,8 +638,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, EntropyUnit.JoulePerKelvin, 1, EntropyUnit.JoulePerKelvin, true)] // Same value and unit. [InlineData(1, EntropyUnit.JoulePerKelvin, 2, EntropyUnit.JoulePerKelvin, false)] // Different value. - [InlineData(2, EntropyUnit.JoulePerKelvin, 1, EntropyUnit.CaloriePerKelvin, false)] // Different value and unit. - [InlineData(1, EntropyUnit.JoulePerKelvin, 1, EntropyUnit.CaloriePerKelvin, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, EntropyUnit unitA, double valueB, EntropyUnit unitB, bool expectEqual) { var a = new Entropy(valueA, unitA); @@ -682,8 +697,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Entropy.FromJoulesPerKelvin(firstValue); var otherQuantity = Entropy.FromJoulesPerKelvin(secondValue); Entropy maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Entropy.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -702,7 +717,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -715,6 +730,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Entropy.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Entropy.Info.Units, Entropy.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Entropy.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -789,7 +816,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Entropy.FromJoulesPerKelvin(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Entropy), quantity.As(Entropy.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/FluidResistanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/FluidResistanceTestsBase.g.cs index 7a4523034c..d729bf5a2a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/FluidResistanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/FluidResistanceTestsBase.g.cs @@ -197,6 +197,20 @@ public void FluidResistance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void FluidResistanceInfo_CreateWithCustomUnitInfos() + { + FluidResistanceUnit[] expectedUnits = [FluidResistanceUnit.PascalSecondPerCubicMeter]; + + FluidResistance.FluidResistanceInfo quantityInfo = FluidResistance.FluidResistanceInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("FluidResistance", quantityInfo.Name); + Assert.Equal(FluidResistance.Zero, quantityInfo.Zero); + Assert.Equal(FluidResistance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void PascalSecondPerCubicMeterToFluidResistanceUnits() { @@ -425,7 +439,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 Па·с/мл", FluidResistanceUnit.PascalSecondPerMilliliter, 4.2)] [InlineData("ru-RU", "4,2 ЕВ", FluidResistanceUnit.WoodUnit, 4.2)] [InlineData("ru-RU", "4,2 ЕГС", FluidResistanceUnit.WoodUnit, 4.2)] - public void Parse(string culture, string quantityString, FluidResistanceUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, FluidResistanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = FluidResistance.Parse(quantityString); @@ -476,7 +490,7 @@ public void Parse(string culture, string quantityString, FluidResistanceUnit exp [InlineData("ru-RU", "4,2 Па·с/мл", FluidResistanceUnit.PascalSecondPerMilliliter, 4.2)] [InlineData("ru-RU", "4,2 ЕВ", FluidResistanceUnit.WoodUnit, 4.2)] [InlineData("ru-RU", "4,2 ЕГС", FluidResistanceUnit.WoodUnit, 4.2)] - public void TryParse(string culture, string quantityString, FluidResistanceUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, FluidResistanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(FluidResistance.TryParse(quantityString, out FluidResistance parsed)); @@ -890,6 +904,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(FluidResistanceU var quantity = FluidResistance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -913,50 +928,52 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(FluidResistanceUnit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - FluidResistance pascalsecondpercubicmeter = FluidResistance.FromPascalSecondsPerCubicMeter(1); - AssertEx.EqualTolerance(1, FluidResistance.FromDyneSecondsPerCentimeterToTheFifth(pascalsecondpercubicmeter.DyneSecondsPerCentimeterToTheFifth).PascalSecondsPerCubicMeter, DyneSecondsPerCentimeterToTheFifthTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromMegapascalSecondsPerCubicMeter(pascalsecondpercubicmeter.MegapascalSecondsPerCubicMeter).PascalSecondsPerCubicMeter, MegapascalSecondsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromMillimeterMercuryMinutesPerCubicCentimeter(pascalsecondpercubicmeter.MillimeterMercuryMinutesPerCubicCentimeter).PascalSecondsPerCubicMeter, MillimeterMercuryMinutesPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromMillimeterMercuryMinutesPerCubicMeter(pascalsecondpercubicmeter.MillimeterMercuryMinutesPerCubicMeter).PascalSecondsPerCubicMeter, MillimeterMercuryMinutesPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromMillimeterMercuryMinutesPerLiter(pascalsecondpercubicmeter.MillimeterMercuryMinutesPerLiter).PascalSecondsPerCubicMeter, MillimeterMercuryMinutesPerLiterTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromMillimeterMercuryMinutesPerMilliliter(pascalsecondpercubicmeter.MillimeterMercuryMinutesPerMilliliter).PascalSecondsPerCubicMeter, MillimeterMercuryMinutesPerMilliliterTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromMillimeterMercurySecondsPerCubicCentimeter(pascalsecondpercubicmeter.MillimeterMercurySecondsPerCubicCentimeter).PascalSecondsPerCubicMeter, MillimeterMercurySecondsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromMillimeterMercurySecondsPerCubicMeter(pascalsecondpercubicmeter.MillimeterMercurySecondsPerCubicMeter).PascalSecondsPerCubicMeter, MillimeterMercurySecondsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromMillimeterMercurySecondsPerLiter(pascalsecondpercubicmeter.MillimeterMercurySecondsPerLiter).PascalSecondsPerCubicMeter, MillimeterMercurySecondsPerLiterTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromMillimeterMercurySecondsPerMilliliter(pascalsecondpercubicmeter.MillimeterMercurySecondsPerMilliliter).PascalSecondsPerCubicMeter, MillimeterMercurySecondsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromPascalMinutesPerCubicCentimeter(pascalsecondpercubicmeter.PascalMinutesPerCubicCentimeter).PascalSecondsPerCubicMeter, PascalMinutesPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromPascalMinutesPerCubicMeter(pascalsecondpercubicmeter.PascalMinutesPerCubicMeter).PascalSecondsPerCubicMeter, PascalMinutesPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromPascalMinutesPerLiter(pascalsecondpercubicmeter.PascalMinutesPerLiter).PascalSecondsPerCubicMeter, PascalMinutesPerLiterTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromPascalMinutesPerMilliliter(pascalsecondpercubicmeter.PascalMinutesPerMilliliter).PascalSecondsPerCubicMeter, PascalMinutesPerMilliliterTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromPascalSecondsPerCubicCentimeter(pascalsecondpercubicmeter.PascalSecondsPerCubicCentimeter).PascalSecondsPerCubicMeter, PascalSecondsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromPascalSecondsPerCubicMeter(pascalsecondpercubicmeter.PascalSecondsPerCubicMeter).PascalSecondsPerCubicMeter, PascalSecondsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromPascalSecondsPerLiter(pascalsecondpercubicmeter.PascalSecondsPerLiter).PascalSecondsPerCubicMeter, PascalSecondsPerLiterTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromPascalSecondsPerMilliliter(pascalsecondpercubicmeter.PascalSecondsPerMilliliter).PascalSecondsPerCubicMeter, PascalSecondsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, FluidResistance.FromWoodUnits(pascalsecondpercubicmeter.WoodUnits).PascalSecondsPerCubicMeter, WoodUnitsTolerance); + FluidResistance pascalsecondpercubicmeter = FluidResistance.FromPascalSecondsPerCubicMeter(3); + Assert.Equal(3, FluidResistance.FromDyneSecondsPerCentimeterToTheFifth(pascalsecondpercubicmeter.DyneSecondsPerCentimeterToTheFifth).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromMegapascalSecondsPerCubicMeter(pascalsecondpercubicmeter.MegapascalSecondsPerCubicMeter).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromMillimeterMercuryMinutesPerCubicCentimeter(pascalsecondpercubicmeter.MillimeterMercuryMinutesPerCubicCentimeter).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromMillimeterMercuryMinutesPerCubicMeter(pascalsecondpercubicmeter.MillimeterMercuryMinutesPerCubicMeter).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromMillimeterMercuryMinutesPerLiter(pascalsecondpercubicmeter.MillimeterMercuryMinutesPerLiter).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromMillimeterMercuryMinutesPerMilliliter(pascalsecondpercubicmeter.MillimeterMercuryMinutesPerMilliliter).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromMillimeterMercurySecondsPerCubicCentimeter(pascalsecondpercubicmeter.MillimeterMercurySecondsPerCubicCentimeter).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromMillimeterMercurySecondsPerCubicMeter(pascalsecondpercubicmeter.MillimeterMercurySecondsPerCubicMeter).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromMillimeterMercurySecondsPerLiter(pascalsecondpercubicmeter.MillimeterMercurySecondsPerLiter).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromMillimeterMercurySecondsPerMilliliter(pascalsecondpercubicmeter.MillimeterMercurySecondsPerMilliliter).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromPascalMinutesPerCubicCentimeter(pascalsecondpercubicmeter.PascalMinutesPerCubicCentimeter).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromPascalMinutesPerCubicMeter(pascalsecondpercubicmeter.PascalMinutesPerCubicMeter).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromPascalMinutesPerLiter(pascalsecondpercubicmeter.PascalMinutesPerLiter).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromPascalMinutesPerMilliliter(pascalsecondpercubicmeter.PascalMinutesPerMilliliter).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromPascalSecondsPerCubicCentimeter(pascalsecondpercubicmeter.PascalSecondsPerCubicCentimeter).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromPascalSecondsPerCubicMeter(pascalsecondpercubicmeter.PascalSecondsPerCubicMeter).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromPascalSecondsPerLiter(pascalsecondpercubicmeter.PascalSecondsPerLiter).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromPascalSecondsPerMilliliter(pascalsecondpercubicmeter.PascalSecondsPerMilliliter).PascalSecondsPerCubicMeter); + Assert.Equal(3, FluidResistance.FromWoodUnits(pascalsecondpercubicmeter.WoodUnits).PascalSecondsPerCubicMeter); } [Fact] public void ArithmeticOperators() { FluidResistance v = FluidResistance.FromPascalSecondsPerCubicMeter(1); - AssertEx.EqualTolerance(-1, -v.PascalSecondsPerCubicMeter, PascalSecondsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (FluidResistance.FromPascalSecondsPerCubicMeter(3)-v).PascalSecondsPerCubicMeter, PascalSecondsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).PascalSecondsPerCubicMeter, PascalSecondsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).PascalSecondsPerCubicMeter, PascalSecondsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).PascalSecondsPerCubicMeter, PascalSecondsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (FluidResistance.FromPascalSecondsPerCubicMeter(10)/5).PascalSecondsPerCubicMeter, PascalSecondsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, FluidResistance.FromPascalSecondsPerCubicMeter(10)/FluidResistance.FromPascalSecondsPerCubicMeter(5), PascalSecondsPerCubicMeterTolerance); + Assert.Equal(-1, -v.PascalSecondsPerCubicMeter); + Assert.Equal(2, (FluidResistance.FromPascalSecondsPerCubicMeter(3) - v).PascalSecondsPerCubicMeter); + Assert.Equal(2, (v + v).PascalSecondsPerCubicMeter); + Assert.Equal(10, (v * 10).PascalSecondsPerCubicMeter); + Assert.Equal(10, (10 * v).PascalSecondsPerCubicMeter); + Assert.Equal(2, (FluidResistance.FromPascalSecondsPerCubicMeter(10) / 5).PascalSecondsPerCubicMeter); + Assert.Equal(2, FluidResistance.FromPascalSecondsPerCubicMeter(10) / FluidResistance.FromPascalSecondsPerCubicMeter(5)); } [Fact] @@ -1002,8 +1019,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, FluidResistanceUnit.PascalSecondPerCubicMeter, 1, FluidResistanceUnit.PascalSecondPerCubicMeter, true)] // Same value and unit. [InlineData(1, FluidResistanceUnit.PascalSecondPerCubicMeter, 2, FluidResistanceUnit.PascalSecondPerCubicMeter, false)] // Different value. - [InlineData(2, FluidResistanceUnit.PascalSecondPerCubicMeter, 1, FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, false)] // Different value and unit. - [InlineData(1, FluidResistanceUnit.PascalSecondPerCubicMeter, 1, FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, FluidResistanceUnit unitA, double valueB, FluidResistanceUnit unitB, bool expectEqual) { var a = new FluidResistance(valueA, unitA); @@ -1063,8 +1078,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(firstValue); var otherQuantity = FluidResistance.FromPascalSecondsPerCubicMeter(secondValue); FluidResistance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, FluidResistance.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1083,7 +1098,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1096,6 +1111,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(FluidResistance.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(FluidResistance.Info.Units, FluidResistance.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, FluidResistance.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1194,7 +1221,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = FluidResistance.FromPascalSecondsPerCubicMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(FluidResistance), quantity.As(FluidResistance.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs index e336bc373f..5715018475 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceChangeRateTestsBase.g.cs @@ -181,6 +181,20 @@ public void ForceChangeRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ForceChangeRateInfo_CreateWithCustomUnitInfos() + { + ForceChangeRateUnit[] expectedUnits = [ForceChangeRateUnit.NewtonPerSecond]; + + ForceChangeRate.ForceChangeRateInfo quantityInfo = ForceChangeRate.ForceChangeRateInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ForceChangeRate", quantityInfo.Name); + Assert.Equal(ForceChangeRate.Zero, quantityInfo.Zero); + Assert.Equal(ForceChangeRate.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void NewtonPerSecondToForceChangeRateUnits() { @@ -378,7 +392,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 N/s", ForceChangeRateUnit.NewtonPerSecond, 4.2)] [InlineData("en-US", "4.2 lbf/min", ForceChangeRateUnit.PoundForcePerMinute, 4.2)] [InlineData("en-US", "4.2 lbf/s", ForceChangeRateUnit.PoundForcePerSecond, 4.2)] - public void Parse(string culture, string quantityString, ForceChangeRateUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ForceChangeRateUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ForceChangeRate.Parse(quantityString); @@ -406,7 +420,7 @@ public void Parse(string culture, string quantityString, ForceChangeRateUnit exp [InlineData("en-US", "4.2 N/s", ForceChangeRateUnit.NewtonPerSecond, 4.2)] [InlineData("en-US", "4.2 lbf/min", ForceChangeRateUnit.PoundForcePerMinute, 4.2)] [InlineData("en-US", "4.2 lbf/s", ForceChangeRateUnit.PoundForcePerSecond, 4.2)] - public void TryParse(string culture, string quantityString, ForceChangeRateUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ForceChangeRateUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ForceChangeRate.TryParse(quantityString, out ForceChangeRate parsed)); @@ -697,6 +711,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ForceChangeRateU var quantity = ForceChangeRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -720,46 +735,48 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ForceChangeRateUnit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ForceChangeRate newtonpersecond = ForceChangeRate.FromNewtonsPerSecond(1); - AssertEx.EqualTolerance(1, ForceChangeRate.FromCentinewtonsPerSecond(newtonpersecond.CentinewtonsPerSecond).NewtonsPerSecond, CentinewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromDecanewtonsPerMinute(newtonpersecond.DecanewtonsPerMinute).NewtonsPerSecond, DecanewtonsPerMinuteTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromDecanewtonsPerSecond(newtonpersecond.DecanewtonsPerSecond).NewtonsPerSecond, DecanewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromDecinewtonsPerSecond(newtonpersecond.DecinewtonsPerSecond).NewtonsPerSecond, DecinewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromKilonewtonsPerMinute(newtonpersecond.KilonewtonsPerMinute).NewtonsPerSecond, KilonewtonsPerMinuteTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromKilonewtonsPerSecond(newtonpersecond.KilonewtonsPerSecond).NewtonsPerSecond, KilonewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromKilopoundsForcePerMinute(newtonpersecond.KilopoundsForcePerMinute).NewtonsPerSecond, KilopoundsForcePerMinuteTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromKilopoundsForcePerSecond(newtonpersecond.KilopoundsForcePerSecond).NewtonsPerSecond, KilopoundsForcePerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromMicronewtonsPerSecond(newtonpersecond.MicronewtonsPerSecond).NewtonsPerSecond, MicronewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromMillinewtonsPerSecond(newtonpersecond.MillinewtonsPerSecond).NewtonsPerSecond, MillinewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromNanonewtonsPerSecond(newtonpersecond.NanonewtonsPerSecond).NewtonsPerSecond, NanonewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromNewtonsPerMinute(newtonpersecond.NewtonsPerMinute).NewtonsPerSecond, NewtonsPerMinuteTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromNewtonsPerSecond(newtonpersecond.NewtonsPerSecond).NewtonsPerSecond, NewtonsPerSecondTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromPoundsForcePerMinute(newtonpersecond.PoundsForcePerMinute).NewtonsPerSecond, PoundsForcePerMinuteTolerance); - AssertEx.EqualTolerance(1, ForceChangeRate.FromPoundsForcePerSecond(newtonpersecond.PoundsForcePerSecond).NewtonsPerSecond, PoundsForcePerSecondTolerance); + ForceChangeRate newtonpersecond = ForceChangeRate.FromNewtonsPerSecond(3); + Assert.Equal(3, ForceChangeRate.FromCentinewtonsPerSecond(newtonpersecond.CentinewtonsPerSecond).NewtonsPerSecond); + Assert.Equal(3, ForceChangeRate.FromDecanewtonsPerMinute(newtonpersecond.DecanewtonsPerMinute).NewtonsPerSecond); + Assert.Equal(3, ForceChangeRate.FromDecanewtonsPerSecond(newtonpersecond.DecanewtonsPerSecond).NewtonsPerSecond); + Assert.Equal(3, ForceChangeRate.FromDecinewtonsPerSecond(newtonpersecond.DecinewtonsPerSecond).NewtonsPerSecond); + Assert.Equal(3, ForceChangeRate.FromKilonewtonsPerMinute(newtonpersecond.KilonewtonsPerMinute).NewtonsPerSecond); + Assert.Equal(3, ForceChangeRate.FromKilonewtonsPerSecond(newtonpersecond.KilonewtonsPerSecond).NewtonsPerSecond); + Assert.Equal(3, ForceChangeRate.FromKilopoundsForcePerMinute(newtonpersecond.KilopoundsForcePerMinute).NewtonsPerSecond); + Assert.Equal(3, ForceChangeRate.FromKilopoundsForcePerSecond(newtonpersecond.KilopoundsForcePerSecond).NewtonsPerSecond); + Assert.Equal(3, ForceChangeRate.FromMicronewtonsPerSecond(newtonpersecond.MicronewtonsPerSecond).NewtonsPerSecond); + Assert.Equal(3, ForceChangeRate.FromMillinewtonsPerSecond(newtonpersecond.MillinewtonsPerSecond).NewtonsPerSecond); + Assert.Equal(3, ForceChangeRate.FromNanonewtonsPerSecond(newtonpersecond.NanonewtonsPerSecond).NewtonsPerSecond); + Assert.Equal(3, ForceChangeRate.FromNewtonsPerMinute(newtonpersecond.NewtonsPerMinute).NewtonsPerSecond); + Assert.Equal(3, ForceChangeRate.FromNewtonsPerSecond(newtonpersecond.NewtonsPerSecond).NewtonsPerSecond); + Assert.Equal(3, ForceChangeRate.FromPoundsForcePerMinute(newtonpersecond.PoundsForcePerMinute).NewtonsPerSecond); + Assert.Equal(3, ForceChangeRate.FromPoundsForcePerSecond(newtonpersecond.PoundsForcePerSecond).NewtonsPerSecond); } [Fact] public void ArithmeticOperators() { ForceChangeRate v = ForceChangeRate.FromNewtonsPerSecond(1); - AssertEx.EqualTolerance(-1, -v.NewtonsPerSecond, NewtonsPerSecondTolerance); - AssertEx.EqualTolerance(2, (ForceChangeRate.FromNewtonsPerSecond(3)-v).NewtonsPerSecond, NewtonsPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).NewtonsPerSecond, NewtonsPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).NewtonsPerSecond, NewtonsPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).NewtonsPerSecond, NewtonsPerSecondTolerance); - AssertEx.EqualTolerance(2, (ForceChangeRate.FromNewtonsPerSecond(10)/5).NewtonsPerSecond, NewtonsPerSecondTolerance); - AssertEx.EqualTolerance(2, ForceChangeRate.FromNewtonsPerSecond(10)/ForceChangeRate.FromNewtonsPerSecond(5), NewtonsPerSecondTolerance); + Assert.Equal(-1, -v.NewtonsPerSecond); + Assert.Equal(2, (ForceChangeRate.FromNewtonsPerSecond(3) - v).NewtonsPerSecond); + Assert.Equal(2, (v + v).NewtonsPerSecond); + Assert.Equal(10, (v * 10).NewtonsPerSecond); + Assert.Equal(10, (10 * v).NewtonsPerSecond); + Assert.Equal(2, (ForceChangeRate.FromNewtonsPerSecond(10) / 5).NewtonsPerSecond); + Assert.Equal(2, ForceChangeRate.FromNewtonsPerSecond(10) / ForceChangeRate.FromNewtonsPerSecond(5)); } [Fact] @@ -805,8 +822,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ForceChangeRateUnit.NewtonPerSecond, 1, ForceChangeRateUnit.NewtonPerSecond, true)] // Same value and unit. [InlineData(1, ForceChangeRateUnit.NewtonPerSecond, 2, ForceChangeRateUnit.NewtonPerSecond, false)] // Different value. - [InlineData(2, ForceChangeRateUnit.NewtonPerSecond, 1, ForceChangeRateUnit.CentinewtonPerSecond, false)] // Different value and unit. - [InlineData(1, ForceChangeRateUnit.NewtonPerSecond, 1, ForceChangeRateUnit.CentinewtonPerSecond, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ForceChangeRateUnit unitA, double valueB, ForceChangeRateUnit unitB, bool expectEqual) { var a = new ForceChangeRate(valueA, unitA); @@ -866,8 +881,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ForceChangeRate.FromNewtonsPerSecond(firstValue); var otherQuantity = ForceChangeRate.FromNewtonsPerSecond(secondValue); ForceChangeRate maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ForceChangeRate.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -886,7 +901,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -899,6 +914,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ForceChangeRate.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ForceChangeRate.Info.Units, ForceChangeRate.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ForceChangeRate.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -989,7 +1016,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ForceChangeRate.FromNewtonsPerSecond(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ForceChangeRate), quantity.As(ForceChangeRate.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs index 7cc6373954..4c399cbc07 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ForcePerLengthTestsBase.g.cs @@ -273,6 +273,20 @@ public void ForcePerLength_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ForcePerLengthInfo_CreateWithCustomUnitInfos() + { + ForcePerLengthUnit[] expectedUnits = [ForcePerLengthUnit.NewtonPerMeter]; + + ForcePerLength.ForcePerLengthInfo quantityInfo = ForcePerLength.ForcePerLengthInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ForcePerLength", quantityInfo.Name); + Assert.Equal(ForcePerLength.Zero, quantityInfo.Zero); + Assert.Equal(ForcePerLength.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void NewtonPerMeterToForcePerLengthUnits() { @@ -545,7 +559,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 тс/см", ForcePerLengthUnit.TonneForcePerCentimeter, 4.2)] [InlineData("ru-RU", "4,2 тс/м", ForcePerLengthUnit.TonneForcePerMeter, 4.2)] [InlineData("ru-RU", "4,2 тс/мм", ForcePerLengthUnit.TonneForcePerMillimeter, 4.2)] - public void Parse(string culture, string quantityString, ForcePerLengthUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ForcePerLengthUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ForcePerLength.Parse(quantityString); @@ -602,7 +616,7 @@ public void Parse(string culture, string quantityString, ForcePerLengthUnit expe [InlineData("ru-RU", "4,2 тс/см", ForcePerLengthUnit.TonneForcePerCentimeter, 4.2)] [InlineData("ru-RU", "4,2 тс/м", ForcePerLengthUnit.TonneForcePerMeter, 4.2)] [InlineData("ru-RU", "4,2 тс/мм", ForcePerLengthUnit.TonneForcePerMillimeter, 4.2)] - public void TryParse(string culture, string quantityString, ForcePerLengthUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ForcePerLengthUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ForcePerLength.TryParse(quantityString, out ForcePerLength parsed)); @@ -1130,6 +1144,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ForcePerLengthUn var quantity = ForcePerLength.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -1153,69 +1168,71 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ForcePerLengthUnit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ForcePerLength newtonpermeter = ForcePerLength.FromNewtonsPerMeter(1); - AssertEx.EqualTolerance(1, ForcePerLength.FromCentinewtonsPerCentimeter(newtonpermeter.CentinewtonsPerCentimeter).NewtonsPerMeter, CentinewtonsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromCentinewtonsPerMeter(newtonpermeter.CentinewtonsPerMeter).NewtonsPerMeter, CentinewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromCentinewtonsPerMillimeter(newtonpermeter.CentinewtonsPerMillimeter).NewtonsPerMeter, CentinewtonsPerMillimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromDecanewtonsPerCentimeter(newtonpermeter.DecanewtonsPerCentimeter).NewtonsPerMeter, DecanewtonsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromDecanewtonsPerMeter(newtonpermeter.DecanewtonsPerMeter).NewtonsPerMeter, DecanewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromDecanewtonsPerMillimeter(newtonpermeter.DecanewtonsPerMillimeter).NewtonsPerMeter, DecanewtonsPerMillimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromDecinewtonsPerCentimeter(newtonpermeter.DecinewtonsPerCentimeter).NewtonsPerMeter, DecinewtonsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromDecinewtonsPerMeter(newtonpermeter.DecinewtonsPerMeter).NewtonsPerMeter, DecinewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromDecinewtonsPerMillimeter(newtonpermeter.DecinewtonsPerMillimeter).NewtonsPerMeter, DecinewtonsPerMillimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromKilogramsForcePerCentimeter(newtonpermeter.KilogramsForcePerCentimeter).NewtonsPerMeter, KilogramsForcePerCentimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromKilogramsForcePerMeter(newtonpermeter.KilogramsForcePerMeter).NewtonsPerMeter, KilogramsForcePerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromKilogramsForcePerMillimeter(newtonpermeter.KilogramsForcePerMillimeter).NewtonsPerMeter, KilogramsForcePerMillimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromKilonewtonsPerCentimeter(newtonpermeter.KilonewtonsPerCentimeter).NewtonsPerMeter, KilonewtonsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromKilonewtonsPerMeter(newtonpermeter.KilonewtonsPerMeter).NewtonsPerMeter, KilonewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromKilonewtonsPerMillimeter(newtonpermeter.KilonewtonsPerMillimeter).NewtonsPerMeter, KilonewtonsPerMillimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromKilopoundsForcePerFoot(newtonpermeter.KilopoundsForcePerFoot).NewtonsPerMeter, KilopoundsForcePerFootTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromKilopoundsForcePerInch(newtonpermeter.KilopoundsForcePerInch).NewtonsPerMeter, KilopoundsForcePerInchTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromMeganewtonsPerCentimeter(newtonpermeter.MeganewtonsPerCentimeter).NewtonsPerMeter, MeganewtonsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromMeganewtonsPerMeter(newtonpermeter.MeganewtonsPerMeter).NewtonsPerMeter, MeganewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromMeganewtonsPerMillimeter(newtonpermeter.MeganewtonsPerMillimeter).NewtonsPerMeter, MeganewtonsPerMillimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromMicronewtonsPerCentimeter(newtonpermeter.MicronewtonsPerCentimeter).NewtonsPerMeter, MicronewtonsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromMicronewtonsPerMeter(newtonpermeter.MicronewtonsPerMeter).NewtonsPerMeter, MicronewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromMicronewtonsPerMillimeter(newtonpermeter.MicronewtonsPerMillimeter).NewtonsPerMeter, MicronewtonsPerMillimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromMillinewtonsPerCentimeter(newtonpermeter.MillinewtonsPerCentimeter).NewtonsPerMeter, MillinewtonsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromMillinewtonsPerMeter(newtonpermeter.MillinewtonsPerMeter).NewtonsPerMeter, MillinewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromMillinewtonsPerMillimeter(newtonpermeter.MillinewtonsPerMillimeter).NewtonsPerMeter, MillinewtonsPerMillimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromNanonewtonsPerCentimeter(newtonpermeter.NanonewtonsPerCentimeter).NewtonsPerMeter, NanonewtonsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromNanonewtonsPerMeter(newtonpermeter.NanonewtonsPerMeter).NewtonsPerMeter, NanonewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromNanonewtonsPerMillimeter(newtonpermeter.NanonewtonsPerMillimeter).NewtonsPerMeter, NanonewtonsPerMillimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromNewtonsPerCentimeter(newtonpermeter.NewtonsPerCentimeter).NewtonsPerMeter, NewtonsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromNewtonsPerMeter(newtonpermeter.NewtonsPerMeter).NewtonsPerMeter, NewtonsPerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromNewtonsPerMillimeter(newtonpermeter.NewtonsPerMillimeter).NewtonsPerMeter, NewtonsPerMillimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromPoundsForcePerFoot(newtonpermeter.PoundsForcePerFoot).NewtonsPerMeter, PoundsForcePerFootTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromPoundsForcePerInch(newtonpermeter.PoundsForcePerInch).NewtonsPerMeter, PoundsForcePerInchTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromPoundsForcePerYard(newtonpermeter.PoundsForcePerYard).NewtonsPerMeter, PoundsForcePerYardTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromTonnesForcePerCentimeter(newtonpermeter.TonnesForcePerCentimeter).NewtonsPerMeter, TonnesForcePerCentimeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromTonnesForcePerMeter(newtonpermeter.TonnesForcePerMeter).NewtonsPerMeter, TonnesForcePerMeterTolerance); - AssertEx.EqualTolerance(1, ForcePerLength.FromTonnesForcePerMillimeter(newtonpermeter.TonnesForcePerMillimeter).NewtonsPerMeter, TonnesForcePerMillimeterTolerance); + ForcePerLength newtonpermeter = ForcePerLength.FromNewtonsPerMeter(3); + Assert.Equal(3, ForcePerLength.FromCentinewtonsPerCentimeter(newtonpermeter.CentinewtonsPerCentimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromCentinewtonsPerMeter(newtonpermeter.CentinewtonsPerMeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromCentinewtonsPerMillimeter(newtonpermeter.CentinewtonsPerMillimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromDecanewtonsPerCentimeter(newtonpermeter.DecanewtonsPerCentimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromDecanewtonsPerMeter(newtonpermeter.DecanewtonsPerMeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromDecanewtonsPerMillimeter(newtonpermeter.DecanewtonsPerMillimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromDecinewtonsPerCentimeter(newtonpermeter.DecinewtonsPerCentimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromDecinewtonsPerMeter(newtonpermeter.DecinewtonsPerMeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromDecinewtonsPerMillimeter(newtonpermeter.DecinewtonsPerMillimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromKilogramsForcePerCentimeter(newtonpermeter.KilogramsForcePerCentimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromKilogramsForcePerMeter(newtonpermeter.KilogramsForcePerMeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromKilogramsForcePerMillimeter(newtonpermeter.KilogramsForcePerMillimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromKilonewtonsPerCentimeter(newtonpermeter.KilonewtonsPerCentimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromKilonewtonsPerMeter(newtonpermeter.KilonewtonsPerMeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromKilonewtonsPerMillimeter(newtonpermeter.KilonewtonsPerMillimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromKilopoundsForcePerFoot(newtonpermeter.KilopoundsForcePerFoot).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromKilopoundsForcePerInch(newtonpermeter.KilopoundsForcePerInch).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromMeganewtonsPerCentimeter(newtonpermeter.MeganewtonsPerCentimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromMeganewtonsPerMeter(newtonpermeter.MeganewtonsPerMeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromMeganewtonsPerMillimeter(newtonpermeter.MeganewtonsPerMillimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromMicronewtonsPerCentimeter(newtonpermeter.MicronewtonsPerCentimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromMicronewtonsPerMeter(newtonpermeter.MicronewtonsPerMeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromMicronewtonsPerMillimeter(newtonpermeter.MicronewtonsPerMillimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromMillinewtonsPerCentimeter(newtonpermeter.MillinewtonsPerCentimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromMillinewtonsPerMeter(newtonpermeter.MillinewtonsPerMeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromMillinewtonsPerMillimeter(newtonpermeter.MillinewtonsPerMillimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromNanonewtonsPerCentimeter(newtonpermeter.NanonewtonsPerCentimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromNanonewtonsPerMeter(newtonpermeter.NanonewtonsPerMeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromNanonewtonsPerMillimeter(newtonpermeter.NanonewtonsPerMillimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromNewtonsPerCentimeter(newtonpermeter.NewtonsPerCentimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromNewtonsPerMeter(newtonpermeter.NewtonsPerMeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromNewtonsPerMillimeter(newtonpermeter.NewtonsPerMillimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromPoundsForcePerFoot(newtonpermeter.PoundsForcePerFoot).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromPoundsForcePerInch(newtonpermeter.PoundsForcePerInch).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromPoundsForcePerYard(newtonpermeter.PoundsForcePerYard).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromTonnesForcePerCentimeter(newtonpermeter.TonnesForcePerCentimeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromTonnesForcePerMeter(newtonpermeter.TonnesForcePerMeter).NewtonsPerMeter); + Assert.Equal(3, ForcePerLength.FromTonnesForcePerMillimeter(newtonpermeter.TonnesForcePerMillimeter).NewtonsPerMeter); } [Fact] public void ArithmeticOperators() { ForcePerLength v = ForcePerLength.FromNewtonsPerMeter(1); - AssertEx.EqualTolerance(-1, -v.NewtonsPerMeter, NewtonsPerMeterTolerance); - AssertEx.EqualTolerance(2, (ForcePerLength.FromNewtonsPerMeter(3)-v).NewtonsPerMeter, NewtonsPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).NewtonsPerMeter, NewtonsPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).NewtonsPerMeter, NewtonsPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).NewtonsPerMeter, NewtonsPerMeterTolerance); - AssertEx.EqualTolerance(2, (ForcePerLength.FromNewtonsPerMeter(10)/5).NewtonsPerMeter, NewtonsPerMeterTolerance); - AssertEx.EqualTolerance(2, ForcePerLength.FromNewtonsPerMeter(10)/ForcePerLength.FromNewtonsPerMeter(5), NewtonsPerMeterTolerance); + Assert.Equal(-1, -v.NewtonsPerMeter); + Assert.Equal(2, (ForcePerLength.FromNewtonsPerMeter(3) - v).NewtonsPerMeter); + Assert.Equal(2, (v + v).NewtonsPerMeter); + Assert.Equal(10, (v * 10).NewtonsPerMeter); + Assert.Equal(10, (10 * v).NewtonsPerMeter); + Assert.Equal(2, (ForcePerLength.FromNewtonsPerMeter(10) / 5).NewtonsPerMeter); + Assert.Equal(2, ForcePerLength.FromNewtonsPerMeter(10) / ForcePerLength.FromNewtonsPerMeter(5)); } [Fact] @@ -1261,8 +1278,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ForcePerLengthUnit.NewtonPerMeter, 1, ForcePerLengthUnit.NewtonPerMeter, true)] // Same value and unit. [InlineData(1, ForcePerLengthUnit.NewtonPerMeter, 2, ForcePerLengthUnit.NewtonPerMeter, false)] // Different value. - [InlineData(2, ForcePerLengthUnit.NewtonPerMeter, 1, ForcePerLengthUnit.CentinewtonPerCentimeter, false)] // Different value and unit. - [InlineData(1, ForcePerLengthUnit.NewtonPerMeter, 1, ForcePerLengthUnit.CentinewtonPerCentimeter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ForcePerLengthUnit unitA, double valueB, ForcePerLengthUnit unitB, bool expectEqual) { var a = new ForcePerLength(valueA, unitA); @@ -1322,8 +1337,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ForcePerLength.FromNewtonsPerMeter(firstValue); var otherQuantity = ForcePerLength.FromNewtonsPerMeter(secondValue); ForcePerLength maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ForcePerLength.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1342,7 +1357,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1355,6 +1370,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ForcePerLength.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ForcePerLength.Info.Units, ForcePerLength.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ForcePerLength.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1491,7 +1518,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ForcePerLength.FromNewtonsPerMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ForcePerLength), quantity.As(ForcePerLength.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs index ffd2dc009e..632fb06496 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ForceTestsBase.g.cs @@ -181,6 +181,20 @@ public void Force_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ForceInfo_CreateWithCustomUnitInfos() + { + ForceUnit[] expectedUnits = [ForceUnit.Newton]; + + Force.ForceInfo quantityInfo = Force.ForceInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Force", quantityInfo.Name); + Assert.Equal(Force.Zero, quantityInfo.Zero); + Assert.Equal(Force.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void NewtonToForceUnits() { @@ -392,7 +406,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 паундаль", ForceUnit.Poundal, 4.2)] [InlineData("ru-RU", "4,2 фунт-сила", ForceUnit.PoundForce, 4.2)] [InlineData("ru-RU", "4,2 тс", ForceUnit.TonneForce, 4.2)] - public void Parse(string culture, string quantityString, ForceUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ForceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Force.Parse(quantityString); @@ -441,7 +455,7 @@ public void ParseWithAmbiguousAbbreviation(string culture, string quantityString [InlineData("ru-RU", "4,2 паундаль", ForceUnit.Poundal, 4.2)] [InlineData("ru-RU", "4,2 фунт-сила", ForceUnit.PoundForce, 4.2)] [InlineData("ru-RU", "4,2 тс", ForceUnit.TonneForce, 4.2)] - public void TryParse(string culture, string quantityString, ForceUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ForceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Force.TryParse(quantityString, out Force parsed)); @@ -826,6 +840,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ForceUnit unit) var quantity = Force.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -849,46 +864,48 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ForceUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Force newton = Force.FromNewtons(1); - AssertEx.EqualTolerance(1, Force.FromDecanewtons(newton.Decanewtons).Newtons, DecanewtonsTolerance); - AssertEx.EqualTolerance(1, Force.FromDyne(newton.Dyne).Newtons, DyneTolerance); - AssertEx.EqualTolerance(1, Force.FromKilogramsForce(newton.KilogramsForce).Newtons, KilogramsForceTolerance); - AssertEx.EqualTolerance(1, Force.FromKilonewtons(newton.Kilonewtons).Newtons, KilonewtonsTolerance); - AssertEx.EqualTolerance(1, Force.FromKiloPonds(newton.KiloPonds).Newtons, KiloPondsTolerance); - AssertEx.EqualTolerance(1, Force.FromKilopoundsForce(newton.KilopoundsForce).Newtons, KilopoundsForceTolerance); - AssertEx.EqualTolerance(1, Force.FromMeganewtons(newton.Meganewtons).Newtons, MeganewtonsTolerance); - AssertEx.EqualTolerance(1, Force.FromMicronewtons(newton.Micronewtons).Newtons, MicronewtonsTolerance); - AssertEx.EqualTolerance(1, Force.FromMillinewtons(newton.Millinewtons).Newtons, MillinewtonsTolerance); - AssertEx.EqualTolerance(1, Force.FromNewtons(newton.Newtons).Newtons, NewtonsTolerance); - AssertEx.EqualTolerance(1, Force.FromOunceForce(newton.OunceForce).Newtons, OunceForceTolerance); - AssertEx.EqualTolerance(1, Force.FromPoundals(newton.Poundals).Newtons, PoundalsTolerance); - AssertEx.EqualTolerance(1, Force.FromPoundsForce(newton.PoundsForce).Newtons, PoundsForceTolerance); - AssertEx.EqualTolerance(1, Force.FromShortTonsForce(newton.ShortTonsForce).Newtons, ShortTonsForceTolerance); - AssertEx.EqualTolerance(1, Force.FromTonnesForce(newton.TonnesForce).Newtons, TonnesForceTolerance); + Force newton = Force.FromNewtons(3); + Assert.Equal(3, Force.FromDecanewtons(newton.Decanewtons).Newtons); + Assert.Equal(3, Force.FromDyne(newton.Dyne).Newtons); + Assert.Equal(3, Force.FromKilogramsForce(newton.KilogramsForce).Newtons); + Assert.Equal(3, Force.FromKilonewtons(newton.Kilonewtons).Newtons); + Assert.Equal(3, Force.FromKiloPonds(newton.KiloPonds).Newtons); + Assert.Equal(3, Force.FromKilopoundsForce(newton.KilopoundsForce).Newtons); + Assert.Equal(3, Force.FromMeganewtons(newton.Meganewtons).Newtons); + Assert.Equal(3, Force.FromMicronewtons(newton.Micronewtons).Newtons); + Assert.Equal(3, Force.FromMillinewtons(newton.Millinewtons).Newtons); + Assert.Equal(3, Force.FromNewtons(newton.Newtons).Newtons); + Assert.Equal(3, Force.FromOunceForce(newton.OunceForce).Newtons); + Assert.Equal(3, Force.FromPoundals(newton.Poundals).Newtons); + Assert.Equal(3, Force.FromPoundsForce(newton.PoundsForce).Newtons); + Assert.Equal(3, Force.FromShortTonsForce(newton.ShortTonsForce).Newtons); + Assert.Equal(3, Force.FromTonnesForce(newton.TonnesForce).Newtons); } [Fact] public void ArithmeticOperators() { Force v = Force.FromNewtons(1); - AssertEx.EqualTolerance(-1, -v.Newtons, NewtonsTolerance); - AssertEx.EqualTolerance(2, (Force.FromNewtons(3)-v).Newtons, NewtonsTolerance); - AssertEx.EqualTolerance(2, (v + v).Newtons, NewtonsTolerance); - AssertEx.EqualTolerance(10, (v*10).Newtons, NewtonsTolerance); - AssertEx.EqualTolerance(10, (10*v).Newtons, NewtonsTolerance); - AssertEx.EqualTolerance(2, (Force.FromNewtons(10)/5).Newtons, NewtonsTolerance); - AssertEx.EqualTolerance(2, Force.FromNewtons(10)/Force.FromNewtons(5), NewtonsTolerance); + Assert.Equal(-1, -v.Newtons); + Assert.Equal(2, (Force.FromNewtons(3) - v).Newtons); + Assert.Equal(2, (v + v).Newtons); + Assert.Equal(10, (v * 10).Newtons); + Assert.Equal(10, (10 * v).Newtons); + Assert.Equal(2, (Force.FromNewtons(10) / 5).Newtons); + Assert.Equal(2, Force.FromNewtons(10) / Force.FromNewtons(5)); } [Fact] @@ -934,8 +951,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ForceUnit.Newton, 1, ForceUnit.Newton, true)] // Same value and unit. [InlineData(1, ForceUnit.Newton, 2, ForceUnit.Newton, false)] // Different value. - [InlineData(2, ForceUnit.Newton, 1, ForceUnit.Decanewton, false)] // Different value and unit. - [InlineData(1, ForceUnit.Newton, 1, ForceUnit.Decanewton, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ForceUnit unitA, double valueB, ForceUnit unitB, bool expectEqual) { var a = new Force(valueA, unitA); @@ -995,8 +1010,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Force.FromNewtons(firstValue); var otherQuantity = Force.FromNewtons(secondValue); Force maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Force.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1015,7 +1030,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1028,6 +1043,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Force.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Force.Info.Units, Force.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Force.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1118,7 +1145,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Force.FromNewtons(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Force), quantity.As(Force.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs index 8976679468..6b5f16a9ef 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/FrequencyTestsBase.g.cs @@ -169,6 +169,20 @@ public void Frequency_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void FrequencyInfo_CreateWithCustomUnitInfos() + { + FrequencyUnit[] expectedUnits = [FrequencyUnit.Hertz]; + + Frequency.FrequencyInfo quantityInfo = Frequency.FrequencyInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Frequency", quantityInfo.Name); + Assert.Equal(Frequency.Zero, quantityInfo.Zero); + Assert.Equal(Frequency.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void HertzToFrequencyUnits() { @@ -362,7 +376,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 с⁻¹", FrequencyUnit.PerSecond, 4.2)] [InlineData("ru-RU", "4,2 рад/с", FrequencyUnit.RadianPerSecond, 4.2)] [InlineData("ru-RU", "4,2 ТГц", FrequencyUnit.Terahertz, 4.2)] - public void Parse(string culture, string quantityString, FrequencyUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, FrequencyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Frequency.Parse(quantityString); @@ -392,7 +406,7 @@ public void Parse(string culture, string quantityString, FrequencyUnit expectedU [InlineData("ru-RU", "4,2 с⁻¹", FrequencyUnit.PerSecond, 4.2)] [InlineData("ru-RU", "4,2 рад/с", FrequencyUnit.RadianPerSecond, 4.2)] [InlineData("ru-RU", "4,2 ТГц", FrequencyUnit.Terahertz, 4.2)] - public void TryParse(string culture, string quantityString, FrequencyUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, FrequencyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Frequency.TryParse(quantityString, out Frequency parsed)); @@ -669,6 +683,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(FrequencyUnit un var quantity = Frequency.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -692,43 +707,45 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(FrequencyUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Frequency hertz = Frequency.FromHertz(1); - AssertEx.EqualTolerance(1, Frequency.FromBeatsPerMinute(hertz.BeatsPerMinute).Hertz, BeatsPerMinuteTolerance); - AssertEx.EqualTolerance(1, Frequency.FromCyclesPerHour(hertz.CyclesPerHour).Hertz, CyclesPerHourTolerance); - AssertEx.EqualTolerance(1, Frequency.FromCyclesPerMinute(hertz.CyclesPerMinute).Hertz, CyclesPerMinuteTolerance); - AssertEx.EqualTolerance(1, Frequency.FromGigahertz(hertz.Gigahertz).Hertz, GigahertzTolerance); - AssertEx.EqualTolerance(1, Frequency.FromHertz(hertz.Hertz).Hertz, HertzTolerance); - AssertEx.EqualTolerance(1, Frequency.FromKilohertz(hertz.Kilohertz).Hertz, KilohertzTolerance); - AssertEx.EqualTolerance(1, Frequency.FromMegahertz(hertz.Megahertz).Hertz, MegahertzTolerance); - AssertEx.EqualTolerance(1, Frequency.FromMicrohertz(hertz.Microhertz).Hertz, MicrohertzTolerance); - AssertEx.EqualTolerance(1, Frequency.FromMillihertz(hertz.Millihertz).Hertz, MillihertzTolerance); - AssertEx.EqualTolerance(1, Frequency.FromPerSecond(hertz.PerSecond).Hertz, PerSecondTolerance); - AssertEx.EqualTolerance(1, Frequency.FromRadiansPerSecond(hertz.RadiansPerSecond).Hertz, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(1, Frequency.FromTerahertz(hertz.Terahertz).Hertz, TerahertzTolerance); + Frequency hertz = Frequency.FromHertz(3); + Assert.Equal(3, Frequency.FromBeatsPerMinute(hertz.BeatsPerMinute).Hertz); + Assert.Equal(3, Frequency.FromCyclesPerHour(hertz.CyclesPerHour).Hertz); + Assert.Equal(3, Frequency.FromCyclesPerMinute(hertz.CyclesPerMinute).Hertz); + Assert.Equal(3, Frequency.FromGigahertz(hertz.Gigahertz).Hertz); + Assert.Equal(3, Frequency.FromHertz(hertz.Hertz).Hertz); + Assert.Equal(3, Frequency.FromKilohertz(hertz.Kilohertz).Hertz); + Assert.Equal(3, Frequency.FromMegahertz(hertz.Megahertz).Hertz); + Assert.Equal(3, Frequency.FromMicrohertz(hertz.Microhertz).Hertz); + Assert.Equal(3, Frequency.FromMillihertz(hertz.Millihertz).Hertz); + Assert.Equal(3, Frequency.FromPerSecond(hertz.PerSecond).Hertz); + Assert.Equal(3, Frequency.FromRadiansPerSecond(hertz.RadiansPerSecond).Hertz); + Assert.Equal(3, Frequency.FromTerahertz(hertz.Terahertz).Hertz); } [Fact] public void ArithmeticOperators() { Frequency v = Frequency.FromHertz(1); - AssertEx.EqualTolerance(-1, -v.Hertz, HertzTolerance); - AssertEx.EqualTolerance(2, (Frequency.FromHertz(3)-v).Hertz, HertzTolerance); - AssertEx.EqualTolerance(2, (v + v).Hertz, HertzTolerance); - AssertEx.EqualTolerance(10, (v*10).Hertz, HertzTolerance); - AssertEx.EqualTolerance(10, (10*v).Hertz, HertzTolerance); - AssertEx.EqualTolerance(2, (Frequency.FromHertz(10)/5).Hertz, HertzTolerance); - AssertEx.EqualTolerance(2, Frequency.FromHertz(10)/Frequency.FromHertz(5), HertzTolerance); + Assert.Equal(-1, -v.Hertz); + Assert.Equal(2, (Frequency.FromHertz(3) - v).Hertz); + Assert.Equal(2, (v + v).Hertz); + Assert.Equal(10, (v * 10).Hertz); + Assert.Equal(10, (10 * v).Hertz); + Assert.Equal(2, (Frequency.FromHertz(10) / 5).Hertz); + Assert.Equal(2, Frequency.FromHertz(10) / Frequency.FromHertz(5)); } [Fact] @@ -774,8 +791,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, FrequencyUnit.Hertz, 1, FrequencyUnit.Hertz, true)] // Same value and unit. [InlineData(1, FrequencyUnit.Hertz, 2, FrequencyUnit.Hertz, false)] // Different value. - [InlineData(2, FrequencyUnit.Hertz, 1, FrequencyUnit.BeatPerMinute, false)] // Different value and unit. - [InlineData(1, FrequencyUnit.Hertz, 1, FrequencyUnit.BeatPerMinute, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, FrequencyUnit unitA, double valueB, FrequencyUnit unitB, bool expectEqual) { var a = new Frequency(valueA, unitA); @@ -835,8 +850,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Frequency.FromHertz(firstValue); var otherQuantity = Frequency.FromHertz(secondValue); Frequency maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Frequency.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -855,7 +870,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -868,6 +883,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Frequency.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Frequency.Info.Units, Frequency.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Frequency.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -952,7 +979,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Frequency.FromHertz(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Frequency), quantity.As(Frequency.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs index ac772ae4d6..9693a30ac0 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/FuelEfficiencyTestsBase.g.cs @@ -137,6 +137,20 @@ public void FuelEfficiency_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void FuelEfficiencyInfo_CreateWithCustomUnitInfos() + { + FuelEfficiencyUnit[] expectedUnits = [FuelEfficiencyUnit.KilometerPerLiter]; + + FuelEfficiency.FuelEfficiencyInfo quantityInfo = FuelEfficiency.FuelEfficiencyInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("FuelEfficiency", quantityInfo.Name); + Assert.Equal(FuelEfficiency.Zero, quantityInfo.Zero); + Assert.Equal(FuelEfficiency.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void KilometerPerLiterToFuelEfficiencyUnits() { @@ -297,7 +311,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 l/100km", FuelEfficiencyUnit.LiterPer100Kilometers, 4.2)] [InlineData("en-US", "4.2 mpg (imp.)", FuelEfficiencyUnit.MilePerUkGallon, 4.2)] [InlineData("en-US", "4.2 mpg (U.S.)", FuelEfficiencyUnit.MilePerUsGallon, 4.2)] - public void Parse(string culture, string quantityString, FuelEfficiencyUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, FuelEfficiencyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = FuelEfficiency.Parse(quantityString); @@ -310,7 +324,7 @@ public void Parse(string culture, string quantityString, FuelEfficiencyUnit expe [InlineData("en-US", "4.2 l/100km", FuelEfficiencyUnit.LiterPer100Kilometers, 4.2)] [InlineData("en-US", "4.2 mpg (imp.)", FuelEfficiencyUnit.MilePerUkGallon, 4.2)] [InlineData("en-US", "4.2 mpg (U.S.)", FuelEfficiencyUnit.MilePerUsGallon, 4.2)] - public void TryParse(string culture, string quantityString, FuelEfficiencyUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, FuelEfficiencyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(FuelEfficiency.TryParse(quantityString, out FuelEfficiency parsed)); @@ -470,6 +484,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(FuelEfficiencyUn var quantity = FuelEfficiency.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -493,35 +508,37 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(FuelEfficiencyUnit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - FuelEfficiency kilometerperliter = FuelEfficiency.FromKilometersPerLiter(1); - AssertEx.EqualTolerance(1, FuelEfficiency.FromKilometersPerLiter(kilometerperliter.KilometersPerLiter).KilometersPerLiter, KilometersPerLiterTolerance); - AssertEx.EqualTolerance(1, FuelEfficiency.FromLitersPer100Kilometers(kilometerperliter.LitersPer100Kilometers).KilometersPerLiter, LitersPer100KilometersTolerance); - AssertEx.EqualTolerance(1, FuelEfficiency.FromMilesPerUkGallon(kilometerperliter.MilesPerUkGallon).KilometersPerLiter, MilesPerUkGallonTolerance); - AssertEx.EqualTolerance(1, FuelEfficiency.FromMilesPerUsGallon(kilometerperliter.MilesPerUsGallon).KilometersPerLiter, MilesPerUsGallonTolerance); + FuelEfficiency kilometerperliter = FuelEfficiency.FromKilometersPerLiter(3); + Assert.Equal(3, FuelEfficiency.FromKilometersPerLiter(kilometerperliter.KilometersPerLiter).KilometersPerLiter); + Assert.Equal(3, FuelEfficiency.FromLitersPer100Kilometers(kilometerperliter.LitersPer100Kilometers).KilometersPerLiter); + Assert.Equal(3, FuelEfficiency.FromMilesPerUkGallon(kilometerperliter.MilesPerUkGallon).KilometersPerLiter); + Assert.Equal(3, FuelEfficiency.FromMilesPerUsGallon(kilometerperliter.MilesPerUsGallon).KilometersPerLiter); } [Fact] public void ArithmeticOperators() { FuelEfficiency v = FuelEfficiency.FromKilometersPerLiter(1); - AssertEx.EqualTolerance(-1, -v.KilometersPerLiter, KilometersPerLiterTolerance); - AssertEx.EqualTolerance(2, (FuelEfficiency.FromKilometersPerLiter(3)-v).KilometersPerLiter, KilometersPerLiterTolerance); - AssertEx.EqualTolerance(2, (v + v).KilometersPerLiter, KilometersPerLiterTolerance); - AssertEx.EqualTolerance(10, (v*10).KilometersPerLiter, KilometersPerLiterTolerance); - AssertEx.EqualTolerance(10, (10*v).KilometersPerLiter, KilometersPerLiterTolerance); - AssertEx.EqualTolerance(2, (FuelEfficiency.FromKilometersPerLiter(10)/5).KilometersPerLiter, KilometersPerLiterTolerance); - AssertEx.EqualTolerance(2, FuelEfficiency.FromKilometersPerLiter(10)/FuelEfficiency.FromKilometersPerLiter(5), KilometersPerLiterTolerance); + Assert.Equal(-1, -v.KilometersPerLiter); + Assert.Equal(2, (FuelEfficiency.FromKilometersPerLiter(3) - v).KilometersPerLiter); + Assert.Equal(2, (v + v).KilometersPerLiter); + Assert.Equal(10, (v * 10).KilometersPerLiter); + Assert.Equal(10, (10 * v).KilometersPerLiter); + Assert.Equal(2, (FuelEfficiency.FromKilometersPerLiter(10) / 5).KilometersPerLiter); + Assert.Equal(2, FuelEfficiency.FromKilometersPerLiter(10) / FuelEfficiency.FromKilometersPerLiter(5)); } [Fact] @@ -567,8 +584,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, FuelEfficiencyUnit.KilometerPerLiter, 1, FuelEfficiencyUnit.KilometerPerLiter, true)] // Same value and unit. [InlineData(1, FuelEfficiencyUnit.KilometerPerLiter, 2, FuelEfficiencyUnit.KilometerPerLiter, false)] // Different value. - [InlineData(2, FuelEfficiencyUnit.KilometerPerLiter, 1, FuelEfficiencyUnit.LiterPer100Kilometers, false)] // Different value and unit. - [InlineData(1, FuelEfficiencyUnit.KilometerPerLiter, 1, FuelEfficiencyUnit.LiterPer100Kilometers, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, FuelEfficiencyUnit unitA, double valueB, FuelEfficiencyUnit unitB, bool expectEqual) { var a = new FuelEfficiency(valueA, unitA); @@ -628,8 +643,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = FuelEfficiency.FromKilometersPerLiter(firstValue); var otherQuantity = FuelEfficiency.FromKilometersPerLiter(secondValue); FuelEfficiency maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, FuelEfficiency.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -648,7 +663,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -661,6 +676,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(FuelEfficiency.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(FuelEfficiency.Info.Units, FuelEfficiency.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, FuelEfficiency.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -729,7 +756,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = FuelEfficiency.FromKilometersPerLiter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(FuelEfficiency), quantity.As(FuelEfficiency.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs index 16ac1f38a9..699d7f8dd8 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatFluxTestsBase.g.cs @@ -193,6 +193,20 @@ public void HeatFlux_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void HeatFluxInfo_CreateWithCustomUnitInfos() + { + HeatFluxUnit[] expectedUnits = [HeatFluxUnit.WattPerSquareMeter]; + + HeatFlux.HeatFluxInfo quantityInfo = HeatFlux.HeatFluxInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("HeatFlux", quantityInfo.Name); + Assert.Equal(HeatFlux.Zero, quantityInfo.Zero); + Assert.Equal(HeatFlux.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void WattPerSquareMeterToHeatFluxUnits() { @@ -396,7 +410,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 W/ft²", HeatFluxUnit.WattPerSquareFoot, 4.2)] [InlineData("en-US", "4.2 W/in²", HeatFluxUnit.WattPerSquareInch, 4.2)] [InlineData("en-US", "4.2 W/m²", HeatFluxUnit.WattPerSquareMeter, 4.2)] - public void Parse(string culture, string quantityString, HeatFluxUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, HeatFluxUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = HeatFlux.Parse(quantityString); @@ -424,7 +438,7 @@ public void Parse(string culture, string quantityString, HeatFluxUnit expectedUn [InlineData("en-US", "4.2 W/ft²", HeatFluxUnit.WattPerSquareFoot, 4.2)] [InlineData("en-US", "4.2 W/in²", HeatFluxUnit.WattPerSquareInch, 4.2)] [InlineData("en-US", "4.2 W/m²", HeatFluxUnit.WattPerSquareMeter, 4.2)] - public void TryParse(string culture, string quantityString, HeatFluxUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, HeatFluxUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(HeatFlux.TryParse(quantityString, out HeatFlux parsed)); @@ -718,6 +732,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(HeatFluxUnit uni var quantity = HeatFlux.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -741,49 +756,51 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(HeatFluxUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - HeatFlux wattpersquaremeter = HeatFlux.FromWattsPerSquareMeter(1); - AssertEx.EqualTolerance(1, HeatFlux.FromBtusPerHourSquareFoot(wattpersquaremeter.BtusPerHourSquareFoot).WattsPerSquareMeter, BtusPerHourSquareFootTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromBtusPerMinuteSquareFoot(wattpersquaremeter.BtusPerMinuteSquareFoot).WattsPerSquareMeter, BtusPerMinuteSquareFootTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromBtusPerSecondSquareFoot(wattpersquaremeter.BtusPerSecondSquareFoot).WattsPerSquareMeter, BtusPerSecondSquareFootTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromBtusPerSecondSquareInch(wattpersquaremeter.BtusPerSecondSquareInch).WattsPerSquareMeter, BtusPerSecondSquareInchTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromCaloriesPerSecondSquareCentimeter(wattpersquaremeter.CaloriesPerSecondSquareCentimeter).WattsPerSquareMeter, CaloriesPerSecondSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromCentiwattsPerSquareMeter(wattpersquaremeter.CentiwattsPerSquareMeter).WattsPerSquareMeter, CentiwattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromDeciwattsPerSquareMeter(wattpersquaremeter.DeciwattsPerSquareMeter).WattsPerSquareMeter, DeciwattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromKilocaloriesPerHourSquareMeter(wattpersquaremeter.KilocaloriesPerHourSquareMeter).WattsPerSquareMeter, KilocaloriesPerHourSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromKilocaloriesPerSecondSquareCentimeter(wattpersquaremeter.KilocaloriesPerSecondSquareCentimeter).WattsPerSquareMeter, KilocaloriesPerSecondSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromKilowattsPerSquareMeter(wattpersquaremeter.KilowattsPerSquareMeter).WattsPerSquareMeter, KilowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromMicrowattsPerSquareMeter(wattpersquaremeter.MicrowattsPerSquareMeter).WattsPerSquareMeter, MicrowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromMilliwattsPerSquareMeter(wattpersquaremeter.MilliwattsPerSquareMeter).WattsPerSquareMeter, MilliwattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromNanowattsPerSquareMeter(wattpersquaremeter.NanowattsPerSquareMeter).WattsPerSquareMeter, NanowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromPoundsForcePerFootSecond(wattpersquaremeter.PoundsForcePerFootSecond).WattsPerSquareMeter, PoundsForcePerFootSecondTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromPoundsPerSecondCubed(wattpersquaremeter.PoundsPerSecondCubed).WattsPerSquareMeter, PoundsPerSecondCubedTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromWattsPerSquareFoot(wattpersquaremeter.WattsPerSquareFoot).WattsPerSquareMeter, WattsPerSquareFootTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromWattsPerSquareInch(wattpersquaremeter.WattsPerSquareInch).WattsPerSquareMeter, WattsPerSquareInchTolerance); - AssertEx.EqualTolerance(1, HeatFlux.FromWattsPerSquareMeter(wattpersquaremeter.WattsPerSquareMeter).WattsPerSquareMeter, WattsPerSquareMeterTolerance); + HeatFlux wattpersquaremeter = HeatFlux.FromWattsPerSquareMeter(3); + Assert.Equal(3, HeatFlux.FromBtusPerHourSquareFoot(wattpersquaremeter.BtusPerHourSquareFoot).WattsPerSquareMeter); + Assert.Equal(3, HeatFlux.FromBtusPerMinuteSquareFoot(wattpersquaremeter.BtusPerMinuteSquareFoot).WattsPerSquareMeter); + Assert.Equal(3, HeatFlux.FromBtusPerSecondSquareFoot(wattpersquaremeter.BtusPerSecondSquareFoot).WattsPerSquareMeter); + Assert.Equal(3, HeatFlux.FromBtusPerSecondSquareInch(wattpersquaremeter.BtusPerSecondSquareInch).WattsPerSquareMeter); + Assert.Equal(3, HeatFlux.FromCaloriesPerSecondSquareCentimeter(wattpersquaremeter.CaloriesPerSecondSquareCentimeter).WattsPerSquareMeter); + Assert.Equal(3, HeatFlux.FromCentiwattsPerSquareMeter(wattpersquaremeter.CentiwattsPerSquareMeter).WattsPerSquareMeter); + Assert.Equal(3, HeatFlux.FromDeciwattsPerSquareMeter(wattpersquaremeter.DeciwattsPerSquareMeter).WattsPerSquareMeter); + Assert.Equal(3, HeatFlux.FromKilocaloriesPerHourSquareMeter(wattpersquaremeter.KilocaloriesPerHourSquareMeter).WattsPerSquareMeter); + Assert.Equal(3, HeatFlux.FromKilocaloriesPerSecondSquareCentimeter(wattpersquaremeter.KilocaloriesPerSecondSquareCentimeter).WattsPerSquareMeter); + Assert.Equal(3, HeatFlux.FromKilowattsPerSquareMeter(wattpersquaremeter.KilowattsPerSquareMeter).WattsPerSquareMeter); + Assert.Equal(3, HeatFlux.FromMicrowattsPerSquareMeter(wattpersquaremeter.MicrowattsPerSquareMeter).WattsPerSquareMeter); + Assert.Equal(3, HeatFlux.FromMilliwattsPerSquareMeter(wattpersquaremeter.MilliwattsPerSquareMeter).WattsPerSquareMeter); + Assert.Equal(3, HeatFlux.FromNanowattsPerSquareMeter(wattpersquaremeter.NanowattsPerSquareMeter).WattsPerSquareMeter); + Assert.Equal(3, HeatFlux.FromPoundsForcePerFootSecond(wattpersquaremeter.PoundsForcePerFootSecond).WattsPerSquareMeter); + Assert.Equal(3, HeatFlux.FromPoundsPerSecondCubed(wattpersquaremeter.PoundsPerSecondCubed).WattsPerSquareMeter); + Assert.Equal(3, HeatFlux.FromWattsPerSquareFoot(wattpersquaremeter.WattsPerSquareFoot).WattsPerSquareMeter); + Assert.Equal(3, HeatFlux.FromWattsPerSquareInch(wattpersquaremeter.WattsPerSquareInch).WattsPerSquareMeter); + Assert.Equal(3, HeatFlux.FromWattsPerSquareMeter(wattpersquaremeter.WattsPerSquareMeter).WattsPerSquareMeter); } [Fact] public void ArithmeticOperators() { HeatFlux v = HeatFlux.FromWattsPerSquareMeter(1); - AssertEx.EqualTolerance(-1, -v.WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (HeatFlux.FromWattsPerSquareMeter(3)-v).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (HeatFlux.FromWattsPerSquareMeter(10)/5).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, HeatFlux.FromWattsPerSquareMeter(10)/HeatFlux.FromWattsPerSquareMeter(5), WattsPerSquareMeterTolerance); + Assert.Equal(-1, -v.WattsPerSquareMeter); + Assert.Equal(2, (HeatFlux.FromWattsPerSquareMeter(3) - v).WattsPerSquareMeter); + Assert.Equal(2, (v + v).WattsPerSquareMeter); + Assert.Equal(10, (v * 10).WattsPerSquareMeter); + Assert.Equal(10, (10 * v).WattsPerSquareMeter); + Assert.Equal(2, (HeatFlux.FromWattsPerSquareMeter(10) / 5).WattsPerSquareMeter); + Assert.Equal(2, HeatFlux.FromWattsPerSquareMeter(10) / HeatFlux.FromWattsPerSquareMeter(5)); } [Fact] @@ -829,8 +846,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, HeatFluxUnit.WattPerSquareMeter, 1, HeatFluxUnit.WattPerSquareMeter, true)] // Same value and unit. [InlineData(1, HeatFluxUnit.WattPerSquareMeter, 2, HeatFluxUnit.WattPerSquareMeter, false)] // Different value. - [InlineData(2, HeatFluxUnit.WattPerSquareMeter, 1, HeatFluxUnit.BtuPerHourSquareFoot, false)] // Different value and unit. - [InlineData(1, HeatFluxUnit.WattPerSquareMeter, 1, HeatFluxUnit.BtuPerHourSquareFoot, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, HeatFluxUnit unitA, double valueB, HeatFluxUnit unitB, bool expectEqual) { var a = new HeatFlux(valueA, unitA); @@ -890,8 +905,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = HeatFlux.FromWattsPerSquareMeter(firstValue); var otherQuantity = HeatFlux.FromWattsPerSquareMeter(secondValue); HeatFlux maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, HeatFlux.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -910,7 +925,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -923,6 +938,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(HeatFlux.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(HeatFlux.Info.Units, HeatFlux.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, HeatFlux.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1019,7 +1046,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = HeatFlux.FromWattsPerSquareMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(HeatFlux), quantity.As(HeatFlux.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs index 045cb75a2e..0bf7fc9acc 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/HeatTransferCoefficientTestsBase.g.cs @@ -141,6 +141,20 @@ public void HeatTransferCoefficient_QuantityInfo_ReturnsQuantityInfoDescribingQu Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void HeatTransferCoefficientInfo_CreateWithCustomUnitInfos() + { + HeatTransferCoefficientUnit[] expectedUnits = [HeatTransferCoefficientUnit.WattPerSquareMeterKelvin]; + + HeatTransferCoefficient.HeatTransferCoefficientInfo quantityInfo = HeatTransferCoefficient.HeatTransferCoefficientInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("HeatTransferCoefficient", quantityInfo.Name); + Assert.Equal(HeatTransferCoefficient.Zero, quantityInfo.Zero); + Assert.Equal(HeatTransferCoefficient.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void WattPerSquareMeterKelvinToHeatTransferCoefficientUnits() { @@ -313,7 +327,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 kkcal/(m²·hr·°C)", HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, 4.2)] [InlineData("en-US", "4.2 W/(m²·°C)", HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, 4.2)] [InlineData("en-US", "4.2 W/(m²·K)", HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, 4.2)] - public void Parse(string culture, string quantityString, HeatTransferCoefficientUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, HeatTransferCoefficientUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = HeatTransferCoefficient.Parse(quantityString); @@ -336,7 +350,7 @@ public void Parse(string culture, string quantityString, HeatTransferCoefficient [InlineData("en-US", "4.2 kkcal/(m²·hr·°C)", HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, 4.2)] [InlineData("en-US", "4.2 W/(m²·°C)", HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, 4.2)] [InlineData("en-US", "4.2 W/(m²·K)", HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, 4.2)] - public void TryParse(string culture, string quantityString, HeatTransferCoefficientUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, HeatTransferCoefficientUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(HeatTransferCoefficient.TryParse(quantityString, out HeatTransferCoefficient parsed)); @@ -577,6 +591,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(HeatTransferCoef var quantity = HeatTransferCoefficient.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -600,36 +615,38 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(HeatTransferCoeffic IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - AssertEx.EqualTolerance(1, HeatTransferCoefficient.FromBtusPerHourSquareFootDegreeFahrenheit(wattpersquaremeterkelvin.BtusPerHourSquareFootDegreeFahrenheit).WattsPerSquareMeterKelvin, BtusPerHourSquareFootDegreeFahrenheitTolerance); - AssertEx.EqualTolerance(1, HeatTransferCoefficient.FromCaloriesPerHourSquareMeterDegreeCelsius(wattpersquaremeterkelvin.CaloriesPerHourSquareMeterDegreeCelsius).WattsPerSquareMeterKelvin, CaloriesPerHourSquareMeterDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, HeatTransferCoefficient.FromKilocaloriesPerHourSquareMeterDegreeCelsius(wattpersquaremeterkelvin.KilocaloriesPerHourSquareMeterDegreeCelsius).WattsPerSquareMeterKelvin, KilocaloriesPerHourSquareMeterDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, HeatTransferCoefficient.FromWattsPerSquareMeterCelsius(wattpersquaremeterkelvin.WattsPerSquareMeterCelsius).WattsPerSquareMeterKelvin, WattsPerSquareMeterCelsiusTolerance); - AssertEx.EqualTolerance(1, HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(wattpersquaremeterkelvin.WattsPerSquareMeterKelvin).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); + HeatTransferCoefficient wattpersquaremeterkelvin = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(3); + Assert.Equal(3, HeatTransferCoefficient.FromBtusPerHourSquareFootDegreeFahrenheit(wattpersquaremeterkelvin.BtusPerHourSquareFootDegreeFahrenheit).WattsPerSquareMeterKelvin); + Assert.Equal(3, HeatTransferCoefficient.FromCaloriesPerHourSquareMeterDegreeCelsius(wattpersquaremeterkelvin.CaloriesPerHourSquareMeterDegreeCelsius).WattsPerSquareMeterKelvin); + Assert.Equal(3, HeatTransferCoefficient.FromKilocaloriesPerHourSquareMeterDegreeCelsius(wattpersquaremeterkelvin.KilocaloriesPerHourSquareMeterDegreeCelsius).WattsPerSquareMeterKelvin); + Assert.Equal(3, HeatTransferCoefficient.FromWattsPerSquareMeterCelsius(wattpersquaremeterkelvin.WattsPerSquareMeterCelsius).WattsPerSquareMeterKelvin); + Assert.Equal(3, HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(wattpersquaremeterkelvin.WattsPerSquareMeterKelvin).WattsPerSquareMeterKelvin); } [Fact] public void ArithmeticOperators() { HeatTransferCoefficient v = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1); - AssertEx.EqualTolerance(-1, -v.WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); - AssertEx.EqualTolerance(2, (HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(3)-v).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); - AssertEx.EqualTolerance(2, (v + v).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); - AssertEx.EqualTolerance(10, (v*10).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); - AssertEx.EqualTolerance(10, (10*v).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); - AssertEx.EqualTolerance(2, (HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(10)/5).WattsPerSquareMeterKelvin, WattsPerSquareMeterKelvinTolerance); - AssertEx.EqualTolerance(2, HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(10)/HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(5), WattsPerSquareMeterKelvinTolerance); + Assert.Equal(-1, -v.WattsPerSquareMeterKelvin); + Assert.Equal(2, (HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(3) - v).WattsPerSquareMeterKelvin); + Assert.Equal(2, (v + v).WattsPerSquareMeterKelvin); + Assert.Equal(10, (v * 10).WattsPerSquareMeterKelvin); + Assert.Equal(10, (10 * v).WattsPerSquareMeterKelvin); + Assert.Equal(2, (HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(10) / 5).WattsPerSquareMeterKelvin); + Assert.Equal(2, HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(10) / HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(5)); } [Fact] @@ -675,8 +692,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, 1, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, true)] // Same value and unit. [InlineData(1, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, 2, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, false)] // Different value. - [InlineData(2, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, 1, HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, false)] // Different value and unit. - [InlineData(1, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, 1, HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, HeatTransferCoefficientUnit unitA, double valueB, HeatTransferCoefficientUnit unitB, bool expectEqual) { var a = new HeatTransferCoefficient(valueA, unitA); @@ -736,8 +751,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(firstValue); var otherQuantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(secondValue); HeatTransferCoefficient maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, HeatTransferCoefficient.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -756,7 +771,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -769,6 +784,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(HeatTransferCoefficient.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(HeatTransferCoefficient.Info.Units, HeatTransferCoefficient.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, HeatTransferCoefficient.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -839,7 +866,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = HeatTransferCoefficient.FromWattsPerSquareMeterKelvin(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(HeatTransferCoefficient), quantity.As(HeatTransferCoefficient.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs index 0f40c21957..e858c67dba 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/IlluminanceTestsBase.g.cs @@ -137,6 +137,20 @@ public void Illuminance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void IlluminanceInfo_CreateWithCustomUnitInfos() + { + IlluminanceUnit[] expectedUnits = [IlluminanceUnit.Lux]; + + Illuminance.IlluminanceInfo quantityInfo = Illuminance.IlluminanceInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Illuminance", quantityInfo.Name); + Assert.Equal(Illuminance.Zero, quantityInfo.Zero); + Assert.Equal(Illuminance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void LuxToIlluminanceUnits() { @@ -297,7 +311,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 lx", IlluminanceUnit.Lux, 4.2)] [InlineData("en-US", "4.2 Mlx", IlluminanceUnit.Megalux, 4.2)] [InlineData("en-US", "4.2 mlx", IlluminanceUnit.Millilux, 4.2)] - public void Parse(string culture, string quantityString, IlluminanceUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, IlluminanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Illuminance.Parse(quantityString); @@ -310,7 +324,7 @@ public void Parse(string culture, string quantityString, IlluminanceUnit expecte [InlineData("en-US", "4.2 lx", IlluminanceUnit.Lux, 4.2)] [InlineData("en-US", "4.2 Mlx", IlluminanceUnit.Megalux, 4.2)] [InlineData("en-US", "4.2 mlx", IlluminanceUnit.Millilux, 4.2)] - public void TryParse(string culture, string quantityString, IlluminanceUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, IlluminanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Illuminance.TryParse(quantityString, out Illuminance parsed)); @@ -470,6 +484,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(IlluminanceUnit var quantity = Illuminance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -493,35 +508,37 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(IlluminanceUnit uni IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Illuminance lux = Illuminance.FromLux(1); - AssertEx.EqualTolerance(1, Illuminance.FromKilolux(lux.Kilolux).Lux, KiloluxTolerance); - AssertEx.EqualTolerance(1, Illuminance.FromLux(lux.Lux).Lux, LuxTolerance); - AssertEx.EqualTolerance(1, Illuminance.FromMegalux(lux.Megalux).Lux, MegaluxTolerance); - AssertEx.EqualTolerance(1, Illuminance.FromMillilux(lux.Millilux).Lux, MilliluxTolerance); + Illuminance lux = Illuminance.FromLux(3); + Assert.Equal(3, Illuminance.FromKilolux(lux.Kilolux).Lux); + Assert.Equal(3, Illuminance.FromLux(lux.Lux).Lux); + Assert.Equal(3, Illuminance.FromMegalux(lux.Megalux).Lux); + Assert.Equal(3, Illuminance.FromMillilux(lux.Millilux).Lux); } [Fact] public void ArithmeticOperators() { Illuminance v = Illuminance.FromLux(1); - AssertEx.EqualTolerance(-1, -v.Lux, LuxTolerance); - AssertEx.EqualTolerance(2, (Illuminance.FromLux(3)-v).Lux, LuxTolerance); - AssertEx.EqualTolerance(2, (v + v).Lux, LuxTolerance); - AssertEx.EqualTolerance(10, (v*10).Lux, LuxTolerance); - AssertEx.EqualTolerance(10, (10*v).Lux, LuxTolerance); - AssertEx.EqualTolerance(2, (Illuminance.FromLux(10)/5).Lux, LuxTolerance); - AssertEx.EqualTolerance(2, Illuminance.FromLux(10)/Illuminance.FromLux(5), LuxTolerance); + Assert.Equal(-1, -v.Lux); + Assert.Equal(2, (Illuminance.FromLux(3) - v).Lux); + Assert.Equal(2, (v + v).Lux); + Assert.Equal(10, (v * 10).Lux); + Assert.Equal(10, (10 * v).Lux); + Assert.Equal(2, (Illuminance.FromLux(10) / 5).Lux); + Assert.Equal(2, Illuminance.FromLux(10) / Illuminance.FromLux(5)); } [Fact] @@ -567,8 +584,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, IlluminanceUnit.Lux, 1, IlluminanceUnit.Lux, true)] // Same value and unit. [InlineData(1, IlluminanceUnit.Lux, 2, IlluminanceUnit.Lux, false)] // Different value. - [InlineData(2, IlluminanceUnit.Lux, 1, IlluminanceUnit.Kilolux, false)] // Different value and unit. - [InlineData(1, IlluminanceUnit.Lux, 1, IlluminanceUnit.Kilolux, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, IlluminanceUnit unitA, double valueB, IlluminanceUnit unitB, bool expectEqual) { var a = new Illuminance(valueA, unitA); @@ -628,8 +643,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Illuminance.FromLux(firstValue); var otherQuantity = Illuminance.FromLux(secondValue); Illuminance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Illuminance.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -648,7 +663,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -661,6 +676,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Illuminance.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Illuminance.Info.Units, Illuminance.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Illuminance.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -729,7 +756,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Illuminance.FromLux(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Illuminance), quantity.As(Illuminance.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ImpulseTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ImpulseTestsBase.g.cs index 56fa4efebd..8355c9db58 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ImpulseTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ImpulseTestsBase.g.cs @@ -173,6 +173,20 @@ public void Impulse_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ImpulseInfo_CreateWithCustomUnitInfos() + { + ImpulseUnit[] expectedUnits = [ImpulseUnit.NewtonSecond]; + + Impulse.ImpulseInfo quantityInfo = Impulse.ImpulseInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Impulse", quantityInfo.Name); + Assert.Equal(Impulse.Zero, quantityInfo.Zero); + Assert.Equal(Impulse.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void NewtonSecondToImpulseUnits() { @@ -360,7 +374,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 lb·ft/s", ImpulseUnit.PoundFootPerSecond, 4.2)] [InlineData("en-US", "4.2 lbf·s", ImpulseUnit.PoundForceSecond, 4.2)] [InlineData("en-US", "4.2 slug·ft/s", ImpulseUnit.SlugFootPerSecond, 4.2)] - public void Parse(string culture, string quantityString, ImpulseUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ImpulseUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Impulse.Parse(quantityString); @@ -382,7 +396,7 @@ public void Parse(string culture, string quantityString, ImpulseUnit expectedUni [InlineData("en-US", "4.2 lb·ft/s", ImpulseUnit.PoundFootPerSecond, 4.2)] [InlineData("en-US", "4.2 lbf·s", ImpulseUnit.PoundForceSecond, 4.2)] [InlineData("en-US", "4.2 slug·ft/s", ImpulseUnit.SlugFootPerSecond, 4.2)] - public void TryParse(string culture, string quantityString, ImpulseUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ImpulseUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Impulse.TryParse(quantityString, out Impulse parsed)); @@ -623,6 +637,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ImpulseUnit unit var quantity = Impulse.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -646,44 +661,46 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ImpulseUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Impulse newtonsecond = Impulse.FromNewtonSeconds(1); - AssertEx.EqualTolerance(1, Impulse.FromCentinewtonSeconds(newtonsecond.CentinewtonSeconds).NewtonSeconds, CentinewtonSecondsTolerance); - AssertEx.EqualTolerance(1, Impulse.FromDecanewtonSeconds(newtonsecond.DecanewtonSeconds).NewtonSeconds, DecanewtonSecondsTolerance); - AssertEx.EqualTolerance(1, Impulse.FromDecinewtonSeconds(newtonsecond.DecinewtonSeconds).NewtonSeconds, DecinewtonSecondsTolerance); - AssertEx.EqualTolerance(1, Impulse.FromKilogramMetersPerSecond(newtonsecond.KilogramMetersPerSecond).NewtonSeconds, KilogramMetersPerSecondTolerance); - AssertEx.EqualTolerance(1, Impulse.FromKilonewtonSeconds(newtonsecond.KilonewtonSeconds).NewtonSeconds, KilonewtonSecondsTolerance); - AssertEx.EqualTolerance(1, Impulse.FromMeganewtonSeconds(newtonsecond.MeganewtonSeconds).NewtonSeconds, MeganewtonSecondsTolerance); - AssertEx.EqualTolerance(1, Impulse.FromMicronewtonSeconds(newtonsecond.MicronewtonSeconds).NewtonSeconds, MicronewtonSecondsTolerance); - AssertEx.EqualTolerance(1, Impulse.FromMillinewtonSeconds(newtonsecond.MillinewtonSeconds).NewtonSeconds, MillinewtonSecondsTolerance); - AssertEx.EqualTolerance(1, Impulse.FromNanonewtonSeconds(newtonsecond.NanonewtonSeconds).NewtonSeconds, NanonewtonSecondsTolerance); - AssertEx.EqualTolerance(1, Impulse.FromNewtonSeconds(newtonsecond.NewtonSeconds).NewtonSeconds, NewtonSecondsTolerance); - AssertEx.EqualTolerance(1, Impulse.FromPoundFeetPerSecond(newtonsecond.PoundFeetPerSecond).NewtonSeconds, PoundFeetPerSecondTolerance); - AssertEx.EqualTolerance(1, Impulse.FromPoundForceSeconds(newtonsecond.PoundForceSeconds).NewtonSeconds, PoundForceSecondsTolerance); - AssertEx.EqualTolerance(1, Impulse.FromSlugFeetPerSecond(newtonsecond.SlugFeetPerSecond).NewtonSeconds, SlugFeetPerSecondTolerance); + Impulse newtonsecond = Impulse.FromNewtonSeconds(3); + Assert.Equal(3, Impulse.FromCentinewtonSeconds(newtonsecond.CentinewtonSeconds).NewtonSeconds); + Assert.Equal(3, Impulse.FromDecanewtonSeconds(newtonsecond.DecanewtonSeconds).NewtonSeconds); + Assert.Equal(3, Impulse.FromDecinewtonSeconds(newtonsecond.DecinewtonSeconds).NewtonSeconds); + Assert.Equal(3, Impulse.FromKilogramMetersPerSecond(newtonsecond.KilogramMetersPerSecond).NewtonSeconds); + Assert.Equal(3, Impulse.FromKilonewtonSeconds(newtonsecond.KilonewtonSeconds).NewtonSeconds); + Assert.Equal(3, Impulse.FromMeganewtonSeconds(newtonsecond.MeganewtonSeconds).NewtonSeconds); + Assert.Equal(3, Impulse.FromMicronewtonSeconds(newtonsecond.MicronewtonSeconds).NewtonSeconds); + Assert.Equal(3, Impulse.FromMillinewtonSeconds(newtonsecond.MillinewtonSeconds).NewtonSeconds); + Assert.Equal(3, Impulse.FromNanonewtonSeconds(newtonsecond.NanonewtonSeconds).NewtonSeconds); + Assert.Equal(3, Impulse.FromNewtonSeconds(newtonsecond.NewtonSeconds).NewtonSeconds); + Assert.Equal(3, Impulse.FromPoundFeetPerSecond(newtonsecond.PoundFeetPerSecond).NewtonSeconds); + Assert.Equal(3, Impulse.FromPoundForceSeconds(newtonsecond.PoundForceSeconds).NewtonSeconds); + Assert.Equal(3, Impulse.FromSlugFeetPerSecond(newtonsecond.SlugFeetPerSecond).NewtonSeconds); } [Fact] public void ArithmeticOperators() { Impulse v = Impulse.FromNewtonSeconds(1); - AssertEx.EqualTolerance(-1, -v.NewtonSeconds, NewtonSecondsTolerance); - AssertEx.EqualTolerance(2, (Impulse.FromNewtonSeconds(3)-v).NewtonSeconds, NewtonSecondsTolerance); - AssertEx.EqualTolerance(2, (v + v).NewtonSeconds, NewtonSecondsTolerance); - AssertEx.EqualTolerance(10, (v*10).NewtonSeconds, NewtonSecondsTolerance); - AssertEx.EqualTolerance(10, (10*v).NewtonSeconds, NewtonSecondsTolerance); - AssertEx.EqualTolerance(2, (Impulse.FromNewtonSeconds(10)/5).NewtonSeconds, NewtonSecondsTolerance); - AssertEx.EqualTolerance(2, Impulse.FromNewtonSeconds(10)/Impulse.FromNewtonSeconds(5), NewtonSecondsTolerance); + Assert.Equal(-1, -v.NewtonSeconds); + Assert.Equal(2, (Impulse.FromNewtonSeconds(3) - v).NewtonSeconds); + Assert.Equal(2, (v + v).NewtonSeconds); + Assert.Equal(10, (v * 10).NewtonSeconds); + Assert.Equal(10, (10 * v).NewtonSeconds); + Assert.Equal(2, (Impulse.FromNewtonSeconds(10) / 5).NewtonSeconds); + Assert.Equal(2, Impulse.FromNewtonSeconds(10) / Impulse.FromNewtonSeconds(5)); } [Fact] @@ -729,8 +746,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ImpulseUnit.NewtonSecond, 1, ImpulseUnit.NewtonSecond, true)] // Same value and unit. [InlineData(1, ImpulseUnit.NewtonSecond, 2, ImpulseUnit.NewtonSecond, false)] // Different value. - [InlineData(2, ImpulseUnit.NewtonSecond, 1, ImpulseUnit.CentinewtonSecond, false)] // Different value and unit. - [InlineData(1, ImpulseUnit.NewtonSecond, 1, ImpulseUnit.CentinewtonSecond, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ImpulseUnit unitA, double valueB, ImpulseUnit unitB, bool expectEqual) { var a = new Impulse(valueA, unitA); @@ -790,8 +805,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Impulse.FromNewtonSeconds(firstValue); var otherQuantity = Impulse.FromNewtonSeconds(secondValue); Impulse maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Impulse.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -810,7 +825,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -823,6 +838,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Impulse.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Impulse.Info.Units, Impulse.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Impulse.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -909,7 +936,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Impulse.FromNewtonSeconds(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Impulse), quantity.As(Impulse.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs index a35abcd79e..efd180daa1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/InformationTestsBase.g.cs @@ -256,6 +256,20 @@ public void Information_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void InformationInfo_CreateWithCustomUnitInfos() + { + InformationUnit[] expectedUnits = [InformationUnit.Bit]; + + Information.InformationInfo quantityInfo = Information.InformationInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Information", quantityInfo.Name); + Assert.Equal(Information.Zero, quantityInfo.Zero); + Assert.Equal(Information.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void BitToInformationUnits() { @@ -482,7 +496,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() [InlineData("en-US", "4.2 Tb", InformationUnit.Terabit, 4.2)] [InlineData("en-US", "4.2 TB", InformationUnit.Terabyte, 4.2)] [InlineData("en-US", "4.2 To", InformationUnit.Teraoctet, 4.2)] - public void Parse(string culture, string quantityString, InformationUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, InformationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Information.Parse(quantityString); @@ -530,7 +544,7 @@ public void Parse(string culture, string quantityString, InformationUnit expecte [InlineData("en-US", "4.2 Tb", InformationUnit.Terabit, 4.2)] [InlineData("en-US", "4.2 TB", InformationUnit.Terabyte, 4.2)] [InlineData("en-US", "4.2 To", InformationUnit.Teraoctet, 4.2)] - public void TryParse(string culture, string quantityString, InformationUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, InformationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Information.TryParse(quantityString, out Information parsed)); @@ -1005,6 +1019,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(InformationUnit var quantity = Information.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -1028,70 +1043,72 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(InformationUnit uni IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Information bit = Information.FromBits(1); - AssertEx.EqualTolerance(1, Information.FromBits(bit.Bits).Bits, BitsTolerance); - AssertEx.EqualTolerance(1, Information.FromBytes(bit.Bytes).Bits, BytesTolerance); - AssertEx.EqualTolerance(1, Information.FromExabits(bit.Exabits).Bits, ExabitsTolerance); - AssertEx.EqualTolerance(1, Information.FromExabytes(bit.Exabytes).Bits, ExabytesTolerance); - AssertEx.EqualTolerance(1, Information.FromExaoctets(bit.Exaoctets).Bits, ExaoctetsTolerance); - AssertEx.EqualTolerance(1, Information.FromExbibits(bit.Exbibits).Bits, ExbibitsTolerance); - AssertEx.EqualTolerance(1, Information.FromExbibytes(bit.Exbibytes).Bits, ExbibytesTolerance); - AssertEx.EqualTolerance(1, Information.FromExbioctets(bit.Exbioctets).Bits, ExbioctetsTolerance); - AssertEx.EqualTolerance(1, Information.FromGibibits(bit.Gibibits).Bits, GibibitsTolerance); - AssertEx.EqualTolerance(1, Information.FromGibibytes(bit.Gibibytes).Bits, GibibytesTolerance); - AssertEx.EqualTolerance(1, Information.FromGibioctets(bit.Gibioctets).Bits, GibioctetsTolerance); - AssertEx.EqualTolerance(1, Information.FromGigabits(bit.Gigabits).Bits, GigabitsTolerance); - AssertEx.EqualTolerance(1, Information.FromGigabytes(bit.Gigabytes).Bits, GigabytesTolerance); - AssertEx.EqualTolerance(1, Information.FromGigaoctets(bit.Gigaoctets).Bits, GigaoctetsTolerance); - AssertEx.EqualTolerance(1, Information.FromKibibits(bit.Kibibits).Bits, KibibitsTolerance); - AssertEx.EqualTolerance(1, Information.FromKibibytes(bit.Kibibytes).Bits, KibibytesTolerance); - AssertEx.EqualTolerance(1, Information.FromKibioctets(bit.Kibioctets).Bits, KibioctetsTolerance); - AssertEx.EqualTolerance(1, Information.FromKilobits(bit.Kilobits).Bits, KilobitsTolerance); - AssertEx.EqualTolerance(1, Information.FromKilobytes(bit.Kilobytes).Bits, KilobytesTolerance); - AssertEx.EqualTolerance(1, Information.FromKilooctets(bit.Kilooctets).Bits, KilooctetsTolerance); - AssertEx.EqualTolerance(1, Information.FromMebibits(bit.Mebibits).Bits, MebibitsTolerance); - AssertEx.EqualTolerance(1, Information.FromMebibytes(bit.Mebibytes).Bits, MebibytesTolerance); - AssertEx.EqualTolerance(1, Information.FromMebioctets(bit.Mebioctets).Bits, MebioctetsTolerance); - AssertEx.EqualTolerance(1, Information.FromMegabits(bit.Megabits).Bits, MegabitsTolerance); - AssertEx.EqualTolerance(1, Information.FromMegabytes(bit.Megabytes).Bits, MegabytesTolerance); - AssertEx.EqualTolerance(1, Information.FromMegaoctets(bit.Megaoctets).Bits, MegaoctetsTolerance); - AssertEx.EqualTolerance(1, Information.FromOctets(bit.Octets).Bits, OctetsTolerance); - AssertEx.EqualTolerance(1, Information.FromPebibits(bit.Pebibits).Bits, PebibitsTolerance); - AssertEx.EqualTolerance(1, Information.FromPebibytes(bit.Pebibytes).Bits, PebibytesTolerance); - AssertEx.EqualTolerance(1, Information.FromPebioctets(bit.Pebioctets).Bits, PebioctetsTolerance); - AssertEx.EqualTolerance(1, Information.FromPetabits(bit.Petabits).Bits, PetabitsTolerance); - AssertEx.EqualTolerance(1, Information.FromPetabytes(bit.Petabytes).Bits, PetabytesTolerance); - AssertEx.EqualTolerance(1, Information.FromPetaoctets(bit.Petaoctets).Bits, PetaoctetsTolerance); - AssertEx.EqualTolerance(1, Information.FromTebibits(bit.Tebibits).Bits, TebibitsTolerance); - AssertEx.EqualTolerance(1, Information.FromTebibytes(bit.Tebibytes).Bits, TebibytesTolerance); - AssertEx.EqualTolerance(1, Information.FromTebioctets(bit.Tebioctets).Bits, TebioctetsTolerance); - AssertEx.EqualTolerance(1, Information.FromTerabits(bit.Terabits).Bits, TerabitsTolerance); - AssertEx.EqualTolerance(1, Information.FromTerabytes(bit.Terabytes).Bits, TerabytesTolerance); - AssertEx.EqualTolerance(1, Information.FromTeraoctets(bit.Teraoctets).Bits, TeraoctetsTolerance); + Information bit = Information.FromBits(3); + Assert.Equal(3, Information.FromBits(bit.Bits).Bits); + Assert.Equal(3, Information.FromBytes(bit.Bytes).Bits); + Assert.Equal(3, Information.FromExabits(bit.Exabits).Bits); + Assert.Equal(3, Information.FromExabytes(bit.Exabytes).Bits); + Assert.Equal(3, Information.FromExaoctets(bit.Exaoctets).Bits); + Assert.Equal(3, Information.FromExbibits(bit.Exbibits).Bits); + Assert.Equal(3, Information.FromExbibytes(bit.Exbibytes).Bits); + Assert.Equal(3, Information.FromExbioctets(bit.Exbioctets).Bits); + Assert.Equal(3, Information.FromGibibits(bit.Gibibits).Bits); + Assert.Equal(3, Information.FromGibibytes(bit.Gibibytes).Bits); + Assert.Equal(3, Information.FromGibioctets(bit.Gibioctets).Bits); + Assert.Equal(3, Information.FromGigabits(bit.Gigabits).Bits); + Assert.Equal(3, Information.FromGigabytes(bit.Gigabytes).Bits); + Assert.Equal(3, Information.FromGigaoctets(bit.Gigaoctets).Bits); + Assert.Equal(3, Information.FromKibibits(bit.Kibibits).Bits); + Assert.Equal(3, Information.FromKibibytes(bit.Kibibytes).Bits); + Assert.Equal(3, Information.FromKibioctets(bit.Kibioctets).Bits); + Assert.Equal(3, Information.FromKilobits(bit.Kilobits).Bits); + Assert.Equal(3, Information.FromKilobytes(bit.Kilobytes).Bits); + Assert.Equal(3, Information.FromKilooctets(bit.Kilooctets).Bits); + Assert.Equal(3, Information.FromMebibits(bit.Mebibits).Bits); + Assert.Equal(3, Information.FromMebibytes(bit.Mebibytes).Bits); + Assert.Equal(3, Information.FromMebioctets(bit.Mebioctets).Bits); + Assert.Equal(3, Information.FromMegabits(bit.Megabits).Bits); + Assert.Equal(3, Information.FromMegabytes(bit.Megabytes).Bits); + Assert.Equal(3, Information.FromMegaoctets(bit.Megaoctets).Bits); + Assert.Equal(3, Information.FromOctets(bit.Octets).Bits); + Assert.Equal(3, Information.FromPebibits(bit.Pebibits).Bits); + Assert.Equal(3, Information.FromPebibytes(bit.Pebibytes).Bits); + Assert.Equal(3, Information.FromPebioctets(bit.Pebioctets).Bits); + Assert.Equal(3, Information.FromPetabits(bit.Petabits).Bits); + Assert.Equal(3, Information.FromPetabytes(bit.Petabytes).Bits); + Assert.Equal(3, Information.FromPetaoctets(bit.Petaoctets).Bits); + Assert.Equal(3, Information.FromTebibits(bit.Tebibits).Bits); + Assert.Equal(3, Information.FromTebibytes(bit.Tebibytes).Bits); + Assert.Equal(3, Information.FromTebioctets(bit.Tebioctets).Bits); + Assert.Equal(3, Information.FromTerabits(bit.Terabits).Bits); + Assert.Equal(3, Information.FromTerabytes(bit.Terabytes).Bits); + Assert.Equal(3, Information.FromTeraoctets(bit.Teraoctets).Bits); } [Fact] public void ArithmeticOperators() { Information v = Information.FromBits(1); - AssertEx.EqualTolerance(-1, -v.Bits, BitsTolerance); - AssertEx.EqualTolerance(2, (Information.FromBits(3)-v).Bits, BitsTolerance); - AssertEx.EqualTolerance(2, (v + v).Bits, BitsTolerance); - AssertEx.EqualTolerance(10, (v*10).Bits, BitsTolerance); - AssertEx.EqualTolerance(10, (10*v).Bits, BitsTolerance); - AssertEx.EqualTolerance(2, (Information.FromBits(10)/5).Bits, BitsTolerance); - AssertEx.EqualTolerance(2, Information.FromBits(10)/Information.FromBits(5), BitsTolerance); + Assert.Equal(-1, -v.Bits); + Assert.Equal(2, (Information.FromBits(3) - v).Bits); + Assert.Equal(2, (v + v).Bits); + Assert.Equal(10, (v * 10).Bits); + Assert.Equal(10, (10 * v).Bits); + Assert.Equal(2, (Information.FromBits(10) / 5).Bits); + Assert.Equal(2, Information.FromBits(10) / Information.FromBits(5)); } [Fact] @@ -1137,8 +1154,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, InformationUnit.Bit, 1, InformationUnit.Bit, true)] // Same value and unit. [InlineData(1, InformationUnit.Bit, 2, InformationUnit.Bit, false)] // Different value. - [InlineData(2, InformationUnit.Bit, 1, InformationUnit.Byte, false)] // Different value and unit. - [InlineData(1, InformationUnit.Bit, 1, InformationUnit.Byte, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, InformationUnit unitA, double valueB, InformationUnit unitB, bool expectEqual) { var a = new Information(valueA, unitA); @@ -1198,8 +1213,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Information.FromBits(firstValue); var otherQuantity = Information.FromBits(secondValue); Information maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Information.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1218,7 +1233,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1231,6 +1246,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Information.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Information.Info.Units, Information.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Information.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1369,7 +1396,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Information.FromBits(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Information), quantity.As(Information.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs index ec5017615b..fa43a5769b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradianceTestsBase.g.cs @@ -177,6 +177,20 @@ public void Irradiance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void IrradianceInfo_CreateWithCustomUnitInfos() + { + IrradianceUnit[] expectedUnits = [IrradianceUnit.WattPerSquareMeter]; + + Irradiance.IrradianceInfo quantityInfo = Irradiance.IrradianceInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Irradiance", quantityInfo.Name); + Assert.Equal(Irradiance.Zero, quantityInfo.Zero); + Assert.Equal(Irradiance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void WattPerSquareMeterToIrradianceUnits() { @@ -367,7 +381,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 pW/m²", IrradianceUnit.PicowattPerSquareMeter, 4.2)] [InlineData("en-US", "4.2 W/cm²", IrradianceUnit.WattPerSquareCentimeter, 4.2)] [InlineData("en-US", "4.2 W/m²", IrradianceUnit.WattPerSquareMeter, 4.2)] - public void Parse(string culture, string quantityString, IrradianceUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, IrradianceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Irradiance.Parse(quantityString); @@ -390,7 +404,7 @@ public void Parse(string culture, string quantityString, IrradianceUnit expected [InlineData("en-US", "4.2 pW/m²", IrradianceUnit.PicowattPerSquareMeter, 4.2)] [InlineData("en-US", "4.2 W/cm²", IrradianceUnit.WattPerSquareCentimeter, 4.2)] [InlineData("en-US", "4.2 W/m²", IrradianceUnit.WattPerSquareMeter, 4.2)] - public void TryParse(string culture, string quantityString, IrradianceUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, IrradianceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Irradiance.TryParse(quantityString, out Irradiance parsed)); @@ -640,6 +654,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(IrradianceUnit u var quantity = Irradiance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -663,45 +678,47 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(IrradianceUnit unit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Irradiance wattpersquaremeter = Irradiance.FromWattsPerSquareMeter(1); - AssertEx.EqualTolerance(1, Irradiance.FromKilowattsPerSquareCentimeter(wattpersquaremeter.KilowattsPerSquareCentimeter).WattsPerSquareMeter, KilowattsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Irradiance.FromKilowattsPerSquareMeter(wattpersquaremeter.KilowattsPerSquareMeter).WattsPerSquareMeter, KilowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Irradiance.FromMegawattsPerSquareCentimeter(wattpersquaremeter.MegawattsPerSquareCentimeter).WattsPerSquareMeter, MegawattsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Irradiance.FromMegawattsPerSquareMeter(wattpersquaremeter.MegawattsPerSquareMeter).WattsPerSquareMeter, MegawattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Irradiance.FromMicrowattsPerSquareCentimeter(wattpersquaremeter.MicrowattsPerSquareCentimeter).WattsPerSquareMeter, MicrowattsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Irradiance.FromMicrowattsPerSquareMeter(wattpersquaremeter.MicrowattsPerSquareMeter).WattsPerSquareMeter, MicrowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Irradiance.FromMilliwattsPerSquareCentimeter(wattpersquaremeter.MilliwattsPerSquareCentimeter).WattsPerSquareMeter, MilliwattsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Irradiance.FromMilliwattsPerSquareMeter(wattpersquaremeter.MilliwattsPerSquareMeter).WattsPerSquareMeter, MilliwattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Irradiance.FromNanowattsPerSquareCentimeter(wattpersquaremeter.NanowattsPerSquareCentimeter).WattsPerSquareMeter, NanowattsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Irradiance.FromNanowattsPerSquareMeter(wattpersquaremeter.NanowattsPerSquareMeter).WattsPerSquareMeter, NanowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Irradiance.FromPicowattsPerSquareCentimeter(wattpersquaremeter.PicowattsPerSquareCentimeter).WattsPerSquareMeter, PicowattsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Irradiance.FromPicowattsPerSquareMeter(wattpersquaremeter.PicowattsPerSquareMeter).WattsPerSquareMeter, PicowattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Irradiance.FromWattsPerSquareCentimeter(wattpersquaremeter.WattsPerSquareCentimeter).WattsPerSquareMeter, WattsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Irradiance.FromWattsPerSquareMeter(wattpersquaremeter.WattsPerSquareMeter).WattsPerSquareMeter, WattsPerSquareMeterTolerance); + Irradiance wattpersquaremeter = Irradiance.FromWattsPerSquareMeter(3); + Assert.Equal(3, Irradiance.FromKilowattsPerSquareCentimeter(wattpersquaremeter.KilowattsPerSquareCentimeter).WattsPerSquareMeter); + Assert.Equal(3, Irradiance.FromKilowattsPerSquareMeter(wattpersquaremeter.KilowattsPerSquareMeter).WattsPerSquareMeter); + Assert.Equal(3, Irradiance.FromMegawattsPerSquareCentimeter(wattpersquaremeter.MegawattsPerSquareCentimeter).WattsPerSquareMeter); + Assert.Equal(3, Irradiance.FromMegawattsPerSquareMeter(wattpersquaremeter.MegawattsPerSquareMeter).WattsPerSquareMeter); + Assert.Equal(3, Irradiance.FromMicrowattsPerSquareCentimeter(wattpersquaremeter.MicrowattsPerSquareCentimeter).WattsPerSquareMeter); + Assert.Equal(3, Irradiance.FromMicrowattsPerSquareMeter(wattpersquaremeter.MicrowattsPerSquareMeter).WattsPerSquareMeter); + Assert.Equal(3, Irradiance.FromMilliwattsPerSquareCentimeter(wattpersquaremeter.MilliwattsPerSquareCentimeter).WattsPerSquareMeter); + Assert.Equal(3, Irradiance.FromMilliwattsPerSquareMeter(wattpersquaremeter.MilliwattsPerSquareMeter).WattsPerSquareMeter); + Assert.Equal(3, Irradiance.FromNanowattsPerSquareCentimeter(wattpersquaremeter.NanowattsPerSquareCentimeter).WattsPerSquareMeter); + Assert.Equal(3, Irradiance.FromNanowattsPerSquareMeter(wattpersquaremeter.NanowattsPerSquareMeter).WattsPerSquareMeter); + Assert.Equal(3, Irradiance.FromPicowattsPerSquareCentimeter(wattpersquaremeter.PicowattsPerSquareCentimeter).WattsPerSquareMeter); + Assert.Equal(3, Irradiance.FromPicowattsPerSquareMeter(wattpersquaremeter.PicowattsPerSquareMeter).WattsPerSquareMeter); + Assert.Equal(3, Irradiance.FromWattsPerSquareCentimeter(wattpersquaremeter.WattsPerSquareCentimeter).WattsPerSquareMeter); + Assert.Equal(3, Irradiance.FromWattsPerSquareMeter(wattpersquaremeter.WattsPerSquareMeter).WattsPerSquareMeter); } [Fact] public void ArithmeticOperators() { Irradiance v = Irradiance.FromWattsPerSquareMeter(1); - AssertEx.EqualTolerance(-1, -v.WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (Irradiance.FromWattsPerSquareMeter(3)-v).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (Irradiance.FromWattsPerSquareMeter(10)/5).WattsPerSquareMeter, WattsPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, Irradiance.FromWattsPerSquareMeter(10)/Irradiance.FromWattsPerSquareMeter(5), WattsPerSquareMeterTolerance); + Assert.Equal(-1, -v.WattsPerSquareMeter); + Assert.Equal(2, (Irradiance.FromWattsPerSquareMeter(3) - v).WattsPerSquareMeter); + Assert.Equal(2, (v + v).WattsPerSquareMeter); + Assert.Equal(10, (v * 10).WattsPerSquareMeter); + Assert.Equal(10, (10 * v).WattsPerSquareMeter); + Assert.Equal(2, (Irradiance.FromWattsPerSquareMeter(10) / 5).WattsPerSquareMeter); + Assert.Equal(2, Irradiance.FromWattsPerSquareMeter(10) / Irradiance.FromWattsPerSquareMeter(5)); } [Fact] @@ -747,8 +764,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, IrradianceUnit.WattPerSquareMeter, 1, IrradianceUnit.WattPerSquareMeter, true)] // Same value and unit. [InlineData(1, IrradianceUnit.WattPerSquareMeter, 2, IrradianceUnit.WattPerSquareMeter, false)] // Different value. - [InlineData(2, IrradianceUnit.WattPerSquareMeter, 1, IrradianceUnit.KilowattPerSquareCentimeter, false)] // Different value and unit. - [InlineData(1, IrradianceUnit.WattPerSquareMeter, 1, IrradianceUnit.KilowattPerSquareCentimeter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, IrradianceUnit unitA, double valueB, IrradianceUnit unitB, bool expectEqual) { var a = new Irradiance(valueA, unitA); @@ -808,8 +823,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Irradiance.FromWattsPerSquareMeter(firstValue); var otherQuantity = Irradiance.FromWattsPerSquareMeter(secondValue); Irradiance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Irradiance.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -828,7 +843,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -841,6 +856,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Irradiance.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Irradiance.Info.Units, Irradiance.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Irradiance.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -929,7 +956,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Irradiance.FromWattsPerSquareMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Irradiance), quantity.As(Irradiance.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs index 52cc06850c..c19713aab8 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/IrradiationTestsBase.g.cs @@ -157,6 +157,20 @@ public void Irradiation_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void IrradiationInfo_CreateWithCustomUnitInfos() + { + IrradiationUnit[] expectedUnits = [IrradiationUnit.JoulePerSquareMeter]; + + Irradiation.IrradiationInfo quantityInfo = Irradiation.IrradiationInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Irradiation", quantityInfo.Name); + Assert.Equal(Irradiation.Zero, quantityInfo.Zero); + Assert.Equal(Irradiation.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void JoulePerSquareMeterToIrradiationUnits() { @@ -332,7 +346,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 kWh/m²", IrradiationUnit.KilowattHourPerSquareMeter, 4.2)] [InlineData("en-US", "4.2 mJ/cm²", IrradiationUnit.MillijoulePerSquareCentimeter, 4.2)] [InlineData("en-US", "4.2 Wh/m²", IrradiationUnit.WattHourPerSquareMeter, 4.2)] - public void Parse(string culture, string quantityString, IrradiationUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, IrradiationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Irradiation.Parse(quantityString); @@ -350,7 +364,7 @@ public void Parse(string culture, string quantityString, IrradiationUnit expecte [InlineData("en-US", "4.2 kWh/m²", IrradiationUnit.KilowattHourPerSquareMeter, 4.2)] [InlineData("en-US", "4.2 mJ/cm²", IrradiationUnit.MillijoulePerSquareCentimeter, 4.2)] [InlineData("en-US", "4.2 Wh/m²", IrradiationUnit.WattHourPerSquareMeter, 4.2)] - public void TryParse(string culture, string quantityString, IrradiationUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, IrradiationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Irradiation.TryParse(quantityString, out Irradiation parsed)); @@ -555,6 +569,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(IrradiationUnit var quantity = Irradiation.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -578,40 +593,42 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(IrradiationUnit uni IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Irradiation joulepersquaremeter = Irradiation.FromJoulesPerSquareMeter(1); - AssertEx.EqualTolerance(1, Irradiation.FromBtusPerSquareFoot(joulepersquaremeter.BtusPerSquareFoot).JoulesPerSquareMeter, BtusPerSquareFootTolerance); - AssertEx.EqualTolerance(1, Irradiation.FromJoulesPerSquareCentimeter(joulepersquaremeter.JoulesPerSquareCentimeter).JoulesPerSquareMeter, JoulesPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Irradiation.FromJoulesPerSquareMeter(joulepersquaremeter.JoulesPerSquareMeter).JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Irradiation.FromJoulesPerSquareMillimeter(joulepersquaremeter.JoulesPerSquareMillimeter).JoulesPerSquareMeter, JoulesPerSquareMillimeterTolerance); - AssertEx.EqualTolerance(1, Irradiation.FromKilobtusPerSquareFoot(joulepersquaremeter.KilobtusPerSquareFoot).JoulesPerSquareMeter, KilobtusPerSquareFootTolerance); - AssertEx.EqualTolerance(1, Irradiation.FromKilojoulesPerSquareMeter(joulepersquaremeter.KilojoulesPerSquareMeter).JoulesPerSquareMeter, KilojoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Irradiation.FromKilowattHoursPerSquareMeter(joulepersquaremeter.KilowattHoursPerSquareMeter).JoulesPerSquareMeter, KilowattHoursPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Irradiation.FromMillijoulesPerSquareCentimeter(joulepersquaremeter.MillijoulesPerSquareCentimeter).JoulesPerSquareMeter, MillijoulesPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Irradiation.FromWattHoursPerSquareMeter(joulepersquaremeter.WattHoursPerSquareMeter).JoulesPerSquareMeter, WattHoursPerSquareMeterTolerance); + Irradiation joulepersquaremeter = Irradiation.FromJoulesPerSquareMeter(3); + Assert.Equal(3, Irradiation.FromBtusPerSquareFoot(joulepersquaremeter.BtusPerSquareFoot).JoulesPerSquareMeter); + Assert.Equal(3, Irradiation.FromJoulesPerSquareCentimeter(joulepersquaremeter.JoulesPerSquareCentimeter).JoulesPerSquareMeter); + Assert.Equal(3, Irradiation.FromJoulesPerSquareMeter(joulepersquaremeter.JoulesPerSquareMeter).JoulesPerSquareMeter); + Assert.Equal(3, Irradiation.FromJoulesPerSquareMillimeter(joulepersquaremeter.JoulesPerSquareMillimeter).JoulesPerSquareMeter); + Assert.Equal(3, Irradiation.FromKilobtusPerSquareFoot(joulepersquaremeter.KilobtusPerSquareFoot).JoulesPerSquareMeter); + Assert.Equal(3, Irradiation.FromKilojoulesPerSquareMeter(joulepersquaremeter.KilojoulesPerSquareMeter).JoulesPerSquareMeter); + Assert.Equal(3, Irradiation.FromKilowattHoursPerSquareMeter(joulepersquaremeter.KilowattHoursPerSquareMeter).JoulesPerSquareMeter); + Assert.Equal(3, Irradiation.FromMillijoulesPerSquareCentimeter(joulepersquaremeter.MillijoulesPerSquareCentimeter).JoulesPerSquareMeter); + Assert.Equal(3, Irradiation.FromWattHoursPerSquareMeter(joulepersquaremeter.WattHoursPerSquareMeter).JoulesPerSquareMeter); } [Fact] public void ArithmeticOperators() { Irradiation v = Irradiation.FromJoulesPerSquareMeter(1); - AssertEx.EqualTolerance(-1, -v.JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (Irradiation.FromJoulesPerSquareMeter(3)-v).JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (Irradiation.FromJoulesPerSquareMeter(10)/5).JoulesPerSquareMeter, JoulesPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, Irradiation.FromJoulesPerSquareMeter(10)/Irradiation.FromJoulesPerSquareMeter(5), JoulesPerSquareMeterTolerance); + Assert.Equal(-1, -v.JoulesPerSquareMeter); + Assert.Equal(2, (Irradiation.FromJoulesPerSquareMeter(3) - v).JoulesPerSquareMeter); + Assert.Equal(2, (v + v).JoulesPerSquareMeter); + Assert.Equal(10, (v * 10).JoulesPerSquareMeter); + Assert.Equal(10, (10 * v).JoulesPerSquareMeter); + Assert.Equal(2, (Irradiation.FromJoulesPerSquareMeter(10) / 5).JoulesPerSquareMeter); + Assert.Equal(2, Irradiation.FromJoulesPerSquareMeter(10) / Irradiation.FromJoulesPerSquareMeter(5)); } [Fact] @@ -657,8 +674,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, IrradiationUnit.JoulePerSquareMeter, 1, IrradiationUnit.JoulePerSquareMeter, true)] // Same value and unit. [InlineData(1, IrradiationUnit.JoulePerSquareMeter, 2, IrradiationUnit.JoulePerSquareMeter, false)] // Different value. - [InlineData(2, IrradiationUnit.JoulePerSquareMeter, 1, IrradiationUnit.BtuPerSquareFoot, false)] // Different value and unit. - [InlineData(1, IrradiationUnit.JoulePerSquareMeter, 1, IrradiationUnit.BtuPerSquareFoot, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, IrradiationUnit unitA, double valueB, IrradiationUnit unitB, bool expectEqual) { var a = new Irradiation(valueA, unitA); @@ -718,8 +733,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Irradiation.FromJoulesPerSquareMeter(firstValue); var otherQuantity = Irradiation.FromJoulesPerSquareMeter(secondValue); Irradiation maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Irradiation.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -738,7 +753,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -751,6 +766,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Irradiation.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Irradiation.Info.Units, Irradiation.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Irradiation.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -829,7 +856,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Irradiation.FromJoulesPerSquareMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Irradiation), quantity.As(Irradiation.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/JerkTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/JerkTestsBase.g.cs index b560a342f4..b0bdf7f209 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/JerkTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/JerkTestsBase.g.cs @@ -165,6 +165,20 @@ public void Jerk_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void JerkInfo_CreateWithCustomUnitInfos() + { + JerkUnit[] expectedUnits = [JerkUnit.MeterPerSecondCubed]; + + Jerk.JerkInfo quantityInfo = Jerk.JerkInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Jerk", quantityInfo.Name); + Assert.Equal(Jerk.Zero, quantityInfo.Zero); + Assert.Equal(Jerk.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void MeterPerSecondCubedToJerkUnits() { @@ -357,7 +371,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 мg/s", JerkUnit.MillistandardGravitiesPerSecond, 4.2)] [InlineData("ru-RU", "4,2 нм/с³", JerkUnit.NanometerPerSecondCubed, 4.2)] [InlineData("ru-RU", "4,2 g/s", JerkUnit.StandardGravitiesPerSecond, 4.2)] - public void Parse(string culture, string quantityString, JerkUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, JerkUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Jerk.Parse(quantityString); @@ -388,7 +402,7 @@ public void Parse(string culture, string quantityString, JerkUnit expectedUnit, [InlineData("ru-RU", "4,2 мg/s", JerkUnit.MillistandardGravitiesPerSecond, 4.2)] [InlineData("ru-RU", "4,2 нм/с³", JerkUnit.NanometerPerSecondCubed, 4.2)] [InlineData("ru-RU", "4,2 g/s", JerkUnit.StandardGravitiesPerSecond, 4.2)] - public void TryParse(string culture, string quantityString, JerkUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, JerkUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Jerk.TryParse(quantityString, out Jerk parsed)); @@ -666,6 +680,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(JerkUnit unit) var quantity = Jerk.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -689,42 +704,44 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(JerkUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Jerk meterpersecondcubed = Jerk.FromMetersPerSecondCubed(1); - AssertEx.EqualTolerance(1, Jerk.FromCentimetersPerSecondCubed(meterpersecondcubed.CentimetersPerSecondCubed).MetersPerSecondCubed, CentimetersPerSecondCubedTolerance); - AssertEx.EqualTolerance(1, Jerk.FromDecimetersPerSecondCubed(meterpersecondcubed.DecimetersPerSecondCubed).MetersPerSecondCubed, DecimetersPerSecondCubedTolerance); - AssertEx.EqualTolerance(1, Jerk.FromFeetPerSecondCubed(meterpersecondcubed.FeetPerSecondCubed).MetersPerSecondCubed, FeetPerSecondCubedTolerance); - AssertEx.EqualTolerance(1, Jerk.FromInchesPerSecondCubed(meterpersecondcubed.InchesPerSecondCubed).MetersPerSecondCubed, InchesPerSecondCubedTolerance); - AssertEx.EqualTolerance(1, Jerk.FromKilometersPerSecondCubed(meterpersecondcubed.KilometersPerSecondCubed).MetersPerSecondCubed, KilometersPerSecondCubedTolerance); - AssertEx.EqualTolerance(1, Jerk.FromMetersPerSecondCubed(meterpersecondcubed.MetersPerSecondCubed).MetersPerSecondCubed, MetersPerSecondCubedTolerance); - AssertEx.EqualTolerance(1, Jerk.FromMicrometersPerSecondCubed(meterpersecondcubed.MicrometersPerSecondCubed).MetersPerSecondCubed, MicrometersPerSecondCubedTolerance); - AssertEx.EqualTolerance(1, Jerk.FromMillimetersPerSecondCubed(meterpersecondcubed.MillimetersPerSecondCubed).MetersPerSecondCubed, MillimetersPerSecondCubedTolerance); - AssertEx.EqualTolerance(1, Jerk.FromMillistandardGravitiesPerSecond(meterpersecondcubed.MillistandardGravitiesPerSecond).MetersPerSecondCubed, MillistandardGravitiesPerSecondTolerance); - AssertEx.EqualTolerance(1, Jerk.FromNanometersPerSecondCubed(meterpersecondcubed.NanometersPerSecondCubed).MetersPerSecondCubed, NanometersPerSecondCubedTolerance); - AssertEx.EqualTolerance(1, Jerk.FromStandardGravitiesPerSecond(meterpersecondcubed.StandardGravitiesPerSecond).MetersPerSecondCubed, StandardGravitiesPerSecondTolerance); + Jerk meterpersecondcubed = Jerk.FromMetersPerSecondCubed(3); + Assert.Equal(3, Jerk.FromCentimetersPerSecondCubed(meterpersecondcubed.CentimetersPerSecondCubed).MetersPerSecondCubed); + Assert.Equal(3, Jerk.FromDecimetersPerSecondCubed(meterpersecondcubed.DecimetersPerSecondCubed).MetersPerSecondCubed); + Assert.Equal(3, Jerk.FromFeetPerSecondCubed(meterpersecondcubed.FeetPerSecondCubed).MetersPerSecondCubed); + Assert.Equal(3, Jerk.FromInchesPerSecondCubed(meterpersecondcubed.InchesPerSecondCubed).MetersPerSecondCubed); + Assert.Equal(3, Jerk.FromKilometersPerSecondCubed(meterpersecondcubed.KilometersPerSecondCubed).MetersPerSecondCubed); + Assert.Equal(3, Jerk.FromMetersPerSecondCubed(meterpersecondcubed.MetersPerSecondCubed).MetersPerSecondCubed); + Assert.Equal(3, Jerk.FromMicrometersPerSecondCubed(meterpersecondcubed.MicrometersPerSecondCubed).MetersPerSecondCubed); + Assert.Equal(3, Jerk.FromMillimetersPerSecondCubed(meterpersecondcubed.MillimetersPerSecondCubed).MetersPerSecondCubed); + Assert.Equal(3, Jerk.FromMillistandardGravitiesPerSecond(meterpersecondcubed.MillistandardGravitiesPerSecond).MetersPerSecondCubed); + Assert.Equal(3, Jerk.FromNanometersPerSecondCubed(meterpersecondcubed.NanometersPerSecondCubed).MetersPerSecondCubed); + Assert.Equal(3, Jerk.FromStandardGravitiesPerSecond(meterpersecondcubed.StandardGravitiesPerSecond).MetersPerSecondCubed); } [Fact] public void ArithmeticOperators() { Jerk v = Jerk.FromMetersPerSecondCubed(1); - AssertEx.EqualTolerance(-1, -v.MetersPerSecondCubed, MetersPerSecondCubedTolerance); - AssertEx.EqualTolerance(2, (Jerk.FromMetersPerSecondCubed(3)-v).MetersPerSecondCubed, MetersPerSecondCubedTolerance); - AssertEx.EqualTolerance(2, (v + v).MetersPerSecondCubed, MetersPerSecondCubedTolerance); - AssertEx.EqualTolerance(10, (v*10).MetersPerSecondCubed, MetersPerSecondCubedTolerance); - AssertEx.EqualTolerance(10, (10*v).MetersPerSecondCubed, MetersPerSecondCubedTolerance); - AssertEx.EqualTolerance(2, (Jerk.FromMetersPerSecondCubed(10)/5).MetersPerSecondCubed, MetersPerSecondCubedTolerance); - AssertEx.EqualTolerance(2, Jerk.FromMetersPerSecondCubed(10)/Jerk.FromMetersPerSecondCubed(5), MetersPerSecondCubedTolerance); + Assert.Equal(-1, -v.MetersPerSecondCubed); + Assert.Equal(2, (Jerk.FromMetersPerSecondCubed(3) - v).MetersPerSecondCubed); + Assert.Equal(2, (v + v).MetersPerSecondCubed); + Assert.Equal(10, (v * 10).MetersPerSecondCubed); + Assert.Equal(10, (10 * v).MetersPerSecondCubed); + Assert.Equal(2, (Jerk.FromMetersPerSecondCubed(10) / 5).MetersPerSecondCubed); + Assert.Equal(2, Jerk.FromMetersPerSecondCubed(10) / Jerk.FromMetersPerSecondCubed(5)); } [Fact] @@ -770,8 +787,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, JerkUnit.MeterPerSecondCubed, 1, JerkUnit.MeterPerSecondCubed, true)] // Same value and unit. [InlineData(1, JerkUnit.MeterPerSecondCubed, 2, JerkUnit.MeterPerSecondCubed, false)] // Different value. - [InlineData(2, JerkUnit.MeterPerSecondCubed, 1, JerkUnit.CentimeterPerSecondCubed, false)] // Different value and unit. - [InlineData(1, JerkUnit.MeterPerSecondCubed, 1, JerkUnit.CentimeterPerSecondCubed, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, JerkUnit unitA, double valueB, JerkUnit unitB, bool expectEqual) { var a = new Jerk(valueA, unitA); @@ -831,8 +846,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Jerk.FromMetersPerSecondCubed(firstValue); var otherQuantity = Jerk.FromMetersPerSecondCubed(secondValue); Jerk maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Jerk.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -851,7 +866,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -864,6 +879,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Jerk.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Jerk.Info.Units, Jerk.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Jerk.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -946,7 +973,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Jerk.FromMetersPerSecondCubed(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Jerk), quantity.As(Jerk.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs index 62e88d77ad..646b0bc313 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/KinematicViscosityTestsBase.g.cs @@ -157,6 +157,20 @@ public void KinematicViscosity_QuantityInfo_ReturnsQuantityInfoDescribingQuantit Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void KinematicViscosityInfo_CreateWithCustomUnitInfos() + { + KinematicViscosityUnit[] expectedUnits = [KinematicViscosityUnit.SquareMeterPerSecond]; + + KinematicViscosity.KinematicViscosityInfo quantityInfo = KinematicViscosity.KinematicViscosityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("KinematicViscosity", quantityInfo.Name); + Assert.Equal(KinematicViscosity.Zero, quantityInfo.Zero); + Assert.Equal(KinematicViscosity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void SquareMeterPerSecondToKinematicViscosityUnits() { @@ -340,7 +354,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 нСт", KinematicViscosityUnit.Nanostokes, 4.2)] [InlineData("ru-RU", "4,2 м²/с", KinematicViscosityUnit.SquareMeterPerSecond, 4.2)] [InlineData("ru-RU", "4,2 Ст", KinematicViscosityUnit.Stokes, 4.2)] - public void Parse(string culture, string quantityString, KinematicViscosityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, KinematicViscosityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = KinematicViscosity.Parse(quantityString); @@ -366,7 +380,7 @@ public void Parse(string culture, string quantityString, KinematicViscosityUnit [InlineData("ru-RU", "4,2 нСт", KinematicViscosityUnit.Nanostokes, 4.2)] [InlineData("ru-RU", "4,2 м²/с", KinematicViscosityUnit.SquareMeterPerSecond, 4.2)] [InlineData("ru-RU", "4,2 Ст", KinematicViscosityUnit.Stokes, 4.2)] - public void TryParse(string culture, string quantityString, KinematicViscosityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, KinematicViscosityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(KinematicViscosity.TryParse(quantityString, out KinematicViscosity parsed)); @@ -611,6 +625,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(KinematicViscosi var quantity = KinematicViscosity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -634,40 +649,42 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(KinematicViscosityU IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - KinematicViscosity squaremeterpersecond = KinematicViscosity.FromSquareMetersPerSecond(1); - AssertEx.EqualTolerance(1, KinematicViscosity.FromCentistokes(squaremeterpersecond.Centistokes).SquareMetersPerSecond, CentistokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.FromDecistokes(squaremeterpersecond.Decistokes).SquareMetersPerSecond, DecistokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.FromKilostokes(squaremeterpersecond.Kilostokes).SquareMetersPerSecond, KilostokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.FromMicrostokes(squaremeterpersecond.Microstokes).SquareMetersPerSecond, MicrostokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.FromMillistokes(squaremeterpersecond.Millistokes).SquareMetersPerSecond, MillistokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.FromNanostokes(squaremeterpersecond.Nanostokes).SquareMetersPerSecond, NanostokesTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.FromSquareFeetPerSecond(squaremeterpersecond.SquareFeetPerSecond).SquareMetersPerSecond, SquareFeetPerSecondTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.FromSquareMetersPerSecond(squaremeterpersecond.SquareMetersPerSecond).SquareMetersPerSecond, SquareMetersPerSecondTolerance); - AssertEx.EqualTolerance(1, KinematicViscosity.FromStokes(squaremeterpersecond.Stokes).SquareMetersPerSecond, StokesTolerance); + KinematicViscosity squaremeterpersecond = KinematicViscosity.FromSquareMetersPerSecond(3); + Assert.Equal(3, KinematicViscosity.FromCentistokes(squaremeterpersecond.Centistokes).SquareMetersPerSecond); + Assert.Equal(3, KinematicViscosity.FromDecistokes(squaremeterpersecond.Decistokes).SquareMetersPerSecond); + Assert.Equal(3, KinematicViscosity.FromKilostokes(squaremeterpersecond.Kilostokes).SquareMetersPerSecond); + Assert.Equal(3, KinematicViscosity.FromMicrostokes(squaremeterpersecond.Microstokes).SquareMetersPerSecond); + Assert.Equal(3, KinematicViscosity.FromMillistokes(squaremeterpersecond.Millistokes).SquareMetersPerSecond); + Assert.Equal(3, KinematicViscosity.FromNanostokes(squaremeterpersecond.Nanostokes).SquareMetersPerSecond); + Assert.Equal(3, KinematicViscosity.FromSquareFeetPerSecond(squaremeterpersecond.SquareFeetPerSecond).SquareMetersPerSecond); + Assert.Equal(3, KinematicViscosity.FromSquareMetersPerSecond(squaremeterpersecond.SquareMetersPerSecond).SquareMetersPerSecond); + Assert.Equal(3, KinematicViscosity.FromStokes(squaremeterpersecond.Stokes).SquareMetersPerSecond); } [Fact] public void ArithmeticOperators() { KinematicViscosity v = KinematicViscosity.FromSquareMetersPerSecond(1); - AssertEx.EqualTolerance(-1, -v.SquareMetersPerSecond, SquareMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (KinematicViscosity.FromSquareMetersPerSecond(3)-v).SquareMetersPerSecond, SquareMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).SquareMetersPerSecond, SquareMetersPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).SquareMetersPerSecond, SquareMetersPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).SquareMetersPerSecond, SquareMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (KinematicViscosity.FromSquareMetersPerSecond(10)/5).SquareMetersPerSecond, SquareMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, KinematicViscosity.FromSquareMetersPerSecond(10)/KinematicViscosity.FromSquareMetersPerSecond(5), SquareMetersPerSecondTolerance); + Assert.Equal(-1, -v.SquareMetersPerSecond); + Assert.Equal(2, (KinematicViscosity.FromSquareMetersPerSecond(3) - v).SquareMetersPerSecond); + Assert.Equal(2, (v + v).SquareMetersPerSecond); + Assert.Equal(10, (v * 10).SquareMetersPerSecond); + Assert.Equal(10, (10 * v).SquareMetersPerSecond); + Assert.Equal(2, (KinematicViscosity.FromSquareMetersPerSecond(10) / 5).SquareMetersPerSecond); + Assert.Equal(2, KinematicViscosity.FromSquareMetersPerSecond(10) / KinematicViscosity.FromSquareMetersPerSecond(5)); } [Fact] @@ -713,8 +730,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, KinematicViscosityUnit.SquareMeterPerSecond, 1, KinematicViscosityUnit.SquareMeterPerSecond, true)] // Same value and unit. [InlineData(1, KinematicViscosityUnit.SquareMeterPerSecond, 2, KinematicViscosityUnit.SquareMeterPerSecond, false)] // Different value. - [InlineData(2, KinematicViscosityUnit.SquareMeterPerSecond, 1, KinematicViscosityUnit.Centistokes, false)] // Different value and unit. - [InlineData(1, KinematicViscosityUnit.SquareMeterPerSecond, 1, KinematicViscosityUnit.Centistokes, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, KinematicViscosityUnit unitA, double valueB, KinematicViscosityUnit unitB, bool expectEqual) { var a = new KinematicViscosity(valueA, unitA); @@ -774,8 +789,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = KinematicViscosity.FromSquareMetersPerSecond(firstValue); var otherQuantity = KinematicViscosity.FromSquareMetersPerSecond(secondValue); KinematicViscosity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, KinematicViscosity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -794,7 +809,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -807,6 +822,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(KinematicViscosity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(KinematicViscosity.Info.Units, KinematicViscosity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, KinematicViscosity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -885,7 +912,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = KinematicViscosity.FromSquareMetersPerSecond(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(KinematicViscosity), quantity.As(KinematicViscosity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LeakRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LeakRateTestsBase.g.cs index 2ecd71c630..7a49accc92 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LeakRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LeakRateTestsBase.g.cs @@ -137,6 +137,20 @@ public void LeakRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void LeakRateInfo_CreateWithCustomUnitInfos() + { + LeakRateUnit[] expectedUnits = [LeakRateUnit.PascalCubicMeterPerSecond]; + + LeakRate.LeakRateInfo quantityInfo = LeakRate.LeakRateInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("LeakRate", quantityInfo.Name); + Assert.Equal(LeakRate.Zero, quantityInfo.Zero); + Assert.Equal(LeakRate.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void PascalCubicMeterPerSecondToLeakRateUnits() { @@ -297,7 +311,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 mbar·l/s", LeakRateUnit.MillibarLiterPerSecond, 4.2)] [InlineData("en-US", "4.2 Pa·m³/s", LeakRateUnit.PascalCubicMeterPerSecond, 4.2)] [InlineData("en-US", "4.2 Torr·l/s", LeakRateUnit.TorrLiterPerSecond, 4.2)] - public void Parse(string culture, string quantityString, LeakRateUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, LeakRateUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = LeakRate.Parse(quantityString); @@ -310,7 +324,7 @@ public void Parse(string culture, string quantityString, LeakRateUnit expectedUn [InlineData("en-US", "4.2 mbar·l/s", LeakRateUnit.MillibarLiterPerSecond, 4.2)] [InlineData("en-US", "4.2 Pa·m³/s", LeakRateUnit.PascalCubicMeterPerSecond, 4.2)] [InlineData("en-US", "4.2 Torr·l/s", LeakRateUnit.TorrLiterPerSecond, 4.2)] - public void TryParse(string culture, string quantityString, LeakRateUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, LeakRateUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(LeakRate.TryParse(quantityString, out LeakRate parsed)); @@ -470,6 +484,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LeakRateUnit uni var quantity = LeakRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -493,35 +508,37 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(LeakRateUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - LeakRate pascalcubicmeterpersecond = LeakRate.FromPascalCubicMetersPerSecond(1); - AssertEx.EqualTolerance(1, LeakRate.FromAtmCubicCentimetersPerSecond(pascalcubicmeterpersecond.AtmCubicCentimetersPerSecond).PascalCubicMetersPerSecond, AtmCubicCentimetersPerSecondTolerance); - AssertEx.EqualTolerance(1, LeakRate.FromMillibarLitersPerSecond(pascalcubicmeterpersecond.MillibarLitersPerSecond).PascalCubicMetersPerSecond, MillibarLitersPerSecondTolerance); - AssertEx.EqualTolerance(1, LeakRate.FromPascalCubicMetersPerSecond(pascalcubicmeterpersecond.PascalCubicMetersPerSecond).PascalCubicMetersPerSecond, PascalCubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(1, LeakRate.FromTorrLitersPerSecond(pascalcubicmeterpersecond.TorrLitersPerSecond).PascalCubicMetersPerSecond, TorrLitersPerSecondTolerance); + LeakRate pascalcubicmeterpersecond = LeakRate.FromPascalCubicMetersPerSecond(3); + Assert.Equal(3, LeakRate.FromAtmCubicCentimetersPerSecond(pascalcubicmeterpersecond.AtmCubicCentimetersPerSecond).PascalCubicMetersPerSecond); + Assert.Equal(3, LeakRate.FromMillibarLitersPerSecond(pascalcubicmeterpersecond.MillibarLitersPerSecond).PascalCubicMetersPerSecond); + Assert.Equal(3, LeakRate.FromPascalCubicMetersPerSecond(pascalcubicmeterpersecond.PascalCubicMetersPerSecond).PascalCubicMetersPerSecond); + Assert.Equal(3, LeakRate.FromTorrLitersPerSecond(pascalcubicmeterpersecond.TorrLitersPerSecond).PascalCubicMetersPerSecond); } [Fact] public void ArithmeticOperators() { LeakRate v = LeakRate.FromPascalCubicMetersPerSecond(1); - AssertEx.EqualTolerance(-1, -v.PascalCubicMetersPerSecond, PascalCubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (LeakRate.FromPascalCubicMetersPerSecond(3)-v).PascalCubicMetersPerSecond, PascalCubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).PascalCubicMetersPerSecond, PascalCubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).PascalCubicMetersPerSecond, PascalCubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).PascalCubicMetersPerSecond, PascalCubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (LeakRate.FromPascalCubicMetersPerSecond(10)/5).PascalCubicMetersPerSecond, PascalCubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, LeakRate.FromPascalCubicMetersPerSecond(10)/LeakRate.FromPascalCubicMetersPerSecond(5), PascalCubicMetersPerSecondTolerance); + Assert.Equal(-1, -v.PascalCubicMetersPerSecond); + Assert.Equal(2, (LeakRate.FromPascalCubicMetersPerSecond(3) - v).PascalCubicMetersPerSecond); + Assert.Equal(2, (v + v).PascalCubicMetersPerSecond); + Assert.Equal(10, (v * 10).PascalCubicMetersPerSecond); + Assert.Equal(10, (10 * v).PascalCubicMetersPerSecond); + Assert.Equal(2, (LeakRate.FromPascalCubicMetersPerSecond(10) / 5).PascalCubicMetersPerSecond); + Assert.Equal(2, LeakRate.FromPascalCubicMetersPerSecond(10) / LeakRate.FromPascalCubicMetersPerSecond(5)); } [Fact] @@ -567,8 +584,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, LeakRateUnit.PascalCubicMeterPerSecond, 1, LeakRateUnit.PascalCubicMeterPerSecond, true)] // Same value and unit. [InlineData(1, LeakRateUnit.PascalCubicMeterPerSecond, 2, LeakRateUnit.PascalCubicMeterPerSecond, false)] // Different value. - [InlineData(2, LeakRateUnit.PascalCubicMeterPerSecond, 1, LeakRateUnit.AtmCubicCentimeterPerSecond, false)] // Different value and unit. - [InlineData(1, LeakRateUnit.PascalCubicMeterPerSecond, 1, LeakRateUnit.AtmCubicCentimeterPerSecond, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, LeakRateUnit unitA, double valueB, LeakRateUnit unitB, bool expectEqual) { var a = new LeakRate(valueA, unitA); @@ -628,8 +643,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = LeakRate.FromPascalCubicMetersPerSecond(firstValue); var otherQuantity = LeakRate.FromPascalCubicMetersPerSecond(secondValue); LeakRate maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, LeakRate.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -648,7 +663,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -661,6 +676,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(LeakRate.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(LeakRate.Info.Units, LeakRate.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, LeakRate.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -729,7 +756,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = LeakRate.FromPascalCubicMetersPerSecond(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(LeakRate), quantity.As(LeakRate.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs index 815c43e98d..315e73b650 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LengthTestsBase.g.cs @@ -289,6 +289,20 @@ public void Length_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void LengthInfo_CreateWithCustomUnitInfos() + { + LengthUnit[] expectedUnits = [LengthUnit.Meter]; + + Length.LengthInfo quantityInfo = Length.LengthInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Length", quantityInfo.Name); + Assert.Equal(Length.Zero, quantityInfo.Zero); + Assert.Equal(Length.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void MeterToLengthUnits() { @@ -609,7 +623,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("zh-CN", "4.2 毫米", LengthUnit.Millimeter, 4.2)] [InlineData("zh-CN", "4.2 皮米", LengthUnit.Picometer, 4.2)] [InlineData("zh-CN", "4.2 码", LengthUnit.Yard, 4.2)] - public void Parse(string culture, string quantityString, LengthUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, LengthUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Length.Parse(quantityString); @@ -716,7 +730,7 @@ public void ParseWithAmbiguousAbbreviation(string culture, string quantityString [InlineData("zh-CN", "4.2 毫米", LengthUnit.Millimeter, 4.2)] [InlineData("zh-CN", "4.2 皮米", LengthUnit.Picometer, 4.2)] [InlineData("zh-CN", "4.2 码", LengthUnit.Yard, 4.2)] - public void TryParse(string culture, string quantityString, LengthUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, LengthUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Length.TryParse(quantityString, out Length parsed)); @@ -1500,6 +1514,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LengthUnit unit) var quantity = Length.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -1523,73 +1538,75 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(LengthUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Length meter = Length.FromMeters(1); - AssertEx.EqualTolerance(1, Length.FromAngstroms(meter.Angstroms).Meters, AngstromsTolerance); - AssertEx.EqualTolerance(1, Length.FromAstronomicalUnits(meter.AstronomicalUnits).Meters, AstronomicalUnitsTolerance); - AssertEx.EqualTolerance(1, Length.FromCentimeters(meter.Centimeters).Meters, CentimetersTolerance); - AssertEx.EqualTolerance(1, Length.FromChains(meter.Chains).Meters, ChainsTolerance); - AssertEx.EqualTolerance(1, Length.FromDataMiles(meter.DataMiles).Meters, DataMilesTolerance); - AssertEx.EqualTolerance(1, Length.FromDecameters(meter.Decameters).Meters, DecametersTolerance); - AssertEx.EqualTolerance(1, Length.FromDecimeters(meter.Decimeters).Meters, DecimetersTolerance); - AssertEx.EqualTolerance(1, Length.FromDtpPicas(meter.DtpPicas).Meters, DtpPicasTolerance); - AssertEx.EqualTolerance(1, Length.FromDtpPoints(meter.DtpPoints).Meters, DtpPointsTolerance); - AssertEx.EqualTolerance(1, Length.FromFathoms(meter.Fathoms).Meters, FathomsTolerance); - AssertEx.EqualTolerance(1, Length.FromFemtometers(meter.Femtometers).Meters, FemtometersTolerance); - AssertEx.EqualTolerance(1, Length.FromFeet(meter.Feet).Meters, FeetTolerance); - AssertEx.EqualTolerance(1, Length.FromGigameters(meter.Gigameters).Meters, GigametersTolerance); - AssertEx.EqualTolerance(1, Length.FromHands(meter.Hands).Meters, HandsTolerance); - AssertEx.EqualTolerance(1, Length.FromHectometers(meter.Hectometers).Meters, HectometersTolerance); - AssertEx.EqualTolerance(1, Length.FromInches(meter.Inches).Meters, InchesTolerance); - AssertEx.EqualTolerance(1, Length.FromKilofeet(meter.Kilofeet).Meters, KilofeetTolerance); - AssertEx.EqualTolerance(1, Length.FromKilolightYears(meter.KilolightYears).Meters, KilolightYearsTolerance); - AssertEx.EqualTolerance(1, Length.FromKilometers(meter.Kilometers).Meters, KilometersTolerance); - AssertEx.EqualTolerance(1, Length.FromKiloparsecs(meter.Kiloparsecs).Meters, KiloparsecsTolerance); - AssertEx.EqualTolerance(1, Length.FromKiloyards(meter.Kiloyards).Meters, KiloyardsTolerance); - AssertEx.EqualTolerance(1, Length.FromLightYears(meter.LightYears).Meters, LightYearsTolerance); - AssertEx.EqualTolerance(1, Length.FromMegalightYears(meter.MegalightYears).Meters, MegalightYearsTolerance); - AssertEx.EqualTolerance(1, Length.FromMegameters(meter.Megameters).Meters, MegametersTolerance); - AssertEx.EqualTolerance(1, Length.FromMegaparsecs(meter.Megaparsecs).Meters, MegaparsecsTolerance); - AssertEx.EqualTolerance(1, Length.FromMeters(meter.Meters).Meters, MetersTolerance); - AssertEx.EqualTolerance(1, Length.FromMicroinches(meter.Microinches).Meters, MicroinchesTolerance); - AssertEx.EqualTolerance(1, Length.FromMicrometers(meter.Micrometers).Meters, MicrometersTolerance); - AssertEx.EqualTolerance(1, Length.FromMils(meter.Mils).Meters, MilsTolerance); - AssertEx.EqualTolerance(1, Length.FromMiles(meter.Miles).Meters, MilesTolerance); - AssertEx.EqualTolerance(1, Length.FromMillimeters(meter.Millimeters).Meters, MillimetersTolerance); - AssertEx.EqualTolerance(1, Length.FromNanometers(meter.Nanometers).Meters, NanometersTolerance); - AssertEx.EqualTolerance(1, Length.FromNauticalMiles(meter.NauticalMiles).Meters, NauticalMilesTolerance); - AssertEx.EqualTolerance(1, Length.FromParsecs(meter.Parsecs).Meters, ParsecsTolerance); - AssertEx.EqualTolerance(1, Length.FromPicometers(meter.Picometers).Meters, PicometersTolerance); - AssertEx.EqualTolerance(1, Length.FromPrinterPicas(meter.PrinterPicas).Meters, PrinterPicasTolerance); - AssertEx.EqualTolerance(1, Length.FromPrinterPoints(meter.PrinterPoints).Meters, PrinterPointsTolerance); - AssertEx.EqualTolerance(1, Length.FromShackles(meter.Shackles).Meters, ShacklesTolerance); - AssertEx.EqualTolerance(1, Length.FromSolarRadiuses(meter.SolarRadiuses).Meters, SolarRadiusesTolerance); - AssertEx.EqualTolerance(1, Length.FromTwips(meter.Twips).Meters, TwipsTolerance); - AssertEx.EqualTolerance(1, Length.FromUsSurveyFeet(meter.UsSurveyFeet).Meters, UsSurveyFeetTolerance); - AssertEx.EqualTolerance(1, Length.FromYards(meter.Yards).Meters, YardsTolerance); + Length meter = Length.FromMeters(3); + Assert.Equal(3, Length.FromAngstroms(meter.Angstroms).Meters); + Assert.Equal(3, Length.FromAstronomicalUnits(meter.AstronomicalUnits).Meters); + Assert.Equal(3, Length.FromCentimeters(meter.Centimeters).Meters); + Assert.Equal(3, Length.FromChains(meter.Chains).Meters); + Assert.Equal(3, Length.FromDataMiles(meter.DataMiles).Meters); + Assert.Equal(3, Length.FromDecameters(meter.Decameters).Meters); + Assert.Equal(3, Length.FromDecimeters(meter.Decimeters).Meters); + Assert.Equal(3, Length.FromDtpPicas(meter.DtpPicas).Meters); + Assert.Equal(3, Length.FromDtpPoints(meter.DtpPoints).Meters); + Assert.Equal(3, Length.FromFathoms(meter.Fathoms).Meters); + Assert.Equal(3, Length.FromFemtometers(meter.Femtometers).Meters); + Assert.Equal(3, Length.FromFeet(meter.Feet).Meters); + Assert.Equal(3, Length.FromGigameters(meter.Gigameters).Meters); + Assert.Equal(3, Length.FromHands(meter.Hands).Meters); + Assert.Equal(3, Length.FromHectometers(meter.Hectometers).Meters); + Assert.Equal(3, Length.FromInches(meter.Inches).Meters); + Assert.Equal(3, Length.FromKilofeet(meter.Kilofeet).Meters); + Assert.Equal(3, Length.FromKilolightYears(meter.KilolightYears).Meters); + Assert.Equal(3, Length.FromKilometers(meter.Kilometers).Meters); + Assert.Equal(3, Length.FromKiloparsecs(meter.Kiloparsecs).Meters); + Assert.Equal(3, Length.FromKiloyards(meter.Kiloyards).Meters); + Assert.Equal(3, Length.FromLightYears(meter.LightYears).Meters); + Assert.Equal(3, Length.FromMegalightYears(meter.MegalightYears).Meters); + Assert.Equal(3, Length.FromMegameters(meter.Megameters).Meters); + Assert.Equal(3, Length.FromMegaparsecs(meter.Megaparsecs).Meters); + Assert.Equal(3, Length.FromMeters(meter.Meters).Meters); + Assert.Equal(3, Length.FromMicroinches(meter.Microinches).Meters); + Assert.Equal(3, Length.FromMicrometers(meter.Micrometers).Meters); + Assert.Equal(3, Length.FromMils(meter.Mils).Meters); + Assert.Equal(3, Length.FromMiles(meter.Miles).Meters); + Assert.Equal(3, Length.FromMillimeters(meter.Millimeters).Meters); + Assert.Equal(3, Length.FromNanometers(meter.Nanometers).Meters); + Assert.Equal(3, Length.FromNauticalMiles(meter.NauticalMiles).Meters); + Assert.Equal(3, Length.FromParsecs(meter.Parsecs).Meters); + Assert.Equal(3, Length.FromPicometers(meter.Picometers).Meters); + Assert.Equal(3, Length.FromPrinterPicas(meter.PrinterPicas).Meters); + Assert.Equal(3, Length.FromPrinterPoints(meter.PrinterPoints).Meters); + Assert.Equal(3, Length.FromShackles(meter.Shackles).Meters); + Assert.Equal(3, Length.FromSolarRadiuses(meter.SolarRadiuses).Meters); + Assert.Equal(3, Length.FromTwips(meter.Twips).Meters); + Assert.Equal(3, Length.FromUsSurveyFeet(meter.UsSurveyFeet).Meters); + Assert.Equal(3, Length.FromYards(meter.Yards).Meters); } [Fact] public void ArithmeticOperators() { Length v = Length.FromMeters(1); - AssertEx.EqualTolerance(-1, -v.Meters, MetersTolerance); - AssertEx.EqualTolerance(2, (Length.FromMeters(3)-v).Meters, MetersTolerance); - AssertEx.EqualTolerance(2, (v + v).Meters, MetersTolerance); - AssertEx.EqualTolerance(10, (v*10).Meters, MetersTolerance); - AssertEx.EqualTolerance(10, (10*v).Meters, MetersTolerance); - AssertEx.EqualTolerance(2, (Length.FromMeters(10)/5).Meters, MetersTolerance); - AssertEx.EqualTolerance(2, Length.FromMeters(10)/Length.FromMeters(5), MetersTolerance); + Assert.Equal(-1, -v.Meters); + Assert.Equal(2, (Length.FromMeters(3) - v).Meters); + Assert.Equal(2, (v + v).Meters); + Assert.Equal(10, (v * 10).Meters); + Assert.Equal(10, (10 * v).Meters); + Assert.Equal(2, (Length.FromMeters(10) / 5).Meters); + Assert.Equal(2, Length.FromMeters(10) / Length.FromMeters(5)); } [Fact] @@ -1635,8 +1652,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, LengthUnit.Meter, 1, LengthUnit.Meter, true)] // Same value and unit. [InlineData(1, LengthUnit.Meter, 2, LengthUnit.Meter, false)] // Different value. - [InlineData(2, LengthUnit.Meter, 1, LengthUnit.Angstrom, false)] // Different value and unit. - [InlineData(1, LengthUnit.Meter, 1, LengthUnit.Angstrom, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, LengthUnit unitA, double valueB, LengthUnit unitB, bool expectEqual) { var a = new Length(valueA, unitA); @@ -1696,8 +1711,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Length.FromMeters(firstValue); var otherQuantity = Length.FromMeters(secondValue); Length maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Length.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1716,7 +1731,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1729,6 +1744,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Length.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Length.Info.Units, Length.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Length.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1873,7 +1900,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Length.FromMeters(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Length), quantity.As(Length.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs index ffa57907a8..1788186305 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LevelTestsBase.g.cs @@ -108,6 +108,20 @@ public void Level_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void LevelInfo_CreateWithCustomUnitInfos() + { + LevelUnit[] expectedUnits = [LevelUnit.Decibel]; + + Level.LevelInfo quantityInfo = Level.LevelInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Level", quantityInfo.Name); + Assert.Equal(Level.Zero, quantityInfo.Zero); + Assert.Equal(Level.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void DecibelToLevelUnits() { @@ -223,7 +237,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() [Theory] [InlineData("en-US", "4.2 dB", LevelUnit.Decibel, 4.2)] [InlineData("en-US", "4.2 Np", LevelUnit.Neper, 4.2)] - public void Parse(string culture, string quantityString, LevelUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, LevelUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Level.Parse(quantityString); @@ -234,7 +248,7 @@ public void Parse(string culture, string quantityString, LevelUnit expectedUnit, [Theory] [InlineData("en-US", "4.2 dB", LevelUnit.Decibel, 4.2)] [InlineData("en-US", "4.2 Np", LevelUnit.Neper, 4.2)] - public void TryParse(string culture, string quantityString, LevelUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, LevelUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Level.TryParse(quantityString, out Level parsed)); @@ -376,6 +390,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LevelUnit unit) var quantity = Level.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -399,33 +414,35 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(LevelUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Level decibel = Level.FromDecibels(1); - AssertEx.EqualTolerance(1, Level.FromDecibels(decibel.Decibels).Decibels, DecibelsTolerance); - AssertEx.EqualTolerance(1, Level.FromNepers(decibel.Nepers).Decibels, NepersTolerance); + Level decibel = Level.FromDecibels(3); + Assert.Equal(3, Level.FromDecibels(decibel.Decibels).Decibels); + Assert.Equal(3, Level.FromNepers(decibel.Nepers).Decibels); } [Fact] public void LogarithmicArithmeticOperators() { Level v = Level.FromDecibels(40); - AssertEx.EqualTolerance(-40, -v.Decibels, NepersTolerance); + Assert.Equal(-40, -v.Decibels); AssertLogarithmicAddition(); AssertLogarithmicSubtraction(); - AssertEx.EqualTolerance(50, (v*10).Decibels, NepersTolerance); - AssertEx.EqualTolerance(50, (10*v).Decibels, NepersTolerance); - AssertEx.EqualTolerance(35, (v/5).Decibels, NepersTolerance); - AssertEx.EqualTolerance(35, v/Level.FromDecibels(5), NepersTolerance); + Assert.Equal(50, (v * 10).Decibels); + Assert.Equal(50, (10 * v).Decibels); + Assert.Equal(35, (v / 5).Decibels); + Assert.Equal(35, v / Level.FromDecibels(5)); } protected abstract void AssertLogarithmicAddition(); @@ -475,8 +492,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, LevelUnit.Decibel, 1, LevelUnit.Decibel, true)] // Same value and unit. [InlineData(1, LevelUnit.Decibel, 2, LevelUnit.Decibel, false)] // Different value. - [InlineData(2, LevelUnit.Decibel, 1, LevelUnit.Neper, false)] // Different value and unit. - [InlineData(1, LevelUnit.Decibel, 1, LevelUnit.Neper, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, LevelUnit unitA, double valueB, LevelUnit unitB, bool expectEqual) { var a = new Level(valueA, unitA); @@ -536,8 +551,8 @@ public void Equals_Logarithmic_WithTolerance(double firstValue, double secondVal var quantity = Level.FromDecibels(firstValue); var otherQuantity = Level.FromDecibels(secondValue); Level maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Level.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, largerTolerance)); @@ -558,7 +573,7 @@ public void Equals_Logarithmic_WithNegativeTolerance_DoesNotThrowArgumentOutOfRa [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -571,6 +586,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Level.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Level.Info.Units, Level.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Level.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -635,7 +662,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Level.FromDecibels(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Level), quantity.As(Level.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs index 2bcbacb628..3b3d3c18a8 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearDensityTestsBase.g.cs @@ -193,6 +193,20 @@ public void LinearDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void LinearDensityInfo_CreateWithCustomUnitInfos() + { + LinearDensityUnit[] expectedUnits = [LinearDensityUnit.KilogramPerMeter]; + + LinearDensity.LinearDensityInfo quantityInfo = LinearDensity.LinearDensityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("LinearDensity", quantityInfo.Name); + Assert.Equal(LinearDensity.Zero, quantityInfo.Zero); + Assert.Equal(LinearDensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void KilogramPerMeterToLinearDensityUnits() { @@ -395,7 +409,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 mg/mm", LinearDensityUnit.MilligramPerMillimeter, 4.2)] [InlineData("en-US", "4.2 lb/ft", LinearDensityUnit.PoundPerFoot, 4.2)] [InlineData("en-US", "4.2 lb/in", LinearDensityUnit.PoundPerInch, 4.2)] - public void Parse(string culture, string quantityString, LinearDensityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, LinearDensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = LinearDensity.Parse(quantityString); @@ -422,7 +436,7 @@ public void Parse(string culture, string quantityString, LinearDensityUnit expec [InlineData("en-US", "4.2 mg/mm", LinearDensityUnit.MilligramPerMillimeter, 4.2)] [InlineData("en-US", "4.2 lb/ft", LinearDensityUnit.PoundPerFoot, 4.2)] [InlineData("en-US", "4.2 lb/in", LinearDensityUnit.PoundPerInch, 4.2)] - public void TryParse(string culture, string quantityString, LinearDensityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, LinearDensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(LinearDensity.TryParse(quantityString, out LinearDensity parsed)); @@ -708,6 +722,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LinearDensityUni var quantity = LinearDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -731,49 +746,51 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(LinearDensityUnit u IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - LinearDensity kilogrampermeter = LinearDensity.FromKilogramsPerMeter(1); - AssertEx.EqualTolerance(1, LinearDensity.FromGramsPerCentimeter(kilogrampermeter.GramsPerCentimeter).KilogramsPerMeter, GramsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromGramsPerFoot(kilogrampermeter.GramsPerFoot).KilogramsPerMeter, GramsPerFootTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromGramsPerMeter(kilogrampermeter.GramsPerMeter).KilogramsPerMeter, GramsPerMeterTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromGramsPerMillimeter(kilogrampermeter.GramsPerMillimeter).KilogramsPerMeter, GramsPerMillimeterTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromKilogramsPerCentimeter(kilogrampermeter.KilogramsPerCentimeter).KilogramsPerMeter, KilogramsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromKilogramsPerFoot(kilogrampermeter.KilogramsPerFoot).KilogramsPerMeter, KilogramsPerFootTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromKilogramsPerMeter(kilogrampermeter.KilogramsPerMeter).KilogramsPerMeter, KilogramsPerMeterTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromKilogramsPerMillimeter(kilogrampermeter.KilogramsPerMillimeter).KilogramsPerMeter, KilogramsPerMillimeterTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromMicrogramsPerCentimeter(kilogrampermeter.MicrogramsPerCentimeter).KilogramsPerMeter, MicrogramsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromMicrogramsPerFoot(kilogrampermeter.MicrogramsPerFoot).KilogramsPerMeter, MicrogramsPerFootTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromMicrogramsPerMeter(kilogrampermeter.MicrogramsPerMeter).KilogramsPerMeter, MicrogramsPerMeterTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromMicrogramsPerMillimeter(kilogrampermeter.MicrogramsPerMillimeter).KilogramsPerMeter, MicrogramsPerMillimeterTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromMilligramsPerCentimeter(kilogrampermeter.MilligramsPerCentimeter).KilogramsPerMeter, MilligramsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromMilligramsPerFoot(kilogrampermeter.MilligramsPerFoot).KilogramsPerMeter, MilligramsPerFootTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromMilligramsPerMeter(kilogrampermeter.MilligramsPerMeter).KilogramsPerMeter, MilligramsPerMeterTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromMilligramsPerMillimeter(kilogrampermeter.MilligramsPerMillimeter).KilogramsPerMeter, MilligramsPerMillimeterTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromPoundsPerFoot(kilogrampermeter.PoundsPerFoot).KilogramsPerMeter, PoundsPerFootTolerance); - AssertEx.EqualTolerance(1, LinearDensity.FromPoundsPerInch(kilogrampermeter.PoundsPerInch).KilogramsPerMeter, PoundsPerInchTolerance); + LinearDensity kilogrampermeter = LinearDensity.FromKilogramsPerMeter(3); + Assert.Equal(3, LinearDensity.FromGramsPerCentimeter(kilogrampermeter.GramsPerCentimeter).KilogramsPerMeter); + Assert.Equal(3, LinearDensity.FromGramsPerFoot(kilogrampermeter.GramsPerFoot).KilogramsPerMeter); + Assert.Equal(3, LinearDensity.FromGramsPerMeter(kilogrampermeter.GramsPerMeter).KilogramsPerMeter); + Assert.Equal(3, LinearDensity.FromGramsPerMillimeter(kilogrampermeter.GramsPerMillimeter).KilogramsPerMeter); + Assert.Equal(3, LinearDensity.FromKilogramsPerCentimeter(kilogrampermeter.KilogramsPerCentimeter).KilogramsPerMeter); + Assert.Equal(3, LinearDensity.FromKilogramsPerFoot(kilogrampermeter.KilogramsPerFoot).KilogramsPerMeter); + Assert.Equal(3, LinearDensity.FromKilogramsPerMeter(kilogrampermeter.KilogramsPerMeter).KilogramsPerMeter); + Assert.Equal(3, LinearDensity.FromKilogramsPerMillimeter(kilogrampermeter.KilogramsPerMillimeter).KilogramsPerMeter); + Assert.Equal(3, LinearDensity.FromMicrogramsPerCentimeter(kilogrampermeter.MicrogramsPerCentimeter).KilogramsPerMeter); + Assert.Equal(3, LinearDensity.FromMicrogramsPerFoot(kilogrampermeter.MicrogramsPerFoot).KilogramsPerMeter); + Assert.Equal(3, LinearDensity.FromMicrogramsPerMeter(kilogrampermeter.MicrogramsPerMeter).KilogramsPerMeter); + Assert.Equal(3, LinearDensity.FromMicrogramsPerMillimeter(kilogrampermeter.MicrogramsPerMillimeter).KilogramsPerMeter); + Assert.Equal(3, LinearDensity.FromMilligramsPerCentimeter(kilogrampermeter.MilligramsPerCentimeter).KilogramsPerMeter); + Assert.Equal(3, LinearDensity.FromMilligramsPerFoot(kilogrampermeter.MilligramsPerFoot).KilogramsPerMeter); + Assert.Equal(3, LinearDensity.FromMilligramsPerMeter(kilogrampermeter.MilligramsPerMeter).KilogramsPerMeter); + Assert.Equal(3, LinearDensity.FromMilligramsPerMillimeter(kilogrampermeter.MilligramsPerMillimeter).KilogramsPerMeter); + Assert.Equal(3, LinearDensity.FromPoundsPerFoot(kilogrampermeter.PoundsPerFoot).KilogramsPerMeter); + Assert.Equal(3, LinearDensity.FromPoundsPerInch(kilogrampermeter.PoundsPerInch).KilogramsPerMeter); } [Fact] public void ArithmeticOperators() { LinearDensity v = LinearDensity.FromKilogramsPerMeter(1); - AssertEx.EqualTolerance(-1, -v.KilogramsPerMeter, KilogramsPerMeterTolerance); - AssertEx.EqualTolerance(2, (LinearDensity.FromKilogramsPerMeter(3)-v).KilogramsPerMeter, KilogramsPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).KilogramsPerMeter, KilogramsPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).KilogramsPerMeter, KilogramsPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).KilogramsPerMeter, KilogramsPerMeterTolerance); - AssertEx.EqualTolerance(2, (LinearDensity.FromKilogramsPerMeter(10)/5).KilogramsPerMeter, KilogramsPerMeterTolerance); - AssertEx.EqualTolerance(2, LinearDensity.FromKilogramsPerMeter(10)/LinearDensity.FromKilogramsPerMeter(5), KilogramsPerMeterTolerance); + Assert.Equal(-1, -v.KilogramsPerMeter); + Assert.Equal(2, (LinearDensity.FromKilogramsPerMeter(3) - v).KilogramsPerMeter); + Assert.Equal(2, (v + v).KilogramsPerMeter); + Assert.Equal(10, (v * 10).KilogramsPerMeter); + Assert.Equal(10, (10 * v).KilogramsPerMeter); + Assert.Equal(2, (LinearDensity.FromKilogramsPerMeter(10) / 5).KilogramsPerMeter); + Assert.Equal(2, LinearDensity.FromKilogramsPerMeter(10) / LinearDensity.FromKilogramsPerMeter(5)); } [Fact] @@ -819,8 +836,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, LinearDensityUnit.KilogramPerMeter, 1, LinearDensityUnit.KilogramPerMeter, true)] // Same value and unit. [InlineData(1, LinearDensityUnit.KilogramPerMeter, 2, LinearDensityUnit.KilogramPerMeter, false)] // Different value. - [InlineData(2, LinearDensityUnit.KilogramPerMeter, 1, LinearDensityUnit.GramPerCentimeter, false)] // Different value and unit. - [InlineData(1, LinearDensityUnit.KilogramPerMeter, 1, LinearDensityUnit.GramPerCentimeter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, LinearDensityUnit unitA, double valueB, LinearDensityUnit unitB, bool expectEqual) { var a = new LinearDensity(valueA, unitA); @@ -880,8 +895,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = LinearDensity.FromKilogramsPerMeter(firstValue); var otherQuantity = LinearDensity.FromKilogramsPerMeter(secondValue); LinearDensity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, LinearDensity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -900,7 +915,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -913,6 +928,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(LinearDensity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(LinearDensity.Info.Units, LinearDensity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, LinearDensity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1009,7 +1036,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = LinearDensity.FromKilogramsPerMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(LinearDensity), quantity.As(LinearDensity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs index 132da99ab7..071d0a8ae1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LinearPowerDensityTestsBase.g.cs @@ -221,6 +221,20 @@ public void LinearPowerDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantit Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void LinearPowerDensityInfo_CreateWithCustomUnitInfos() + { + LinearPowerDensityUnit[] expectedUnits = [LinearPowerDensityUnit.WattPerMeter]; + + LinearPowerDensity.LinearPowerDensityInfo quantityInfo = LinearPowerDensity.LinearPowerDensityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("LinearPowerDensity", quantityInfo.Name); + Assert.Equal(LinearPowerDensity.Zero, quantityInfo.Zero); + Assert.Equal(LinearPowerDensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void WattPerMeterToLinearPowerDensityUnits() { @@ -444,7 +458,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 W/in", LinearPowerDensityUnit.WattPerInch, 4.2)] [InlineData("en-US", "4.2 W/m", LinearPowerDensityUnit.WattPerMeter, 4.2)] [InlineData("en-US", "4.2 W/mm", LinearPowerDensityUnit.WattPerMillimeter, 4.2)] - public void Parse(string culture, string quantityString, LinearPowerDensityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, LinearPowerDensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = LinearPowerDensity.Parse(quantityString); @@ -478,7 +492,7 @@ public void Parse(string culture, string quantityString, LinearPowerDensityUnit [InlineData("en-US", "4.2 W/in", LinearPowerDensityUnit.WattPerInch, 4.2)] [InlineData("en-US", "4.2 W/m", LinearPowerDensityUnit.WattPerMeter, 4.2)] [InlineData("en-US", "4.2 W/mm", LinearPowerDensityUnit.WattPerMillimeter, 4.2)] - public void TryParse(string culture, string quantityString, LinearPowerDensityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, LinearPowerDensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(LinearPowerDensity.TryParse(quantityString, out LinearPowerDensity parsed)); @@ -827,6 +841,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LinearPowerDensi var quantity = LinearPowerDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -850,56 +865,58 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(LinearPowerDensityU IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - LinearPowerDensity wattpermeter = LinearPowerDensity.FromWattsPerMeter(1); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromGigawattsPerCentimeter(wattpermeter.GigawattsPerCentimeter).WattsPerMeter, GigawattsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromGigawattsPerFoot(wattpermeter.GigawattsPerFoot).WattsPerMeter, GigawattsPerFootTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromGigawattsPerInch(wattpermeter.GigawattsPerInch).WattsPerMeter, GigawattsPerInchTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromGigawattsPerMeter(wattpermeter.GigawattsPerMeter).WattsPerMeter, GigawattsPerMeterTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromGigawattsPerMillimeter(wattpermeter.GigawattsPerMillimeter).WattsPerMeter, GigawattsPerMillimeterTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromKilowattsPerCentimeter(wattpermeter.KilowattsPerCentimeter).WattsPerMeter, KilowattsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromKilowattsPerFoot(wattpermeter.KilowattsPerFoot).WattsPerMeter, KilowattsPerFootTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromKilowattsPerInch(wattpermeter.KilowattsPerInch).WattsPerMeter, KilowattsPerInchTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromKilowattsPerMeter(wattpermeter.KilowattsPerMeter).WattsPerMeter, KilowattsPerMeterTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromKilowattsPerMillimeter(wattpermeter.KilowattsPerMillimeter).WattsPerMeter, KilowattsPerMillimeterTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromMegawattsPerCentimeter(wattpermeter.MegawattsPerCentimeter).WattsPerMeter, MegawattsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromMegawattsPerFoot(wattpermeter.MegawattsPerFoot).WattsPerMeter, MegawattsPerFootTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromMegawattsPerInch(wattpermeter.MegawattsPerInch).WattsPerMeter, MegawattsPerInchTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromMegawattsPerMeter(wattpermeter.MegawattsPerMeter).WattsPerMeter, MegawattsPerMeterTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromMegawattsPerMillimeter(wattpermeter.MegawattsPerMillimeter).WattsPerMeter, MegawattsPerMillimeterTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromMilliwattsPerCentimeter(wattpermeter.MilliwattsPerCentimeter).WattsPerMeter, MilliwattsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromMilliwattsPerFoot(wattpermeter.MilliwattsPerFoot).WattsPerMeter, MilliwattsPerFootTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromMilliwattsPerInch(wattpermeter.MilliwattsPerInch).WattsPerMeter, MilliwattsPerInchTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromMilliwattsPerMeter(wattpermeter.MilliwattsPerMeter).WattsPerMeter, MilliwattsPerMeterTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromMilliwattsPerMillimeter(wattpermeter.MilliwattsPerMillimeter).WattsPerMeter, MilliwattsPerMillimeterTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromWattsPerCentimeter(wattpermeter.WattsPerCentimeter).WattsPerMeter, WattsPerCentimeterTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromWattsPerFoot(wattpermeter.WattsPerFoot).WattsPerMeter, WattsPerFootTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromWattsPerInch(wattpermeter.WattsPerInch).WattsPerMeter, WattsPerInchTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromWattsPerMeter(wattpermeter.WattsPerMeter).WattsPerMeter, WattsPerMeterTolerance); - AssertEx.EqualTolerance(1, LinearPowerDensity.FromWattsPerMillimeter(wattpermeter.WattsPerMillimeter).WattsPerMeter, WattsPerMillimeterTolerance); + LinearPowerDensity wattpermeter = LinearPowerDensity.FromWattsPerMeter(3); + Assert.Equal(3, LinearPowerDensity.FromGigawattsPerCentimeter(wattpermeter.GigawattsPerCentimeter).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromGigawattsPerFoot(wattpermeter.GigawattsPerFoot).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromGigawattsPerInch(wattpermeter.GigawattsPerInch).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromGigawattsPerMeter(wattpermeter.GigawattsPerMeter).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromGigawattsPerMillimeter(wattpermeter.GigawattsPerMillimeter).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromKilowattsPerCentimeter(wattpermeter.KilowattsPerCentimeter).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromKilowattsPerFoot(wattpermeter.KilowattsPerFoot).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromKilowattsPerInch(wattpermeter.KilowattsPerInch).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromKilowattsPerMeter(wattpermeter.KilowattsPerMeter).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromKilowattsPerMillimeter(wattpermeter.KilowattsPerMillimeter).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromMegawattsPerCentimeter(wattpermeter.MegawattsPerCentimeter).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromMegawattsPerFoot(wattpermeter.MegawattsPerFoot).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromMegawattsPerInch(wattpermeter.MegawattsPerInch).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromMegawattsPerMeter(wattpermeter.MegawattsPerMeter).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromMegawattsPerMillimeter(wattpermeter.MegawattsPerMillimeter).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromMilliwattsPerCentimeter(wattpermeter.MilliwattsPerCentimeter).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromMilliwattsPerFoot(wattpermeter.MilliwattsPerFoot).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromMilliwattsPerInch(wattpermeter.MilliwattsPerInch).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromMilliwattsPerMeter(wattpermeter.MilliwattsPerMeter).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromMilliwattsPerMillimeter(wattpermeter.MilliwattsPerMillimeter).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromWattsPerCentimeter(wattpermeter.WattsPerCentimeter).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromWattsPerFoot(wattpermeter.WattsPerFoot).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromWattsPerInch(wattpermeter.WattsPerInch).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromWattsPerMeter(wattpermeter.WattsPerMeter).WattsPerMeter); + Assert.Equal(3, LinearPowerDensity.FromWattsPerMillimeter(wattpermeter.WattsPerMillimeter).WattsPerMeter); } [Fact] public void ArithmeticOperators() { LinearPowerDensity v = LinearPowerDensity.FromWattsPerMeter(1); - AssertEx.EqualTolerance(-1, -v.WattsPerMeter, WattsPerMeterTolerance); - AssertEx.EqualTolerance(2, (LinearPowerDensity.FromWattsPerMeter(3)-v).WattsPerMeter, WattsPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).WattsPerMeter, WattsPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).WattsPerMeter, WattsPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).WattsPerMeter, WattsPerMeterTolerance); - AssertEx.EqualTolerance(2, (LinearPowerDensity.FromWattsPerMeter(10)/5).WattsPerMeter, WattsPerMeterTolerance); - AssertEx.EqualTolerance(2, LinearPowerDensity.FromWattsPerMeter(10)/LinearPowerDensity.FromWattsPerMeter(5), WattsPerMeterTolerance); + Assert.Equal(-1, -v.WattsPerMeter); + Assert.Equal(2, (LinearPowerDensity.FromWattsPerMeter(3) - v).WattsPerMeter); + Assert.Equal(2, (v + v).WattsPerMeter); + Assert.Equal(10, (v * 10).WattsPerMeter); + Assert.Equal(10, (10 * v).WattsPerMeter); + Assert.Equal(2, (LinearPowerDensity.FromWattsPerMeter(10) / 5).WattsPerMeter); + Assert.Equal(2, LinearPowerDensity.FromWattsPerMeter(10) / LinearPowerDensity.FromWattsPerMeter(5)); } [Fact] @@ -945,8 +962,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, LinearPowerDensityUnit.WattPerMeter, 1, LinearPowerDensityUnit.WattPerMeter, true)] // Same value and unit. [InlineData(1, LinearPowerDensityUnit.WattPerMeter, 2, LinearPowerDensityUnit.WattPerMeter, false)] // Different value. - [InlineData(2, LinearPowerDensityUnit.WattPerMeter, 1, LinearPowerDensityUnit.GigawattPerCentimeter, false)] // Different value and unit. - [InlineData(1, LinearPowerDensityUnit.WattPerMeter, 1, LinearPowerDensityUnit.GigawattPerCentimeter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, LinearPowerDensityUnit unitA, double valueB, LinearPowerDensityUnit unitB, bool expectEqual) { var a = new LinearPowerDensity(valueA, unitA); @@ -1006,8 +1021,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = LinearPowerDensity.FromWattsPerMeter(firstValue); var otherQuantity = LinearPowerDensity.FromWattsPerMeter(secondValue); LinearPowerDensity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, LinearPowerDensity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1026,7 +1041,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1039,6 +1054,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(LinearPowerDensity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(LinearPowerDensity.Info.Units, LinearPowerDensity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, LinearPowerDensity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1149,7 +1176,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = LinearPowerDensity.FromWattsPerMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(LinearPowerDensity), quantity.As(LinearPowerDensity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminanceTestsBase.g.cs index ee02e562e4..2259466ac7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminanceTestsBase.g.cs @@ -161,6 +161,20 @@ public void Luminance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void LuminanceInfo_CreateWithCustomUnitInfos() + { + LuminanceUnit[] expectedUnits = [LuminanceUnit.CandelaPerSquareMeter]; + + Luminance.LuminanceInfo quantityInfo = Luminance.LuminanceInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Luminance", quantityInfo.Name); + Assert.Equal(Luminance.Zero, quantityInfo.Zero); + Assert.Equal(Luminance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void CandelaPerSquareMeterToLuminanceUnits() { @@ -339,7 +353,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 mCd/m²", LuminanceUnit.MillicandelaPerSquareMeter, 4.2)] [InlineData("en-US", "4.2 nCd/m²", LuminanceUnit.NanocandelaPerSquareMeter, 4.2)] [InlineData("en-US", "4.2 nt", LuminanceUnit.Nit, 4.2)] - public void Parse(string culture, string quantityString, LuminanceUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, LuminanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Luminance.Parse(quantityString); @@ -358,7 +372,7 @@ public void Parse(string culture, string quantityString, LuminanceUnit expectedU [InlineData("en-US", "4.2 mCd/m²", LuminanceUnit.MillicandelaPerSquareMeter, 4.2)] [InlineData("en-US", "4.2 nCd/m²", LuminanceUnit.NanocandelaPerSquareMeter, 4.2)] [InlineData("en-US", "4.2 nt", LuminanceUnit.Nit, 4.2)] - public void TryParse(string culture, string quantityString, LuminanceUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, LuminanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Luminance.TryParse(quantityString, out Luminance parsed)); @@ -572,6 +586,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LuminanceUnit un var quantity = Luminance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -595,41 +610,43 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(LuminanceUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Luminance candelapersquaremeter = Luminance.FromCandelasPerSquareMeter(1); - AssertEx.EqualTolerance(1, Luminance.FromCandelasPerSquareFoot(candelapersquaremeter.CandelasPerSquareFoot).CandelasPerSquareMeter, CandelasPerSquareFootTolerance); - AssertEx.EqualTolerance(1, Luminance.FromCandelasPerSquareInch(candelapersquaremeter.CandelasPerSquareInch).CandelasPerSquareMeter, CandelasPerSquareInchTolerance); - AssertEx.EqualTolerance(1, Luminance.FromCandelasPerSquareMeter(candelapersquaremeter.CandelasPerSquareMeter).CandelasPerSquareMeter, CandelasPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Luminance.FromCenticandelasPerSquareMeter(candelapersquaremeter.CenticandelasPerSquareMeter).CandelasPerSquareMeter, CenticandelasPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Luminance.FromDecicandelasPerSquareMeter(candelapersquaremeter.DecicandelasPerSquareMeter).CandelasPerSquareMeter, DecicandelasPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Luminance.FromKilocandelasPerSquareMeter(candelapersquaremeter.KilocandelasPerSquareMeter).CandelasPerSquareMeter, KilocandelasPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Luminance.FromMicrocandelasPerSquareMeter(candelapersquaremeter.MicrocandelasPerSquareMeter).CandelasPerSquareMeter, MicrocandelasPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Luminance.FromMillicandelasPerSquareMeter(candelapersquaremeter.MillicandelasPerSquareMeter).CandelasPerSquareMeter, MillicandelasPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Luminance.FromNanocandelasPerSquareMeter(candelapersquaremeter.NanocandelasPerSquareMeter).CandelasPerSquareMeter, NanocandelasPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Luminance.FromNits(candelapersquaremeter.Nits).CandelasPerSquareMeter, NitsTolerance); + Luminance candelapersquaremeter = Luminance.FromCandelasPerSquareMeter(3); + Assert.Equal(3, Luminance.FromCandelasPerSquareFoot(candelapersquaremeter.CandelasPerSquareFoot).CandelasPerSquareMeter); + Assert.Equal(3, Luminance.FromCandelasPerSquareInch(candelapersquaremeter.CandelasPerSquareInch).CandelasPerSquareMeter); + Assert.Equal(3, Luminance.FromCandelasPerSquareMeter(candelapersquaremeter.CandelasPerSquareMeter).CandelasPerSquareMeter); + Assert.Equal(3, Luminance.FromCenticandelasPerSquareMeter(candelapersquaremeter.CenticandelasPerSquareMeter).CandelasPerSquareMeter); + Assert.Equal(3, Luminance.FromDecicandelasPerSquareMeter(candelapersquaremeter.DecicandelasPerSquareMeter).CandelasPerSquareMeter); + Assert.Equal(3, Luminance.FromKilocandelasPerSquareMeter(candelapersquaremeter.KilocandelasPerSquareMeter).CandelasPerSquareMeter); + Assert.Equal(3, Luminance.FromMicrocandelasPerSquareMeter(candelapersquaremeter.MicrocandelasPerSquareMeter).CandelasPerSquareMeter); + Assert.Equal(3, Luminance.FromMillicandelasPerSquareMeter(candelapersquaremeter.MillicandelasPerSquareMeter).CandelasPerSquareMeter); + Assert.Equal(3, Luminance.FromNanocandelasPerSquareMeter(candelapersquaremeter.NanocandelasPerSquareMeter).CandelasPerSquareMeter); + Assert.Equal(3, Luminance.FromNits(candelapersquaremeter.Nits).CandelasPerSquareMeter); } [Fact] public void ArithmeticOperators() { Luminance v = Luminance.FromCandelasPerSquareMeter(1); - AssertEx.EqualTolerance(-1, -v.CandelasPerSquareMeter, CandelasPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (Luminance.FromCandelasPerSquareMeter(3)-v).CandelasPerSquareMeter, CandelasPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).CandelasPerSquareMeter, CandelasPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).CandelasPerSquareMeter, CandelasPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).CandelasPerSquareMeter, CandelasPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (Luminance.FromCandelasPerSquareMeter(10)/5).CandelasPerSquareMeter, CandelasPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, Luminance.FromCandelasPerSquareMeter(10)/Luminance.FromCandelasPerSquareMeter(5), CandelasPerSquareMeterTolerance); + Assert.Equal(-1, -v.CandelasPerSquareMeter); + Assert.Equal(2, (Luminance.FromCandelasPerSquareMeter(3) - v).CandelasPerSquareMeter); + Assert.Equal(2, (v + v).CandelasPerSquareMeter); + Assert.Equal(10, (v * 10).CandelasPerSquareMeter); + Assert.Equal(10, (10 * v).CandelasPerSquareMeter); + Assert.Equal(2, (Luminance.FromCandelasPerSquareMeter(10) / 5).CandelasPerSquareMeter); + Assert.Equal(2, Luminance.FromCandelasPerSquareMeter(10) / Luminance.FromCandelasPerSquareMeter(5)); } [Fact] @@ -675,8 +692,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, LuminanceUnit.CandelaPerSquareMeter, 1, LuminanceUnit.CandelaPerSquareMeter, true)] // Same value and unit. [InlineData(1, LuminanceUnit.CandelaPerSquareMeter, 2, LuminanceUnit.CandelaPerSquareMeter, false)] // Different value. - [InlineData(2, LuminanceUnit.CandelaPerSquareMeter, 1, LuminanceUnit.CandelaPerSquareFoot, false)] // Different value and unit. - [InlineData(1, LuminanceUnit.CandelaPerSquareMeter, 1, LuminanceUnit.CandelaPerSquareFoot, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, LuminanceUnit unitA, double valueB, LuminanceUnit unitB, bool expectEqual) { var a = new Luminance(valueA, unitA); @@ -736,8 +751,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Luminance.FromCandelasPerSquareMeter(firstValue); var otherQuantity = Luminance.FromCandelasPerSquareMeter(secondValue); Luminance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Luminance.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -756,7 +771,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -769,6 +784,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Luminance.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Luminance.Info.Units, Luminance.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Luminance.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -849,7 +876,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Luminance.FromCandelasPerSquareMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Luminance), quantity.As(Luminance.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs index 36d9d17578..4520653299 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminosityTestsBase.g.cs @@ -177,6 +177,20 @@ public void Luminosity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void LuminosityInfo_CreateWithCustomUnitInfos() + { + LuminosityUnit[] expectedUnits = [LuminosityUnit.Watt]; + + Luminosity.LuminosityInfo quantityInfo = Luminosity.LuminosityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Luminosity", quantityInfo.Name); + Assert.Equal(Luminosity.Zero, quantityInfo.Zero); + Assert.Equal(Luminosity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void WattToLuminosityUnits() { @@ -367,7 +381,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 L⊙", LuminosityUnit.SolarLuminosity, 4.2)] [InlineData("en-US", "4.2 TW", LuminosityUnit.Terawatt, 4.2)] [InlineData("en-US", "4.2 W", LuminosityUnit.Watt, 4.2)] - public void Parse(string culture, string quantityString, LuminosityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, LuminosityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Luminosity.Parse(quantityString); @@ -390,7 +404,7 @@ public void Parse(string culture, string quantityString, LuminosityUnit expected [InlineData("en-US", "4.2 L⊙", LuminosityUnit.SolarLuminosity, 4.2)] [InlineData("en-US", "4.2 TW", LuminosityUnit.Terawatt, 4.2)] [InlineData("en-US", "4.2 W", LuminosityUnit.Watt, 4.2)] - public void TryParse(string culture, string quantityString, LuminosityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, LuminosityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Luminosity.TryParse(quantityString, out Luminosity parsed)); @@ -640,6 +654,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LuminosityUnit u var quantity = Luminosity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -663,45 +678,47 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(LuminosityUnit unit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Luminosity watt = Luminosity.FromWatts(1); - AssertEx.EqualTolerance(1, Luminosity.FromDecawatts(watt.Decawatts).Watts, DecawattsTolerance); - AssertEx.EqualTolerance(1, Luminosity.FromDeciwatts(watt.Deciwatts).Watts, DeciwattsTolerance); - AssertEx.EqualTolerance(1, Luminosity.FromFemtowatts(watt.Femtowatts).Watts, FemtowattsTolerance); - AssertEx.EqualTolerance(1, Luminosity.FromGigawatts(watt.Gigawatts).Watts, GigawattsTolerance); - AssertEx.EqualTolerance(1, Luminosity.FromKilowatts(watt.Kilowatts).Watts, KilowattsTolerance); - AssertEx.EqualTolerance(1, Luminosity.FromMegawatts(watt.Megawatts).Watts, MegawattsTolerance); - AssertEx.EqualTolerance(1, Luminosity.FromMicrowatts(watt.Microwatts).Watts, MicrowattsTolerance); - AssertEx.EqualTolerance(1, Luminosity.FromMilliwatts(watt.Milliwatts).Watts, MilliwattsTolerance); - AssertEx.EqualTolerance(1, Luminosity.FromNanowatts(watt.Nanowatts).Watts, NanowattsTolerance); - AssertEx.EqualTolerance(1, Luminosity.FromPetawatts(watt.Petawatts).Watts, PetawattsTolerance); - AssertEx.EqualTolerance(1, Luminosity.FromPicowatts(watt.Picowatts).Watts, PicowattsTolerance); - AssertEx.EqualTolerance(1, Luminosity.FromSolarLuminosities(watt.SolarLuminosities).Watts, SolarLuminositiesTolerance); - AssertEx.EqualTolerance(1, Luminosity.FromTerawatts(watt.Terawatts).Watts, TerawattsTolerance); - AssertEx.EqualTolerance(1, Luminosity.FromWatts(watt.Watts).Watts, WattsTolerance); + Luminosity watt = Luminosity.FromWatts(3); + Assert.Equal(3, Luminosity.FromDecawatts(watt.Decawatts).Watts); + Assert.Equal(3, Luminosity.FromDeciwatts(watt.Deciwatts).Watts); + Assert.Equal(3, Luminosity.FromFemtowatts(watt.Femtowatts).Watts); + Assert.Equal(3, Luminosity.FromGigawatts(watt.Gigawatts).Watts); + Assert.Equal(3, Luminosity.FromKilowatts(watt.Kilowatts).Watts); + Assert.Equal(3, Luminosity.FromMegawatts(watt.Megawatts).Watts); + Assert.Equal(3, Luminosity.FromMicrowatts(watt.Microwatts).Watts); + Assert.Equal(3, Luminosity.FromMilliwatts(watt.Milliwatts).Watts); + Assert.Equal(3, Luminosity.FromNanowatts(watt.Nanowatts).Watts); + Assert.Equal(3, Luminosity.FromPetawatts(watt.Petawatts).Watts); + Assert.Equal(3, Luminosity.FromPicowatts(watt.Picowatts).Watts); + Assert.Equal(3, Luminosity.FromSolarLuminosities(watt.SolarLuminosities).Watts); + Assert.Equal(3, Luminosity.FromTerawatts(watt.Terawatts).Watts); + Assert.Equal(3, Luminosity.FromWatts(watt.Watts).Watts); } [Fact] public void ArithmeticOperators() { Luminosity v = Luminosity.FromWatts(1); - AssertEx.EqualTolerance(-1, -v.Watts, WattsTolerance); - AssertEx.EqualTolerance(2, (Luminosity.FromWatts(3)-v).Watts, WattsTolerance); - AssertEx.EqualTolerance(2, (v + v).Watts, WattsTolerance); - AssertEx.EqualTolerance(10, (v*10).Watts, WattsTolerance); - AssertEx.EqualTolerance(10, (10*v).Watts, WattsTolerance); - AssertEx.EqualTolerance(2, (Luminosity.FromWatts(10)/5).Watts, WattsTolerance); - AssertEx.EqualTolerance(2, Luminosity.FromWatts(10)/Luminosity.FromWatts(5), WattsTolerance); + Assert.Equal(-1, -v.Watts); + Assert.Equal(2, (Luminosity.FromWatts(3) - v).Watts); + Assert.Equal(2, (v + v).Watts); + Assert.Equal(10, (v * 10).Watts); + Assert.Equal(10, (10 * v).Watts); + Assert.Equal(2, (Luminosity.FromWatts(10) / 5).Watts); + Assert.Equal(2, Luminosity.FromWatts(10) / Luminosity.FromWatts(5)); } [Fact] @@ -747,8 +764,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, LuminosityUnit.Watt, 1, LuminosityUnit.Watt, true)] // Same value and unit. [InlineData(1, LuminosityUnit.Watt, 2, LuminosityUnit.Watt, false)] // Different value. - [InlineData(2, LuminosityUnit.Watt, 1, LuminosityUnit.Decawatt, false)] // Different value and unit. - [InlineData(1, LuminosityUnit.Watt, 1, LuminosityUnit.Decawatt, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, LuminosityUnit unitA, double valueB, LuminosityUnit unitB, bool expectEqual) { var a = new Luminosity(valueA, unitA); @@ -808,8 +823,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Luminosity.FromWatts(firstValue); var otherQuantity = Luminosity.FromWatts(secondValue); Luminosity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Luminosity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -828,7 +843,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -841,6 +856,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Luminosity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Luminosity.Info.Units, Luminosity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Luminosity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -929,7 +956,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Luminosity.FromWatts(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Luminosity), quantity.As(Luminosity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs index 4abb983c91..bd93b11d8a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousFluxTestsBase.g.cs @@ -125,6 +125,20 @@ public void LuminousFlux_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void LuminousFluxInfo_CreateWithCustomUnitInfos() + { + LuminousFluxUnit[] expectedUnits = [LuminousFluxUnit.Lumen]; + + LuminousFlux.LuminousFluxInfo quantityInfo = LuminousFlux.LuminousFluxInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("LuminousFlux", quantityInfo.Name); + Assert.Equal(LuminousFlux.Zero, quantityInfo.Zero); + Assert.Equal(LuminousFlux.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void LumenToLuminousFluxUnits() { @@ -276,7 +290,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Theory] [InlineData("en-US", "4.2 lm", LuminousFluxUnit.Lumen, 4.2)] - public void Parse(string culture, string quantityString, LuminousFluxUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, LuminousFluxUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = LuminousFlux.Parse(quantityString); @@ -286,7 +300,7 @@ public void Parse(string culture, string quantityString, LuminousFluxUnit expect [Theory] [InlineData("en-US", "4.2 lm", LuminousFluxUnit.Lumen, 4.2)] - public void TryParse(string culture, string quantityString, LuminousFluxUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, LuminousFluxUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(LuminousFlux.TryParse(quantityString, out LuminousFlux parsed)); @@ -419,6 +433,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LuminousFluxUnit var quantity = LuminousFlux.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -442,32 +457,34 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(LuminousFluxUnit un IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - LuminousFlux lumen = LuminousFlux.FromLumens(1); - AssertEx.EqualTolerance(1, LuminousFlux.FromLumens(lumen.Lumens).Lumens, LumensTolerance); + LuminousFlux lumen = LuminousFlux.FromLumens(3); + Assert.Equal(3, LuminousFlux.FromLumens(lumen.Lumens).Lumens); } [Fact] public void ArithmeticOperators() { LuminousFlux v = LuminousFlux.FromLumens(1); - AssertEx.EqualTolerance(-1, -v.Lumens, LumensTolerance); - AssertEx.EqualTolerance(2, (LuminousFlux.FromLumens(3)-v).Lumens, LumensTolerance); - AssertEx.EqualTolerance(2, (v + v).Lumens, LumensTolerance); - AssertEx.EqualTolerance(10, (v*10).Lumens, LumensTolerance); - AssertEx.EqualTolerance(10, (10*v).Lumens, LumensTolerance); - AssertEx.EqualTolerance(2, (LuminousFlux.FromLumens(10)/5).Lumens, LumensTolerance); - AssertEx.EqualTolerance(2, LuminousFlux.FromLumens(10)/LuminousFlux.FromLumens(5), LumensTolerance); + Assert.Equal(-1, -v.Lumens); + Assert.Equal(2, (LuminousFlux.FromLumens(3) - v).Lumens); + Assert.Equal(2, (v + v).Lumens); + Assert.Equal(10, (v * 10).Lumens); + Assert.Equal(10, (10 * v).Lumens); + Assert.Equal(2, (LuminousFlux.FromLumens(10) / 5).Lumens); + Assert.Equal(2, LuminousFlux.FromLumens(10) / LuminousFlux.FromLumens(5)); } [Fact] @@ -513,7 +530,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, LuminousFluxUnit.Lumen, 1, LuminousFluxUnit.Lumen, true)] // Same value and unit. [InlineData(1, LuminousFluxUnit.Lumen, 2, LuminousFluxUnit.Lumen, false)] // Different value. - [InlineData(2, LuminousFluxUnit.Lumen, 1, LuminousFluxUnit.Lumen, false)] // Different value and unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, LuminousFluxUnit unitA, double valueB, LuminousFluxUnit unitB, bool expectEqual) { var a = new LuminousFlux(valueA, unitA); @@ -573,8 +589,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = LuminousFlux.FromLumens(firstValue); var otherQuantity = LuminousFlux.FromLumens(secondValue); LuminousFlux maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, LuminousFlux.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -593,7 +609,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -606,6 +622,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(LuminousFlux.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(LuminousFlux.Info.Units, LuminousFlux.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, LuminousFlux.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -668,7 +696,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = LuminousFlux.FromLumens(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(LuminousFlux), quantity.As(LuminousFlux.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs index 9758f9de08..296bc7101d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/LuminousIntensityTestsBase.g.cs @@ -125,6 +125,20 @@ public void LuminousIntensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void LuminousIntensityInfo_CreateWithCustomUnitInfos() + { + LuminousIntensityUnit[] expectedUnits = [LuminousIntensityUnit.Candela]; + + LuminousIntensity.LuminousIntensityInfo quantityInfo = LuminousIntensity.LuminousIntensityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("LuminousIntensity", quantityInfo.Name); + Assert.Equal(LuminousIntensity.Zero, quantityInfo.Zero); + Assert.Equal(LuminousIntensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void CandelaToLuminousIntensityUnits() { @@ -276,7 +290,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Theory] [InlineData("en-US", "4.2 cd", LuminousIntensityUnit.Candela, 4.2)] - public void Parse(string culture, string quantityString, LuminousIntensityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, LuminousIntensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = LuminousIntensity.Parse(quantityString); @@ -286,7 +300,7 @@ public void Parse(string culture, string quantityString, LuminousIntensityUnit e [Theory] [InlineData("en-US", "4.2 cd", LuminousIntensityUnit.Candela, 4.2)] - public void TryParse(string culture, string quantityString, LuminousIntensityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, LuminousIntensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(LuminousIntensity.TryParse(quantityString, out LuminousIntensity parsed)); @@ -419,6 +433,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(LuminousIntensit var quantity = LuminousIntensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -442,32 +457,34 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(LuminousIntensityUn IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - LuminousIntensity candela = LuminousIntensity.FromCandela(1); - AssertEx.EqualTolerance(1, LuminousIntensity.FromCandela(candela.Candela).Candela, CandelaTolerance); + LuminousIntensity candela = LuminousIntensity.FromCandela(3); + Assert.Equal(3, LuminousIntensity.FromCandela(candela.Candela).Candela); } [Fact] public void ArithmeticOperators() { LuminousIntensity v = LuminousIntensity.FromCandela(1); - AssertEx.EqualTolerance(-1, -v.Candela, CandelaTolerance); - AssertEx.EqualTolerance(2, (LuminousIntensity.FromCandela(3)-v).Candela, CandelaTolerance); - AssertEx.EqualTolerance(2, (v + v).Candela, CandelaTolerance); - AssertEx.EqualTolerance(10, (v*10).Candela, CandelaTolerance); - AssertEx.EqualTolerance(10, (10*v).Candela, CandelaTolerance); - AssertEx.EqualTolerance(2, (LuminousIntensity.FromCandela(10)/5).Candela, CandelaTolerance); - AssertEx.EqualTolerance(2, LuminousIntensity.FromCandela(10)/LuminousIntensity.FromCandela(5), CandelaTolerance); + Assert.Equal(-1, -v.Candela); + Assert.Equal(2, (LuminousIntensity.FromCandela(3) - v).Candela); + Assert.Equal(2, (v + v).Candela); + Assert.Equal(10, (v * 10).Candela); + Assert.Equal(10, (10 * v).Candela); + Assert.Equal(2, (LuminousIntensity.FromCandela(10) / 5).Candela); + Assert.Equal(2, LuminousIntensity.FromCandela(10) / LuminousIntensity.FromCandela(5)); } [Fact] @@ -513,7 +530,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, LuminousIntensityUnit.Candela, 1, LuminousIntensityUnit.Candela, true)] // Same value and unit. [InlineData(1, LuminousIntensityUnit.Candela, 2, LuminousIntensityUnit.Candela, false)] // Different value. - [InlineData(2, LuminousIntensityUnit.Candela, 1, LuminousIntensityUnit.Candela, false)] // Different value and unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, LuminousIntensityUnit unitA, double valueB, LuminousIntensityUnit unitB, bool expectEqual) { var a = new LuminousIntensity(valueA, unitA); @@ -573,8 +589,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = LuminousIntensity.FromCandela(firstValue); var otherQuantity = LuminousIntensity.FromCandela(secondValue); LuminousIntensity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, LuminousIntensity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -593,7 +609,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -606,6 +622,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(LuminousIntensity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(LuminousIntensity.Info.Units, LuminousIntensity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, LuminousIntensity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -668,7 +696,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = LuminousIntensity.FromCandela(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(LuminousIntensity), quantity.As(LuminousIntensity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs index 52a4237995..0805813287 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFieldTestsBase.g.cs @@ -145,6 +145,20 @@ public void MagneticField_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void MagneticFieldInfo_CreateWithCustomUnitInfos() + { + MagneticFieldUnit[] expectedUnits = [MagneticFieldUnit.Tesla]; + + MagneticField.MagneticFieldInfo quantityInfo = MagneticField.MagneticFieldInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("MagneticField", quantityInfo.Name); + Assert.Equal(MagneticField.Zero, quantityInfo.Zero); + Assert.Equal(MagneticField.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void TeslaToMagneticFieldUnits() { @@ -311,7 +325,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 mT", MagneticFieldUnit.Millitesla, 4.2)] [InlineData("en-US", "4.2 nT", MagneticFieldUnit.Nanotesla, 4.2)] [InlineData("en-US", "4.2 T", MagneticFieldUnit.Tesla, 4.2)] - public void Parse(string culture, string quantityString, MagneticFieldUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, MagneticFieldUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = MagneticField.Parse(quantityString); @@ -326,7 +340,7 @@ public void Parse(string culture, string quantityString, MagneticFieldUnit expec [InlineData("en-US", "4.2 mT", MagneticFieldUnit.Millitesla, 4.2)] [InlineData("en-US", "4.2 nT", MagneticFieldUnit.Nanotesla, 4.2)] [InlineData("en-US", "4.2 T", MagneticFieldUnit.Tesla, 4.2)] - public void TryParse(string culture, string quantityString, MagneticFieldUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, MagneticFieldUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(MagneticField.TryParse(quantityString, out MagneticField parsed)); @@ -504,6 +518,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MagneticFieldUni var quantity = MagneticField.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -527,37 +542,39 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(MagneticFieldUnit u IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - MagneticField tesla = MagneticField.FromTeslas(1); - AssertEx.EqualTolerance(1, MagneticField.FromGausses(tesla.Gausses).Teslas, GaussesTolerance); - AssertEx.EqualTolerance(1, MagneticField.FromMicroteslas(tesla.Microteslas).Teslas, MicroteslasTolerance); - AssertEx.EqualTolerance(1, MagneticField.FromMilligausses(tesla.Milligausses).Teslas, MilligaussesTolerance); - AssertEx.EqualTolerance(1, MagneticField.FromMilliteslas(tesla.Milliteslas).Teslas, MilliteslasTolerance); - AssertEx.EqualTolerance(1, MagneticField.FromNanoteslas(tesla.Nanoteslas).Teslas, NanoteslasTolerance); - AssertEx.EqualTolerance(1, MagneticField.FromTeslas(tesla.Teslas).Teslas, TeslasTolerance); + MagneticField tesla = MagneticField.FromTeslas(3); + Assert.Equal(3, MagneticField.FromGausses(tesla.Gausses).Teslas); + Assert.Equal(3, MagneticField.FromMicroteslas(tesla.Microteslas).Teslas); + Assert.Equal(3, MagneticField.FromMilligausses(tesla.Milligausses).Teslas); + Assert.Equal(3, MagneticField.FromMilliteslas(tesla.Milliteslas).Teslas); + Assert.Equal(3, MagneticField.FromNanoteslas(tesla.Nanoteslas).Teslas); + Assert.Equal(3, MagneticField.FromTeslas(tesla.Teslas).Teslas); } [Fact] public void ArithmeticOperators() { MagneticField v = MagneticField.FromTeslas(1); - AssertEx.EqualTolerance(-1, -v.Teslas, TeslasTolerance); - AssertEx.EqualTolerance(2, (MagneticField.FromTeslas(3)-v).Teslas, TeslasTolerance); - AssertEx.EqualTolerance(2, (v + v).Teslas, TeslasTolerance); - AssertEx.EqualTolerance(10, (v*10).Teslas, TeslasTolerance); - AssertEx.EqualTolerance(10, (10*v).Teslas, TeslasTolerance); - AssertEx.EqualTolerance(2, (MagneticField.FromTeslas(10)/5).Teslas, TeslasTolerance); - AssertEx.EqualTolerance(2, MagneticField.FromTeslas(10)/MagneticField.FromTeslas(5), TeslasTolerance); + Assert.Equal(-1, -v.Teslas); + Assert.Equal(2, (MagneticField.FromTeslas(3) - v).Teslas); + Assert.Equal(2, (v + v).Teslas); + Assert.Equal(10, (v * 10).Teslas); + Assert.Equal(10, (10 * v).Teslas); + Assert.Equal(2, (MagneticField.FromTeslas(10) / 5).Teslas); + Assert.Equal(2, MagneticField.FromTeslas(10) / MagneticField.FromTeslas(5)); } [Fact] @@ -603,8 +620,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, MagneticFieldUnit.Tesla, 1, MagneticFieldUnit.Tesla, true)] // Same value and unit. [InlineData(1, MagneticFieldUnit.Tesla, 2, MagneticFieldUnit.Tesla, false)] // Different value. - [InlineData(2, MagneticFieldUnit.Tesla, 1, MagneticFieldUnit.Gauss, false)] // Different value and unit. - [InlineData(1, MagneticFieldUnit.Tesla, 1, MagneticFieldUnit.Gauss, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, MagneticFieldUnit unitA, double valueB, MagneticFieldUnit unitB, bool expectEqual) { var a = new MagneticField(valueA, unitA); @@ -664,8 +679,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = MagneticField.FromTeslas(firstValue); var otherQuantity = MagneticField.FromTeslas(secondValue); MagneticField maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, MagneticField.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -684,7 +699,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -697,6 +712,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(MagneticField.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(MagneticField.Info.Units, MagneticField.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, MagneticField.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -769,7 +796,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = MagneticField.FromTeslas(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(MagneticField), quantity.As(MagneticField.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs index aed8c93db0..3ba6927baa 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MagneticFluxTestsBase.g.cs @@ -125,6 +125,20 @@ public void MagneticFlux_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void MagneticFluxInfo_CreateWithCustomUnitInfos() + { + MagneticFluxUnit[] expectedUnits = [MagneticFluxUnit.Weber]; + + MagneticFlux.MagneticFluxInfo quantityInfo = MagneticFlux.MagneticFluxInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("MagneticFlux", quantityInfo.Name); + Assert.Equal(MagneticFlux.Zero, quantityInfo.Zero); + Assert.Equal(MagneticFlux.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void WeberToMagneticFluxUnits() { @@ -276,7 +290,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Theory] [InlineData("en-US", "4.2 Wb", MagneticFluxUnit.Weber, 4.2)] - public void Parse(string culture, string quantityString, MagneticFluxUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, MagneticFluxUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = MagneticFlux.Parse(quantityString); @@ -286,7 +300,7 @@ public void Parse(string culture, string quantityString, MagneticFluxUnit expect [Theory] [InlineData("en-US", "4.2 Wb", MagneticFluxUnit.Weber, 4.2)] - public void TryParse(string culture, string quantityString, MagneticFluxUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, MagneticFluxUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(MagneticFlux.TryParse(quantityString, out MagneticFlux parsed)); @@ -419,6 +433,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MagneticFluxUnit var quantity = MagneticFlux.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -442,32 +457,34 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(MagneticFluxUnit un IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - MagneticFlux weber = MagneticFlux.FromWebers(1); - AssertEx.EqualTolerance(1, MagneticFlux.FromWebers(weber.Webers).Webers, WebersTolerance); + MagneticFlux weber = MagneticFlux.FromWebers(3); + Assert.Equal(3, MagneticFlux.FromWebers(weber.Webers).Webers); } [Fact] public void ArithmeticOperators() { MagneticFlux v = MagneticFlux.FromWebers(1); - AssertEx.EqualTolerance(-1, -v.Webers, WebersTolerance); - AssertEx.EqualTolerance(2, (MagneticFlux.FromWebers(3)-v).Webers, WebersTolerance); - AssertEx.EqualTolerance(2, (v + v).Webers, WebersTolerance); - AssertEx.EqualTolerance(10, (v*10).Webers, WebersTolerance); - AssertEx.EqualTolerance(10, (10*v).Webers, WebersTolerance); - AssertEx.EqualTolerance(2, (MagneticFlux.FromWebers(10)/5).Webers, WebersTolerance); - AssertEx.EqualTolerance(2, MagneticFlux.FromWebers(10)/MagneticFlux.FromWebers(5), WebersTolerance); + Assert.Equal(-1, -v.Webers); + Assert.Equal(2, (MagneticFlux.FromWebers(3) - v).Webers); + Assert.Equal(2, (v + v).Webers); + Assert.Equal(10, (v * 10).Webers); + Assert.Equal(10, (10 * v).Webers); + Assert.Equal(2, (MagneticFlux.FromWebers(10) / 5).Webers); + Assert.Equal(2, MagneticFlux.FromWebers(10) / MagneticFlux.FromWebers(5)); } [Fact] @@ -513,7 +530,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, MagneticFluxUnit.Weber, 1, MagneticFluxUnit.Weber, true)] // Same value and unit. [InlineData(1, MagneticFluxUnit.Weber, 2, MagneticFluxUnit.Weber, false)] // Different value. - [InlineData(2, MagneticFluxUnit.Weber, 1, MagneticFluxUnit.Weber, false)] // Different value and unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, MagneticFluxUnit unitA, double valueB, MagneticFluxUnit unitB, bool expectEqual) { var a = new MagneticFlux(valueA, unitA); @@ -573,8 +589,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = MagneticFlux.FromWebers(firstValue); var otherQuantity = MagneticFlux.FromWebers(secondValue); MagneticFlux maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, MagneticFlux.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -593,7 +609,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -606,6 +622,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(MagneticFlux.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(MagneticFlux.Info.Units, MagneticFlux.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, MagneticFlux.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -668,7 +696,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = MagneticFlux.FromWebers(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(MagneticFlux), quantity.As(MagneticFlux.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs index dc90c74dd2..2b00bb6cf6 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MagnetizationTestsBase.g.cs @@ -125,6 +125,20 @@ public void Magnetization_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void MagnetizationInfo_CreateWithCustomUnitInfos() + { + MagnetizationUnit[] expectedUnits = [MagnetizationUnit.AmperePerMeter]; + + Magnetization.MagnetizationInfo quantityInfo = Magnetization.MagnetizationInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Magnetization", quantityInfo.Name); + Assert.Equal(Magnetization.Zero, quantityInfo.Zero); + Assert.Equal(Magnetization.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void AmperePerMeterToMagnetizationUnits() { @@ -276,7 +290,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Theory] [InlineData("en-US", "4.2 A/m", MagnetizationUnit.AmperePerMeter, 4.2)] - public void Parse(string culture, string quantityString, MagnetizationUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, MagnetizationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Magnetization.Parse(quantityString); @@ -286,7 +300,7 @@ public void Parse(string culture, string quantityString, MagnetizationUnit expec [Theory] [InlineData("en-US", "4.2 A/m", MagnetizationUnit.AmperePerMeter, 4.2)] - public void TryParse(string culture, string quantityString, MagnetizationUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, MagnetizationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Magnetization.TryParse(quantityString, out Magnetization parsed)); @@ -419,6 +433,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MagnetizationUni var quantity = Magnetization.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -442,32 +457,34 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(MagnetizationUnit u IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Magnetization amperepermeter = Magnetization.FromAmperesPerMeter(1); - AssertEx.EqualTolerance(1, Magnetization.FromAmperesPerMeter(amperepermeter.AmperesPerMeter).AmperesPerMeter, AmperesPerMeterTolerance); + Magnetization amperepermeter = Magnetization.FromAmperesPerMeter(3); + Assert.Equal(3, Magnetization.FromAmperesPerMeter(amperepermeter.AmperesPerMeter).AmperesPerMeter); } [Fact] public void ArithmeticOperators() { Magnetization v = Magnetization.FromAmperesPerMeter(1); - AssertEx.EqualTolerance(-1, -v.AmperesPerMeter, AmperesPerMeterTolerance); - AssertEx.EqualTolerance(2, (Magnetization.FromAmperesPerMeter(3)-v).AmperesPerMeter, AmperesPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).AmperesPerMeter, AmperesPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).AmperesPerMeter, AmperesPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).AmperesPerMeter, AmperesPerMeterTolerance); - AssertEx.EqualTolerance(2, (Magnetization.FromAmperesPerMeter(10)/5).AmperesPerMeter, AmperesPerMeterTolerance); - AssertEx.EqualTolerance(2, Magnetization.FromAmperesPerMeter(10)/Magnetization.FromAmperesPerMeter(5), AmperesPerMeterTolerance); + Assert.Equal(-1, -v.AmperesPerMeter); + Assert.Equal(2, (Magnetization.FromAmperesPerMeter(3) - v).AmperesPerMeter); + Assert.Equal(2, (v + v).AmperesPerMeter); + Assert.Equal(10, (v * 10).AmperesPerMeter); + Assert.Equal(10, (10 * v).AmperesPerMeter); + Assert.Equal(2, (Magnetization.FromAmperesPerMeter(10) / 5).AmperesPerMeter); + Assert.Equal(2, Magnetization.FromAmperesPerMeter(10) / Magnetization.FromAmperesPerMeter(5)); } [Fact] @@ -513,7 +530,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, MagnetizationUnit.AmperePerMeter, 1, MagnetizationUnit.AmperePerMeter, true)] // Same value and unit. [InlineData(1, MagnetizationUnit.AmperePerMeter, 2, MagnetizationUnit.AmperePerMeter, false)] // Different value. - [InlineData(2, MagnetizationUnit.AmperePerMeter, 1, MagnetizationUnit.AmperePerMeter, false)] // Different value and unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, MagnetizationUnit unitA, double valueB, MagnetizationUnit unitB, bool expectEqual) { var a = new Magnetization(valueA, unitA); @@ -573,8 +589,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Magnetization.FromAmperesPerMeter(firstValue); var otherQuantity = Magnetization.FromAmperesPerMeter(secondValue); Magnetization maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Magnetization.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -593,7 +609,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -606,6 +622,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Magnetization.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Magnetization.Info.Units, Magnetization.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Magnetization.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -668,7 +696,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Magnetization.FromAmperesPerMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Magnetization), quantity.As(Magnetization.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs index 923356eb93..ea89121125 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassConcentrationTestsBase.g.cs @@ -317,6 +317,20 @@ public void MassConcentration_QuantityInfo_ReturnsQuantityInfoDescribingQuantity Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void MassConcentrationInfo_CreateWithCustomUnitInfos() + { + MassConcentrationUnit[] expectedUnits = [MassConcentrationUnit.KilogramPerCubicMeter]; + + MassConcentration.MassConcentrationInfo quantityInfo = MassConcentration.MassConcentrationInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("MassConcentration", quantityInfo.Name); + Assert.Equal(MassConcentration.Zero, quantityInfo.Zero); + Assert.Equal(MassConcentration.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void KilogramPerCubicMeterToMassConcentrationUnits() { @@ -616,7 +630,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 кг/м³", MassConcentrationUnit.KilogramPerCubicMeter, 4.2)] [InlineData("ru-RU", "4,2 мкг/м³", MassConcentrationUnit.MicrogramPerCubicMeter, 4.2)] [InlineData("ru-RU", "4,2 мг/м³", MassConcentrationUnit.MilligramPerCubicMeter, 4.2)] - public void Parse(string culture, string quantityString, MassConcentrationUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, MassConcentrationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = MassConcentration.Parse(quantityString); @@ -678,7 +692,7 @@ public void Parse(string culture, string quantityString, MassConcentrationUnit e [InlineData("ru-RU", "4,2 кг/м³", MassConcentrationUnit.KilogramPerCubicMeter, 4.2)] [InlineData("ru-RU", "4,2 мкг/м³", MassConcentrationUnit.MicrogramPerCubicMeter, 4.2)] [InlineData("ru-RU", "4,2 мг/м³", MassConcentrationUnit.MilligramPerCubicMeter, 4.2)] - public void TryParse(string culture, string quantityString, MassConcentrationUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, MassConcentrationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(MassConcentration.TryParse(quantityString, out MassConcentration parsed)); @@ -1263,6 +1277,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassConcentratio var quantity = MassConcentration.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -1286,80 +1301,82 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(MassConcentrationUn IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - MassConcentration kilogrampercubicmeter = MassConcentration.FromKilogramsPerCubicMeter(1); - AssertEx.EqualTolerance(1, MassConcentration.FromCentigramsPerDeciliter(kilogrampercubicmeter.CentigramsPerDeciliter).KilogramsPerCubicMeter, CentigramsPerDeciliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromCentigramsPerLiter(kilogrampercubicmeter.CentigramsPerLiter).KilogramsPerCubicMeter, CentigramsPerLiterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromCentigramsPerMicroliter(kilogrampercubicmeter.CentigramsPerMicroliter).KilogramsPerCubicMeter, CentigramsPerMicroliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromCentigramsPerMilliliter(kilogrampercubicmeter.CentigramsPerMilliliter).KilogramsPerCubicMeter, CentigramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromDecigramsPerDeciliter(kilogrampercubicmeter.DecigramsPerDeciliter).KilogramsPerCubicMeter, DecigramsPerDeciliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromDecigramsPerLiter(kilogrampercubicmeter.DecigramsPerLiter).KilogramsPerCubicMeter, DecigramsPerLiterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromDecigramsPerMicroliter(kilogrampercubicmeter.DecigramsPerMicroliter).KilogramsPerCubicMeter, DecigramsPerMicroliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromDecigramsPerMilliliter(kilogrampercubicmeter.DecigramsPerMilliliter).KilogramsPerCubicMeter, DecigramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromGramsPerCubicCentimeter(kilogrampercubicmeter.GramsPerCubicCentimeter).KilogramsPerCubicMeter, GramsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromGramsPerCubicMeter(kilogrampercubicmeter.GramsPerCubicMeter).KilogramsPerCubicMeter, GramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromGramsPerCubicMillimeter(kilogrampercubicmeter.GramsPerCubicMillimeter).KilogramsPerCubicMeter, GramsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromGramsPerDeciliter(kilogrampercubicmeter.GramsPerDeciliter).KilogramsPerCubicMeter, GramsPerDeciliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromGramsPerLiter(kilogrampercubicmeter.GramsPerLiter).KilogramsPerCubicMeter, GramsPerLiterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromGramsPerMicroliter(kilogrampercubicmeter.GramsPerMicroliter).KilogramsPerCubicMeter, GramsPerMicroliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromGramsPerMilliliter(kilogrampercubicmeter.GramsPerMilliliter).KilogramsPerCubicMeter, GramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromKilogramsPerCubicCentimeter(kilogrampercubicmeter.KilogramsPerCubicCentimeter).KilogramsPerCubicMeter, KilogramsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromKilogramsPerCubicMeter(kilogrampercubicmeter.KilogramsPerCubicMeter).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromKilogramsPerCubicMillimeter(kilogrampercubicmeter.KilogramsPerCubicMillimeter).KilogramsPerCubicMeter, KilogramsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromKilogramsPerLiter(kilogrampercubicmeter.KilogramsPerLiter).KilogramsPerCubicMeter, KilogramsPerLiterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromKilopoundsPerCubicFoot(kilogrampercubicmeter.KilopoundsPerCubicFoot).KilogramsPerCubicMeter, KilopoundsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromKilopoundsPerCubicInch(kilogrampercubicmeter.KilopoundsPerCubicInch).KilogramsPerCubicMeter, KilopoundsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromMicrogramsPerCubicMeter(kilogrampercubicmeter.MicrogramsPerCubicMeter).KilogramsPerCubicMeter, MicrogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromMicrogramsPerDeciliter(kilogrampercubicmeter.MicrogramsPerDeciliter).KilogramsPerCubicMeter, MicrogramsPerDeciliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromMicrogramsPerLiter(kilogrampercubicmeter.MicrogramsPerLiter).KilogramsPerCubicMeter, MicrogramsPerLiterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromMicrogramsPerMicroliter(kilogrampercubicmeter.MicrogramsPerMicroliter).KilogramsPerCubicMeter, MicrogramsPerMicroliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromMicrogramsPerMilliliter(kilogrampercubicmeter.MicrogramsPerMilliliter).KilogramsPerCubicMeter, MicrogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromMilligramsPerCubicMeter(kilogrampercubicmeter.MilligramsPerCubicMeter).KilogramsPerCubicMeter, MilligramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromMilligramsPerDeciliter(kilogrampercubicmeter.MilligramsPerDeciliter).KilogramsPerCubicMeter, MilligramsPerDeciliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromMilligramsPerLiter(kilogrampercubicmeter.MilligramsPerLiter).KilogramsPerCubicMeter, MilligramsPerLiterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromMilligramsPerMicroliter(kilogrampercubicmeter.MilligramsPerMicroliter).KilogramsPerCubicMeter, MilligramsPerMicroliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromMilligramsPerMilliliter(kilogrampercubicmeter.MilligramsPerMilliliter).KilogramsPerCubicMeter, MilligramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromNanogramsPerDeciliter(kilogrampercubicmeter.NanogramsPerDeciliter).KilogramsPerCubicMeter, NanogramsPerDeciliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromNanogramsPerLiter(kilogrampercubicmeter.NanogramsPerLiter).KilogramsPerCubicMeter, NanogramsPerLiterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromNanogramsPerMicroliter(kilogrampercubicmeter.NanogramsPerMicroliter).KilogramsPerCubicMeter, NanogramsPerMicroliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromNanogramsPerMilliliter(kilogrampercubicmeter.NanogramsPerMilliliter).KilogramsPerCubicMeter, NanogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromOuncesPerImperialGallon(kilogrampercubicmeter.OuncesPerImperialGallon).KilogramsPerCubicMeter, OuncesPerImperialGallonTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromOuncesPerUSGallon(kilogrampercubicmeter.OuncesPerUSGallon).KilogramsPerCubicMeter, OuncesPerUSGallonTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromPicogramsPerDeciliter(kilogrampercubicmeter.PicogramsPerDeciliter).KilogramsPerCubicMeter, PicogramsPerDeciliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromPicogramsPerLiter(kilogrampercubicmeter.PicogramsPerLiter).KilogramsPerCubicMeter, PicogramsPerLiterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromPicogramsPerMicroliter(kilogrampercubicmeter.PicogramsPerMicroliter).KilogramsPerCubicMeter, PicogramsPerMicroliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromPicogramsPerMilliliter(kilogrampercubicmeter.PicogramsPerMilliliter).KilogramsPerCubicMeter, PicogramsPerMilliliterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromPoundsPerCubicFoot(kilogrampercubicmeter.PoundsPerCubicFoot).KilogramsPerCubicMeter, PoundsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromPoundsPerCubicInch(kilogrampercubicmeter.PoundsPerCubicInch).KilogramsPerCubicMeter, PoundsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromPoundsPerImperialGallon(kilogrampercubicmeter.PoundsPerImperialGallon).KilogramsPerCubicMeter, PoundsPerImperialGallonTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromPoundsPerUSGallon(kilogrampercubicmeter.PoundsPerUSGallon).KilogramsPerCubicMeter, PoundsPerUSGallonTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromSlugsPerCubicFoot(kilogrampercubicmeter.SlugsPerCubicFoot).KilogramsPerCubicMeter, SlugsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromTonnesPerCubicCentimeter(kilogrampercubicmeter.TonnesPerCubicCentimeter).KilogramsPerCubicMeter, TonnesPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromTonnesPerCubicMeter(kilogrampercubicmeter.TonnesPerCubicMeter).KilogramsPerCubicMeter, TonnesPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, MassConcentration.FromTonnesPerCubicMillimeter(kilogrampercubicmeter.TonnesPerCubicMillimeter).KilogramsPerCubicMeter, TonnesPerCubicMillimeterTolerance); + MassConcentration kilogrampercubicmeter = MassConcentration.FromKilogramsPerCubicMeter(3); + Assert.Equal(3, MassConcentration.FromCentigramsPerDeciliter(kilogrampercubicmeter.CentigramsPerDeciliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromCentigramsPerLiter(kilogrampercubicmeter.CentigramsPerLiter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromCentigramsPerMicroliter(kilogrampercubicmeter.CentigramsPerMicroliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromCentigramsPerMilliliter(kilogrampercubicmeter.CentigramsPerMilliliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromDecigramsPerDeciliter(kilogrampercubicmeter.DecigramsPerDeciliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromDecigramsPerLiter(kilogrampercubicmeter.DecigramsPerLiter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromDecigramsPerMicroliter(kilogrampercubicmeter.DecigramsPerMicroliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromDecigramsPerMilliliter(kilogrampercubicmeter.DecigramsPerMilliliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromGramsPerCubicCentimeter(kilogrampercubicmeter.GramsPerCubicCentimeter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromGramsPerCubicMeter(kilogrampercubicmeter.GramsPerCubicMeter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromGramsPerCubicMillimeter(kilogrampercubicmeter.GramsPerCubicMillimeter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromGramsPerDeciliter(kilogrampercubicmeter.GramsPerDeciliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromGramsPerLiter(kilogrampercubicmeter.GramsPerLiter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromGramsPerMicroliter(kilogrampercubicmeter.GramsPerMicroliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromGramsPerMilliliter(kilogrampercubicmeter.GramsPerMilliliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromKilogramsPerCubicCentimeter(kilogrampercubicmeter.KilogramsPerCubicCentimeter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromKilogramsPerCubicMeter(kilogrampercubicmeter.KilogramsPerCubicMeter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromKilogramsPerCubicMillimeter(kilogrampercubicmeter.KilogramsPerCubicMillimeter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromKilogramsPerLiter(kilogrampercubicmeter.KilogramsPerLiter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromKilopoundsPerCubicFoot(kilogrampercubicmeter.KilopoundsPerCubicFoot).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromKilopoundsPerCubicInch(kilogrampercubicmeter.KilopoundsPerCubicInch).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromMicrogramsPerCubicMeter(kilogrampercubicmeter.MicrogramsPerCubicMeter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromMicrogramsPerDeciliter(kilogrampercubicmeter.MicrogramsPerDeciliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromMicrogramsPerLiter(kilogrampercubicmeter.MicrogramsPerLiter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromMicrogramsPerMicroliter(kilogrampercubicmeter.MicrogramsPerMicroliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromMicrogramsPerMilliliter(kilogrampercubicmeter.MicrogramsPerMilliliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromMilligramsPerCubicMeter(kilogrampercubicmeter.MilligramsPerCubicMeter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromMilligramsPerDeciliter(kilogrampercubicmeter.MilligramsPerDeciliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromMilligramsPerLiter(kilogrampercubicmeter.MilligramsPerLiter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromMilligramsPerMicroliter(kilogrampercubicmeter.MilligramsPerMicroliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromMilligramsPerMilliliter(kilogrampercubicmeter.MilligramsPerMilliliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromNanogramsPerDeciliter(kilogrampercubicmeter.NanogramsPerDeciliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromNanogramsPerLiter(kilogrampercubicmeter.NanogramsPerLiter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromNanogramsPerMicroliter(kilogrampercubicmeter.NanogramsPerMicroliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromNanogramsPerMilliliter(kilogrampercubicmeter.NanogramsPerMilliliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromOuncesPerImperialGallon(kilogrampercubicmeter.OuncesPerImperialGallon).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromOuncesPerUSGallon(kilogrampercubicmeter.OuncesPerUSGallon).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromPicogramsPerDeciliter(kilogrampercubicmeter.PicogramsPerDeciliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromPicogramsPerLiter(kilogrampercubicmeter.PicogramsPerLiter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromPicogramsPerMicroliter(kilogrampercubicmeter.PicogramsPerMicroliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromPicogramsPerMilliliter(kilogrampercubicmeter.PicogramsPerMilliliter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromPoundsPerCubicFoot(kilogrampercubicmeter.PoundsPerCubicFoot).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromPoundsPerCubicInch(kilogrampercubicmeter.PoundsPerCubicInch).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromPoundsPerImperialGallon(kilogrampercubicmeter.PoundsPerImperialGallon).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromPoundsPerUSGallon(kilogrampercubicmeter.PoundsPerUSGallon).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromSlugsPerCubicFoot(kilogrampercubicmeter.SlugsPerCubicFoot).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromTonnesPerCubicCentimeter(kilogrampercubicmeter.TonnesPerCubicCentimeter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromTonnesPerCubicMeter(kilogrampercubicmeter.TonnesPerCubicMeter).KilogramsPerCubicMeter); + Assert.Equal(3, MassConcentration.FromTonnesPerCubicMillimeter(kilogrampercubicmeter.TonnesPerCubicMillimeter).KilogramsPerCubicMeter); } [Fact] public void ArithmeticOperators() { MassConcentration v = MassConcentration.FromKilogramsPerCubicMeter(1); - AssertEx.EqualTolerance(-1, -v.KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (MassConcentration.FromKilogramsPerCubicMeter(3)-v).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (MassConcentration.FromKilogramsPerCubicMeter(10)/5).KilogramsPerCubicMeter, KilogramsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, MassConcentration.FromKilogramsPerCubicMeter(10)/MassConcentration.FromKilogramsPerCubicMeter(5), KilogramsPerCubicMeterTolerance); + Assert.Equal(-1, -v.KilogramsPerCubicMeter); + Assert.Equal(2, (MassConcentration.FromKilogramsPerCubicMeter(3) - v).KilogramsPerCubicMeter); + Assert.Equal(2, (v + v).KilogramsPerCubicMeter); + Assert.Equal(10, (v * 10).KilogramsPerCubicMeter); + Assert.Equal(10, (10 * v).KilogramsPerCubicMeter); + Assert.Equal(2, (MassConcentration.FromKilogramsPerCubicMeter(10) / 5).KilogramsPerCubicMeter); + Assert.Equal(2, MassConcentration.FromKilogramsPerCubicMeter(10) / MassConcentration.FromKilogramsPerCubicMeter(5)); } [Fact] @@ -1405,8 +1422,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, MassConcentrationUnit.KilogramPerCubicMeter, 1, MassConcentrationUnit.KilogramPerCubicMeter, true)] // Same value and unit. [InlineData(1, MassConcentrationUnit.KilogramPerCubicMeter, 2, MassConcentrationUnit.KilogramPerCubicMeter, false)] // Different value. - [InlineData(2, MassConcentrationUnit.KilogramPerCubicMeter, 1, MassConcentrationUnit.CentigramPerDeciliter, false)] // Different value and unit. - [InlineData(1, MassConcentrationUnit.KilogramPerCubicMeter, 1, MassConcentrationUnit.CentigramPerDeciliter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, MassConcentrationUnit unitA, double valueB, MassConcentrationUnit unitB, bool expectEqual) { var a = new MassConcentration(valueA, unitA); @@ -1466,8 +1481,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = MassConcentration.FromKilogramsPerCubicMeter(firstValue); var otherQuantity = MassConcentration.FromKilogramsPerCubicMeter(secondValue); MassConcentration maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, MassConcentration.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1486,7 +1501,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1499,6 +1514,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(MassConcentration.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(MassConcentration.Info.Units, MassConcentration.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, MassConcentration.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1657,7 +1684,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = MassConcentration.FromKilogramsPerCubicMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(MassConcentration), quantity.As(MassConcentration.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs index 7d0326f608..6c1375e13a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFlowTestsBase.g.cs @@ -253,6 +253,20 @@ public void MassFlow_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void MassFlowInfo_CreateWithCustomUnitInfos() + { + MassFlowUnit[] expectedUnits = [MassFlowUnit.GramPerSecond]; + + MassFlow.MassFlowInfo quantityInfo = MassFlow.MassFlowInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("MassFlow", quantityInfo.Name); + Assert.Equal(MassFlow.Zero, quantityInfo.Zero); + Assert.Equal(MassFlow.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void GramPerSecondToMassFlowUnits() { @@ -511,7 +525,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 t/h", MassFlowUnit.TonnePerHour, 4.2)] [InlineData("ru-RU", "4,2 кг/ч", MassFlowUnit.KilogramPerHour, 4.2)] [InlineData("ru-RU", "4,2 кг/мин", MassFlowUnit.KilogramPerMinute, 4.2)] - public void Parse(string culture, string quantityString, MassFlowUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, MassFlowUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = MassFlow.Parse(quantityString); @@ -564,7 +578,7 @@ public void Parse(string culture, string quantityString, MassFlowUnit expectedUn [InlineData("en-US", "4.2 t/h", MassFlowUnit.TonnePerHour, 4.2)] [InlineData("ru-RU", "4,2 кг/ч", MassFlowUnit.KilogramPerHour, 4.2)] [InlineData("ru-RU", "4,2 кг/мин", MassFlowUnit.KilogramPerMinute, 4.2)] - public void TryParse(string culture, string quantityString, MassFlowUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, MassFlowUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(MassFlow.TryParse(quantityString, out MassFlow parsed)); @@ -1067,6 +1081,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassFlowUnit uni var quantity = MassFlow.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -1090,64 +1105,66 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(MassFlowUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - MassFlow grampersecond = MassFlow.FromGramsPerSecond(1); - AssertEx.EqualTolerance(1, MassFlow.FromCentigramsPerDay(grampersecond.CentigramsPerDay).GramsPerSecond, CentigramsPerDayTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromCentigramsPerSecond(grampersecond.CentigramsPerSecond).GramsPerSecond, CentigramsPerSecondTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromDecagramsPerDay(grampersecond.DecagramsPerDay).GramsPerSecond, DecagramsPerDayTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromDecagramsPerSecond(grampersecond.DecagramsPerSecond).GramsPerSecond, DecagramsPerSecondTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromDecigramsPerDay(grampersecond.DecigramsPerDay).GramsPerSecond, DecigramsPerDayTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromDecigramsPerSecond(grampersecond.DecigramsPerSecond).GramsPerSecond, DecigramsPerSecondTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromGramsPerDay(grampersecond.GramsPerDay).GramsPerSecond, GramsPerDayTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromGramsPerHour(grampersecond.GramsPerHour).GramsPerSecond, GramsPerHourTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromGramsPerSecond(grampersecond.GramsPerSecond).GramsPerSecond, GramsPerSecondTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromHectogramsPerDay(grampersecond.HectogramsPerDay).GramsPerSecond, HectogramsPerDayTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromHectogramsPerSecond(grampersecond.HectogramsPerSecond).GramsPerSecond, HectogramsPerSecondTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromKilogramsPerDay(grampersecond.KilogramsPerDay).GramsPerSecond, KilogramsPerDayTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromKilogramsPerHour(grampersecond.KilogramsPerHour).GramsPerSecond, KilogramsPerHourTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromKilogramsPerMinute(grampersecond.KilogramsPerMinute).GramsPerSecond, KilogramsPerMinuteTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromKilogramsPerSecond(grampersecond.KilogramsPerSecond).GramsPerSecond, KilogramsPerSecondTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromMegagramsPerDay(grampersecond.MegagramsPerDay).GramsPerSecond, MegagramsPerDayTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromMegapoundsPerDay(grampersecond.MegapoundsPerDay).GramsPerSecond, MegapoundsPerDayTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromMegapoundsPerHour(grampersecond.MegapoundsPerHour).GramsPerSecond, MegapoundsPerHourTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromMegapoundsPerMinute(grampersecond.MegapoundsPerMinute).GramsPerSecond, MegapoundsPerMinuteTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromMegapoundsPerSecond(grampersecond.MegapoundsPerSecond).GramsPerSecond, MegapoundsPerSecondTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromMicrogramsPerDay(grampersecond.MicrogramsPerDay).GramsPerSecond, MicrogramsPerDayTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromMicrogramsPerSecond(grampersecond.MicrogramsPerSecond).GramsPerSecond, MicrogramsPerSecondTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromMilligramsPerDay(grampersecond.MilligramsPerDay).GramsPerSecond, MilligramsPerDayTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromMilligramsPerSecond(grampersecond.MilligramsPerSecond).GramsPerSecond, MilligramsPerSecondTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromNanogramsPerDay(grampersecond.NanogramsPerDay).GramsPerSecond, NanogramsPerDayTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromNanogramsPerSecond(grampersecond.NanogramsPerSecond).GramsPerSecond, NanogramsPerSecondTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromPoundsPerDay(grampersecond.PoundsPerDay).GramsPerSecond, PoundsPerDayTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromPoundsPerHour(grampersecond.PoundsPerHour).GramsPerSecond, PoundsPerHourTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromPoundsPerMinute(grampersecond.PoundsPerMinute).GramsPerSecond, PoundsPerMinuteTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromPoundsPerSecond(grampersecond.PoundsPerSecond).GramsPerSecond, PoundsPerSecondTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromShortTonsPerHour(grampersecond.ShortTonsPerHour).GramsPerSecond, ShortTonsPerHourTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromTonnesPerDay(grampersecond.TonnesPerDay).GramsPerSecond, TonnesPerDayTolerance); - AssertEx.EqualTolerance(1, MassFlow.FromTonnesPerHour(grampersecond.TonnesPerHour).GramsPerSecond, TonnesPerHourTolerance); + MassFlow grampersecond = MassFlow.FromGramsPerSecond(3); + Assert.Equal(3, MassFlow.FromCentigramsPerDay(grampersecond.CentigramsPerDay).GramsPerSecond); + Assert.Equal(3, MassFlow.FromCentigramsPerSecond(grampersecond.CentigramsPerSecond).GramsPerSecond); + Assert.Equal(3, MassFlow.FromDecagramsPerDay(grampersecond.DecagramsPerDay).GramsPerSecond); + Assert.Equal(3, MassFlow.FromDecagramsPerSecond(grampersecond.DecagramsPerSecond).GramsPerSecond); + Assert.Equal(3, MassFlow.FromDecigramsPerDay(grampersecond.DecigramsPerDay).GramsPerSecond); + Assert.Equal(3, MassFlow.FromDecigramsPerSecond(grampersecond.DecigramsPerSecond).GramsPerSecond); + Assert.Equal(3, MassFlow.FromGramsPerDay(grampersecond.GramsPerDay).GramsPerSecond); + Assert.Equal(3, MassFlow.FromGramsPerHour(grampersecond.GramsPerHour).GramsPerSecond); + Assert.Equal(3, MassFlow.FromGramsPerSecond(grampersecond.GramsPerSecond).GramsPerSecond); + Assert.Equal(3, MassFlow.FromHectogramsPerDay(grampersecond.HectogramsPerDay).GramsPerSecond); + Assert.Equal(3, MassFlow.FromHectogramsPerSecond(grampersecond.HectogramsPerSecond).GramsPerSecond); + Assert.Equal(3, MassFlow.FromKilogramsPerDay(grampersecond.KilogramsPerDay).GramsPerSecond); + Assert.Equal(3, MassFlow.FromKilogramsPerHour(grampersecond.KilogramsPerHour).GramsPerSecond); + Assert.Equal(3, MassFlow.FromKilogramsPerMinute(grampersecond.KilogramsPerMinute).GramsPerSecond); + Assert.Equal(3, MassFlow.FromKilogramsPerSecond(grampersecond.KilogramsPerSecond).GramsPerSecond); + Assert.Equal(3, MassFlow.FromMegagramsPerDay(grampersecond.MegagramsPerDay).GramsPerSecond); + Assert.Equal(3, MassFlow.FromMegapoundsPerDay(grampersecond.MegapoundsPerDay).GramsPerSecond); + Assert.Equal(3, MassFlow.FromMegapoundsPerHour(grampersecond.MegapoundsPerHour).GramsPerSecond); + Assert.Equal(3, MassFlow.FromMegapoundsPerMinute(grampersecond.MegapoundsPerMinute).GramsPerSecond); + Assert.Equal(3, MassFlow.FromMegapoundsPerSecond(grampersecond.MegapoundsPerSecond).GramsPerSecond); + Assert.Equal(3, MassFlow.FromMicrogramsPerDay(grampersecond.MicrogramsPerDay).GramsPerSecond); + Assert.Equal(3, MassFlow.FromMicrogramsPerSecond(grampersecond.MicrogramsPerSecond).GramsPerSecond); + Assert.Equal(3, MassFlow.FromMilligramsPerDay(grampersecond.MilligramsPerDay).GramsPerSecond); + Assert.Equal(3, MassFlow.FromMilligramsPerSecond(grampersecond.MilligramsPerSecond).GramsPerSecond); + Assert.Equal(3, MassFlow.FromNanogramsPerDay(grampersecond.NanogramsPerDay).GramsPerSecond); + Assert.Equal(3, MassFlow.FromNanogramsPerSecond(grampersecond.NanogramsPerSecond).GramsPerSecond); + Assert.Equal(3, MassFlow.FromPoundsPerDay(grampersecond.PoundsPerDay).GramsPerSecond); + Assert.Equal(3, MassFlow.FromPoundsPerHour(grampersecond.PoundsPerHour).GramsPerSecond); + Assert.Equal(3, MassFlow.FromPoundsPerMinute(grampersecond.PoundsPerMinute).GramsPerSecond); + Assert.Equal(3, MassFlow.FromPoundsPerSecond(grampersecond.PoundsPerSecond).GramsPerSecond); + Assert.Equal(3, MassFlow.FromShortTonsPerHour(grampersecond.ShortTonsPerHour).GramsPerSecond); + Assert.Equal(3, MassFlow.FromTonnesPerDay(grampersecond.TonnesPerDay).GramsPerSecond); + Assert.Equal(3, MassFlow.FromTonnesPerHour(grampersecond.TonnesPerHour).GramsPerSecond); } [Fact] public void ArithmeticOperators() { MassFlow v = MassFlow.FromGramsPerSecond(1); - AssertEx.EqualTolerance(-1, -v.GramsPerSecond, GramsPerSecondTolerance); - AssertEx.EqualTolerance(2, (MassFlow.FromGramsPerSecond(3)-v).GramsPerSecond, GramsPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).GramsPerSecond, GramsPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).GramsPerSecond, GramsPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).GramsPerSecond, GramsPerSecondTolerance); - AssertEx.EqualTolerance(2, (MassFlow.FromGramsPerSecond(10)/5).GramsPerSecond, GramsPerSecondTolerance); - AssertEx.EqualTolerance(2, MassFlow.FromGramsPerSecond(10)/MassFlow.FromGramsPerSecond(5), GramsPerSecondTolerance); + Assert.Equal(-1, -v.GramsPerSecond); + Assert.Equal(2, (MassFlow.FromGramsPerSecond(3) - v).GramsPerSecond); + Assert.Equal(2, (v + v).GramsPerSecond); + Assert.Equal(10, (v * 10).GramsPerSecond); + Assert.Equal(10, (10 * v).GramsPerSecond); + Assert.Equal(2, (MassFlow.FromGramsPerSecond(10) / 5).GramsPerSecond); + Assert.Equal(2, MassFlow.FromGramsPerSecond(10) / MassFlow.FromGramsPerSecond(5)); } [Fact] @@ -1193,8 +1210,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, MassFlowUnit.GramPerSecond, 1, MassFlowUnit.GramPerSecond, true)] // Same value and unit. [InlineData(1, MassFlowUnit.GramPerSecond, 2, MassFlowUnit.GramPerSecond, false)] // Different value. - [InlineData(2, MassFlowUnit.GramPerSecond, 1, MassFlowUnit.CentigramPerDay, false)] // Different value and unit. - [InlineData(1, MassFlowUnit.GramPerSecond, 1, MassFlowUnit.CentigramPerDay, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, MassFlowUnit unitA, double valueB, MassFlowUnit unitB, bool expectEqual) { var a = new MassFlow(valueA, unitA); @@ -1254,8 +1269,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = MassFlow.FromGramsPerSecond(firstValue); var otherQuantity = MassFlow.FromGramsPerSecond(secondValue); MassFlow maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, MassFlow.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1274,7 +1289,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1287,6 +1302,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(MassFlow.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(MassFlow.Info.Units, MassFlow.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, MassFlow.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1413,7 +1440,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = MassFlow.FromGramsPerSecond(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(MassFlow), quantity.As(MassFlow.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs index 65697c156e..dd00c05881 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFluxTestsBase.g.cs @@ -169,6 +169,20 @@ public void MassFlux_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void MassFluxInfo_CreateWithCustomUnitInfos() + { + MassFluxUnit[] expectedUnits = [MassFluxUnit.KilogramPerSecondPerSquareMeter]; + + MassFlux.MassFluxInfo quantityInfo = MassFlux.MassFluxInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("MassFlux", quantityInfo.Name); + Assert.Equal(MassFlux.Zero, quantityInfo.Zero); + Assert.Equal(MassFlux.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void KilogramPerSecondPerSquareMeterToMassFluxUnits() { @@ -353,7 +367,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 kg·s⁻¹·cm⁻²", MassFluxUnit.KilogramPerSecondPerSquareCentimeter, 4.2)] [InlineData("en-US", "4.2 kg·s⁻¹·m⁻²", MassFluxUnit.KilogramPerSecondPerSquareMeter, 4.2)] [InlineData("en-US", "4.2 kg·s⁻¹·mm⁻²", MassFluxUnit.KilogramPerSecondPerSquareMillimeter, 4.2)] - public void Parse(string culture, string quantityString, MassFluxUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, MassFluxUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = MassFlux.Parse(quantityString); @@ -374,7 +388,7 @@ public void Parse(string culture, string quantityString, MassFluxUnit expectedUn [InlineData("en-US", "4.2 kg·s⁻¹·cm⁻²", MassFluxUnit.KilogramPerSecondPerSquareCentimeter, 4.2)] [InlineData("en-US", "4.2 kg·s⁻¹·m⁻²", MassFluxUnit.KilogramPerSecondPerSquareMeter, 4.2)] [InlineData("en-US", "4.2 kg·s⁻¹·mm⁻²", MassFluxUnit.KilogramPerSecondPerSquareMillimeter, 4.2)] - public void TryParse(string culture, string quantityString, MassFluxUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, MassFluxUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(MassFlux.TryParse(quantityString, out MassFlux parsed)); @@ -606,6 +620,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassFluxUnit uni var quantity = MassFlux.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -629,43 +644,45 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(MassFluxUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - MassFlux kilogrampersecondpersquaremeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - AssertEx.EqualTolerance(1, MassFlux.FromGramsPerHourPerSquareCentimeter(kilogrampersecondpersquaremeter.GramsPerHourPerSquareCentimeter).KilogramsPerSecondPerSquareMeter, GramsPerHourPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, MassFlux.FromGramsPerHourPerSquareMeter(kilogrampersecondpersquaremeter.GramsPerHourPerSquareMeter).KilogramsPerSecondPerSquareMeter, GramsPerHourPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, MassFlux.FromGramsPerHourPerSquareMillimeter(kilogrampersecondpersquaremeter.GramsPerHourPerSquareMillimeter).KilogramsPerSecondPerSquareMeter, GramsPerHourPerSquareMillimeterTolerance); - AssertEx.EqualTolerance(1, MassFlux.FromGramsPerSecondPerSquareCentimeter(kilogrampersecondpersquaremeter.GramsPerSecondPerSquareCentimeter).KilogramsPerSecondPerSquareMeter, GramsPerSecondPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, MassFlux.FromGramsPerSecondPerSquareMeter(kilogrampersecondpersquaremeter.GramsPerSecondPerSquareMeter).KilogramsPerSecondPerSquareMeter, GramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, MassFlux.FromGramsPerSecondPerSquareMillimeter(kilogrampersecondpersquaremeter.GramsPerSecondPerSquareMillimeter).KilogramsPerSecondPerSquareMeter, GramsPerSecondPerSquareMillimeterTolerance); - AssertEx.EqualTolerance(1, MassFlux.FromKilogramsPerHourPerSquareCentimeter(kilogrampersecondpersquaremeter.KilogramsPerHourPerSquareCentimeter).KilogramsPerSecondPerSquareMeter, KilogramsPerHourPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, MassFlux.FromKilogramsPerHourPerSquareMeter(kilogrampersecondpersquaremeter.KilogramsPerHourPerSquareMeter).KilogramsPerSecondPerSquareMeter, KilogramsPerHourPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, MassFlux.FromKilogramsPerHourPerSquareMillimeter(kilogrampersecondpersquaremeter.KilogramsPerHourPerSquareMillimeter).KilogramsPerSecondPerSquareMeter, KilogramsPerHourPerSquareMillimeterTolerance); - AssertEx.EqualTolerance(1, MassFlux.FromKilogramsPerSecondPerSquareCentimeter(kilogrampersecondpersquaremeter.KilogramsPerSecondPerSquareCentimeter).KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, MassFlux.FromKilogramsPerSecondPerSquareMeter(kilogrampersecondpersquaremeter.KilogramsPerSecondPerSquareMeter).KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, MassFlux.FromKilogramsPerSecondPerSquareMillimeter(kilogrampersecondpersquaremeter.KilogramsPerSecondPerSquareMillimeter).KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMillimeterTolerance); + MassFlux kilogrampersecondpersquaremeter = MassFlux.FromKilogramsPerSecondPerSquareMeter(3); + Assert.Equal(3, MassFlux.FromGramsPerHourPerSquareCentimeter(kilogrampersecondpersquaremeter.GramsPerHourPerSquareCentimeter).KilogramsPerSecondPerSquareMeter); + Assert.Equal(3, MassFlux.FromGramsPerHourPerSquareMeter(kilogrampersecondpersquaremeter.GramsPerHourPerSquareMeter).KilogramsPerSecondPerSquareMeter); + Assert.Equal(3, MassFlux.FromGramsPerHourPerSquareMillimeter(kilogrampersecondpersquaremeter.GramsPerHourPerSquareMillimeter).KilogramsPerSecondPerSquareMeter); + Assert.Equal(3, MassFlux.FromGramsPerSecondPerSquareCentimeter(kilogrampersecondpersquaremeter.GramsPerSecondPerSquareCentimeter).KilogramsPerSecondPerSquareMeter); + Assert.Equal(3, MassFlux.FromGramsPerSecondPerSquareMeter(kilogrampersecondpersquaremeter.GramsPerSecondPerSquareMeter).KilogramsPerSecondPerSquareMeter); + Assert.Equal(3, MassFlux.FromGramsPerSecondPerSquareMillimeter(kilogrampersecondpersquaremeter.GramsPerSecondPerSquareMillimeter).KilogramsPerSecondPerSquareMeter); + Assert.Equal(3, MassFlux.FromKilogramsPerHourPerSquareCentimeter(kilogrampersecondpersquaremeter.KilogramsPerHourPerSquareCentimeter).KilogramsPerSecondPerSquareMeter); + Assert.Equal(3, MassFlux.FromKilogramsPerHourPerSquareMeter(kilogrampersecondpersquaremeter.KilogramsPerHourPerSquareMeter).KilogramsPerSecondPerSquareMeter); + Assert.Equal(3, MassFlux.FromKilogramsPerHourPerSquareMillimeter(kilogrampersecondpersquaremeter.KilogramsPerHourPerSquareMillimeter).KilogramsPerSecondPerSquareMeter); + Assert.Equal(3, MassFlux.FromKilogramsPerSecondPerSquareCentimeter(kilogrampersecondpersquaremeter.KilogramsPerSecondPerSquareCentimeter).KilogramsPerSecondPerSquareMeter); + Assert.Equal(3, MassFlux.FromKilogramsPerSecondPerSquareMeter(kilogrampersecondpersquaremeter.KilogramsPerSecondPerSquareMeter).KilogramsPerSecondPerSquareMeter); + Assert.Equal(3, MassFlux.FromKilogramsPerSecondPerSquareMillimeter(kilogrampersecondpersquaremeter.KilogramsPerSecondPerSquareMillimeter).KilogramsPerSecondPerSquareMeter); } [Fact] public void ArithmeticOperators() { MassFlux v = MassFlux.FromKilogramsPerSecondPerSquareMeter(1); - AssertEx.EqualTolerance(-1, -v.KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (MassFlux.FromKilogramsPerSecondPerSquareMeter(3)-v).KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (MassFlux.FromKilogramsPerSecondPerSquareMeter(10)/5).KilogramsPerSecondPerSquareMeter, KilogramsPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, MassFlux.FromKilogramsPerSecondPerSquareMeter(10)/MassFlux.FromKilogramsPerSecondPerSquareMeter(5), KilogramsPerSecondPerSquareMeterTolerance); + Assert.Equal(-1, -v.KilogramsPerSecondPerSquareMeter); + Assert.Equal(2, (MassFlux.FromKilogramsPerSecondPerSquareMeter(3) - v).KilogramsPerSecondPerSquareMeter); + Assert.Equal(2, (v + v).KilogramsPerSecondPerSquareMeter); + Assert.Equal(10, (v * 10).KilogramsPerSecondPerSquareMeter); + Assert.Equal(10, (10 * v).KilogramsPerSecondPerSquareMeter); + Assert.Equal(2, (MassFlux.FromKilogramsPerSecondPerSquareMeter(10) / 5).KilogramsPerSecondPerSquareMeter); + Assert.Equal(2, MassFlux.FromKilogramsPerSecondPerSquareMeter(10) / MassFlux.FromKilogramsPerSecondPerSquareMeter(5)); } [Fact] @@ -711,8 +728,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, MassFluxUnit.KilogramPerSecondPerSquareMeter, 1, MassFluxUnit.KilogramPerSecondPerSquareMeter, true)] // Same value and unit. [InlineData(1, MassFluxUnit.KilogramPerSecondPerSquareMeter, 2, MassFluxUnit.KilogramPerSecondPerSquareMeter, false)] // Different value. - [InlineData(2, MassFluxUnit.KilogramPerSecondPerSquareMeter, 1, MassFluxUnit.GramPerHourPerSquareCentimeter, false)] // Different value and unit. - [InlineData(1, MassFluxUnit.KilogramPerSecondPerSquareMeter, 1, MassFluxUnit.GramPerHourPerSquareCentimeter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, MassFluxUnit unitA, double valueB, MassFluxUnit unitB, bool expectEqual) { var a = new MassFlux(valueA, unitA); @@ -772,8 +787,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(firstValue); var otherQuantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(secondValue); MassFlux maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, MassFlux.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -792,7 +807,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -805,6 +820,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(MassFlux.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(MassFlux.Info.Units, MassFlux.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, MassFlux.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -889,7 +916,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = MassFlux.FromKilogramsPerSecondPerSquareMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(MassFlux), quantity.As(MassFlux.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs index 583c878787..bfa0e52938 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassFractionTestsBase.g.cs @@ -196,6 +196,20 @@ public void MassFraction_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void MassFractionInfo_CreateWithCustomUnitInfos() + { + MassFractionUnit[] expectedUnits = [MassFractionUnit.DecimalFraction]; + + MassFraction.MassFractionInfo quantityInfo = MassFraction.MassFractionInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("MassFraction", quantityInfo.Name); + Assert.Equal(MassFraction.Zero, quantityInfo.Zero); + Assert.Equal(MassFraction.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void DecimalFractionToMassFractionUnits() { @@ -378,7 +392,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() [InlineData("en-US", "4.2 ppt", MassFractionUnit.PartPerTrillion, 4.2)] [InlineData("en-US", "4.2 %", MassFractionUnit.Percent, 4.2)] [InlineData("en-US", "4.2 % (w/w)", MassFractionUnit.Percent, 4.2)] - public void Parse(string culture, string quantityString, MassFractionUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, MassFractionUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = MassFraction.Parse(quantityString); @@ -412,7 +426,7 @@ public void Parse(string culture, string quantityString, MassFractionUnit expect [InlineData("en-US", "4.2 ppt", MassFractionUnit.PartPerTrillion, 4.2)] [InlineData("en-US", "4.2 %", MassFractionUnit.Percent, 4.2)] [InlineData("en-US", "4.2 % (w/w)", MassFractionUnit.Percent, 4.2)] - public void TryParse(string culture, string quantityString, MassFractionUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, MassFractionUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(MassFraction.TryParse(quantityString, out MassFraction parsed)); @@ -760,6 +774,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassFractionUnit var quantity = MassFraction.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -783,55 +798,57 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(MassFractionUnit un IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - MassFraction decimalfraction = MassFraction.FromDecimalFractions(1); - AssertEx.EqualTolerance(1, MassFraction.FromCentigramsPerGram(decimalfraction.CentigramsPerGram).DecimalFractions, CentigramsPerGramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromCentigramsPerKilogram(decimalfraction.CentigramsPerKilogram).DecimalFractions, CentigramsPerKilogramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromDecagramsPerGram(decimalfraction.DecagramsPerGram).DecimalFractions, DecagramsPerGramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromDecagramsPerKilogram(decimalfraction.DecagramsPerKilogram).DecimalFractions, DecagramsPerKilogramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromDecigramsPerGram(decimalfraction.DecigramsPerGram).DecimalFractions, DecigramsPerGramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromDecigramsPerKilogram(decimalfraction.DecigramsPerKilogram).DecimalFractions, DecigramsPerKilogramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromDecimalFractions(decimalfraction.DecimalFractions).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromGramsPerGram(decimalfraction.GramsPerGram).DecimalFractions, GramsPerGramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromGramsPerKilogram(decimalfraction.GramsPerKilogram).DecimalFractions, GramsPerKilogramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromHectogramsPerGram(decimalfraction.HectogramsPerGram).DecimalFractions, HectogramsPerGramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromHectogramsPerKilogram(decimalfraction.HectogramsPerKilogram).DecimalFractions, HectogramsPerKilogramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromKilogramsPerGram(decimalfraction.KilogramsPerGram).DecimalFractions, KilogramsPerGramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromKilogramsPerKilogram(decimalfraction.KilogramsPerKilogram).DecimalFractions, KilogramsPerKilogramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromMicrogramsPerGram(decimalfraction.MicrogramsPerGram).DecimalFractions, MicrogramsPerGramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromMicrogramsPerKilogram(decimalfraction.MicrogramsPerKilogram).DecimalFractions, MicrogramsPerKilogramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromMilligramsPerGram(decimalfraction.MilligramsPerGram).DecimalFractions, MilligramsPerGramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromMilligramsPerKilogram(decimalfraction.MilligramsPerKilogram).DecimalFractions, MilligramsPerKilogramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromNanogramsPerGram(decimalfraction.NanogramsPerGram).DecimalFractions, NanogramsPerGramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromNanogramsPerKilogram(decimalfraction.NanogramsPerKilogram).DecimalFractions, NanogramsPerKilogramTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromPartsPerBillion(decimalfraction.PartsPerBillion).DecimalFractions, PartsPerBillionTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromPartsPerMillion(decimalfraction.PartsPerMillion).DecimalFractions, PartsPerMillionTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromPartsPerThousand(decimalfraction.PartsPerThousand).DecimalFractions, PartsPerThousandTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromPartsPerTrillion(decimalfraction.PartsPerTrillion).DecimalFractions, PartsPerTrillionTolerance); - AssertEx.EqualTolerance(1, MassFraction.FromPercent(decimalfraction.Percent).DecimalFractions, PercentTolerance); + MassFraction decimalfraction = MassFraction.FromDecimalFractions(3); + Assert.Equal(3, MassFraction.FromCentigramsPerGram(decimalfraction.CentigramsPerGram).DecimalFractions); + Assert.Equal(3, MassFraction.FromCentigramsPerKilogram(decimalfraction.CentigramsPerKilogram).DecimalFractions); + Assert.Equal(3, MassFraction.FromDecagramsPerGram(decimalfraction.DecagramsPerGram).DecimalFractions); + Assert.Equal(3, MassFraction.FromDecagramsPerKilogram(decimalfraction.DecagramsPerKilogram).DecimalFractions); + Assert.Equal(3, MassFraction.FromDecigramsPerGram(decimalfraction.DecigramsPerGram).DecimalFractions); + Assert.Equal(3, MassFraction.FromDecigramsPerKilogram(decimalfraction.DecigramsPerKilogram).DecimalFractions); + Assert.Equal(3, MassFraction.FromDecimalFractions(decimalfraction.DecimalFractions).DecimalFractions); + Assert.Equal(3, MassFraction.FromGramsPerGram(decimalfraction.GramsPerGram).DecimalFractions); + Assert.Equal(3, MassFraction.FromGramsPerKilogram(decimalfraction.GramsPerKilogram).DecimalFractions); + Assert.Equal(3, MassFraction.FromHectogramsPerGram(decimalfraction.HectogramsPerGram).DecimalFractions); + Assert.Equal(3, MassFraction.FromHectogramsPerKilogram(decimalfraction.HectogramsPerKilogram).DecimalFractions); + Assert.Equal(3, MassFraction.FromKilogramsPerGram(decimalfraction.KilogramsPerGram).DecimalFractions); + Assert.Equal(3, MassFraction.FromKilogramsPerKilogram(decimalfraction.KilogramsPerKilogram).DecimalFractions); + Assert.Equal(3, MassFraction.FromMicrogramsPerGram(decimalfraction.MicrogramsPerGram).DecimalFractions); + Assert.Equal(3, MassFraction.FromMicrogramsPerKilogram(decimalfraction.MicrogramsPerKilogram).DecimalFractions); + Assert.Equal(3, MassFraction.FromMilligramsPerGram(decimalfraction.MilligramsPerGram).DecimalFractions); + Assert.Equal(3, MassFraction.FromMilligramsPerKilogram(decimalfraction.MilligramsPerKilogram).DecimalFractions); + Assert.Equal(3, MassFraction.FromNanogramsPerGram(decimalfraction.NanogramsPerGram).DecimalFractions); + Assert.Equal(3, MassFraction.FromNanogramsPerKilogram(decimalfraction.NanogramsPerKilogram).DecimalFractions); + Assert.Equal(3, MassFraction.FromPartsPerBillion(decimalfraction.PartsPerBillion).DecimalFractions); + Assert.Equal(3, MassFraction.FromPartsPerMillion(decimalfraction.PartsPerMillion).DecimalFractions); + Assert.Equal(3, MassFraction.FromPartsPerThousand(decimalfraction.PartsPerThousand).DecimalFractions); + Assert.Equal(3, MassFraction.FromPartsPerTrillion(decimalfraction.PartsPerTrillion).DecimalFractions); + Assert.Equal(3, MassFraction.FromPercent(decimalfraction.Percent).DecimalFractions); } [Fact] public void ArithmeticOperators() { MassFraction v = MassFraction.FromDecimalFractions(1); - AssertEx.EqualTolerance(-1, -v.DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(2, (MassFraction.FromDecimalFractions(3)-v).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(2, (v + v).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(10, (v*10).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(10, (10*v).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(2, (MassFraction.FromDecimalFractions(10)/5).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(2, MassFraction.FromDecimalFractions(10)/MassFraction.FromDecimalFractions(5), DecimalFractionsTolerance); + Assert.Equal(-1, -v.DecimalFractions); + Assert.Equal(2, (MassFraction.FromDecimalFractions(3) - v).DecimalFractions); + Assert.Equal(2, (v + v).DecimalFractions); + Assert.Equal(10, (v * 10).DecimalFractions); + Assert.Equal(10, (10 * v).DecimalFractions); + Assert.Equal(2, (MassFraction.FromDecimalFractions(10) / 5).DecimalFractions); + Assert.Equal(2, MassFraction.FromDecimalFractions(10) / MassFraction.FromDecimalFractions(5)); } [Fact] @@ -877,8 +894,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, MassFractionUnit.DecimalFraction, 1, MassFractionUnit.DecimalFraction, true)] // Same value and unit. [InlineData(1, MassFractionUnit.DecimalFraction, 2, MassFractionUnit.DecimalFraction, false)] // Different value. - [InlineData(2, MassFractionUnit.DecimalFraction, 1, MassFractionUnit.CentigramPerGram, false)] // Different value and unit. - [InlineData(1, MassFractionUnit.DecimalFraction, 1, MassFractionUnit.CentigramPerGram, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, MassFractionUnit unitA, double valueB, MassFractionUnit unitB, bool expectEqual) { var a = new MassFraction(valueA, unitA); @@ -938,8 +953,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = MassFraction.FromDecimalFractions(firstValue); var otherQuantity = MassFraction.FromDecimalFractions(secondValue); MassFraction maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, MassFraction.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -958,7 +973,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -971,6 +986,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(MassFraction.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(MassFraction.Info.Units, MassFraction.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, MassFraction.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1079,7 +1106,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = MassFraction.FromDecimalFractions(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(MassFraction), quantity.As(MassFraction.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs index 77d58175ae..41ea721d49 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassMomentOfInertiaTestsBase.g.cs @@ -233,6 +233,20 @@ public void MassMomentOfInertia_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void MassMomentOfInertiaInfo_CreateWithCustomUnitInfos() + { + MassMomentOfInertiaUnit[] expectedUnits = [MassMomentOfInertiaUnit.KilogramSquareMeter]; + + MassMomentOfInertia.MassMomentOfInertiaInfo quantityInfo = MassMomentOfInertia.MassMomentOfInertiaInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("MassMomentOfInertia", quantityInfo.Name); + Assert.Equal(MassMomentOfInertia.Zero, quantityInfo.Zero); + Assert.Equal(MassMomentOfInertia.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void KilogramSquareMeterToMassMomentOfInertiaUnits() { @@ -465,7 +479,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 t·dm²", MassMomentOfInertiaUnit.TonneSquareDecimeter, 4.2)] [InlineData("en-US", "4.2 t·m²", MassMomentOfInertiaUnit.TonneSquareMeter, 4.2)] [InlineData("en-US", "4.2 t·mm²", MassMomentOfInertiaUnit.TonneSquareMillimeter, 4.2)] - public void Parse(string culture, string quantityString, MassMomentOfInertiaUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, MassMomentOfInertiaUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = MassMomentOfInertia.Parse(quantityString); @@ -502,7 +516,7 @@ public void Parse(string culture, string quantityString, MassMomentOfInertiaUnit [InlineData("en-US", "4.2 t·dm²", MassMomentOfInertiaUnit.TonneSquareDecimeter, 4.2)] [InlineData("en-US", "4.2 t·m²", MassMomentOfInertiaUnit.TonneSquareMeter, 4.2)] [InlineData("en-US", "4.2 t·mm²", MassMomentOfInertiaUnit.TonneSquareMillimeter, 4.2)] - public void TryParse(string culture, string quantityString, MassMomentOfInertiaUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, MassMomentOfInertiaUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(MassMomentOfInertia.TryParse(quantityString, out MassMomentOfInertia parsed)); @@ -878,6 +892,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassMomentOfIner var quantity = MassMomentOfInertia.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -901,59 +916,61 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(MassMomentOfInertia IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - MassMomentOfInertia kilogramsquaremeter = MassMomentOfInertia.FromKilogramSquareMeters(1); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromGramSquareCentimeters(kilogramsquaremeter.GramSquareCentimeters).KilogramSquareMeters, GramSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromGramSquareDecimeters(kilogramsquaremeter.GramSquareDecimeters).KilogramSquareMeters, GramSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromGramSquareMeters(kilogramsquaremeter.GramSquareMeters).KilogramSquareMeters, GramSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromGramSquareMillimeters(kilogramsquaremeter.GramSquareMillimeters).KilogramSquareMeters, GramSquareMillimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromKilogramSquareCentimeters(kilogramsquaremeter.KilogramSquareCentimeters).KilogramSquareMeters, KilogramSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromKilogramSquareDecimeters(kilogramsquaremeter.KilogramSquareDecimeters).KilogramSquareMeters, KilogramSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromKilogramSquareMeters(kilogramsquaremeter.KilogramSquareMeters).KilogramSquareMeters, KilogramSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromKilogramSquareMillimeters(kilogramsquaremeter.KilogramSquareMillimeters).KilogramSquareMeters, KilogramSquareMillimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromKilotonneSquareCentimeters(kilogramsquaremeter.KilotonneSquareCentimeters).KilogramSquareMeters, KilotonneSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromKilotonneSquareDecimeters(kilogramsquaremeter.KilotonneSquareDecimeters).KilogramSquareMeters, KilotonneSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromKilotonneSquareMeters(kilogramsquaremeter.KilotonneSquareMeters).KilogramSquareMeters, KilotonneSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromKilotonneSquareMillimeters(kilogramsquaremeter.KilotonneSquareMillimeters).KilogramSquareMeters, KilotonneSquareMillimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromMegatonneSquareCentimeters(kilogramsquaremeter.MegatonneSquareCentimeters).KilogramSquareMeters, MegatonneSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromMegatonneSquareDecimeters(kilogramsquaremeter.MegatonneSquareDecimeters).KilogramSquareMeters, MegatonneSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromMegatonneSquareMeters(kilogramsquaremeter.MegatonneSquareMeters).KilogramSquareMeters, MegatonneSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromMegatonneSquareMillimeters(kilogramsquaremeter.MegatonneSquareMillimeters).KilogramSquareMeters, MegatonneSquareMillimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromMilligramSquareCentimeters(kilogramsquaremeter.MilligramSquareCentimeters).KilogramSquareMeters, MilligramSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromMilligramSquareDecimeters(kilogramsquaremeter.MilligramSquareDecimeters).KilogramSquareMeters, MilligramSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromMilligramSquareMeters(kilogramsquaremeter.MilligramSquareMeters).KilogramSquareMeters, MilligramSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromMilligramSquareMillimeters(kilogramsquaremeter.MilligramSquareMillimeters).KilogramSquareMeters, MilligramSquareMillimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromPoundSquareFeet(kilogramsquaremeter.PoundSquareFeet).KilogramSquareMeters, PoundSquareFeetTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromPoundSquareInches(kilogramsquaremeter.PoundSquareInches).KilogramSquareMeters, PoundSquareInchesTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromSlugSquareFeet(kilogramsquaremeter.SlugSquareFeet).KilogramSquareMeters, SlugSquareFeetTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromSlugSquareInches(kilogramsquaremeter.SlugSquareInches).KilogramSquareMeters, SlugSquareInchesTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromTonneSquareCentimeters(kilogramsquaremeter.TonneSquareCentimeters).KilogramSquareMeters, TonneSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromTonneSquareDecimeters(kilogramsquaremeter.TonneSquareDecimeters).KilogramSquareMeters, TonneSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromTonneSquareMeters(kilogramsquaremeter.TonneSquareMeters).KilogramSquareMeters, TonneSquareMetersTolerance); - AssertEx.EqualTolerance(1, MassMomentOfInertia.FromTonneSquareMillimeters(kilogramsquaremeter.TonneSquareMillimeters).KilogramSquareMeters, TonneSquareMillimetersTolerance); + MassMomentOfInertia kilogramsquaremeter = MassMomentOfInertia.FromKilogramSquareMeters(3); + Assert.Equal(3, MassMomentOfInertia.FromGramSquareCentimeters(kilogramsquaremeter.GramSquareCentimeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromGramSquareDecimeters(kilogramsquaremeter.GramSquareDecimeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromGramSquareMeters(kilogramsquaremeter.GramSquareMeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromGramSquareMillimeters(kilogramsquaremeter.GramSquareMillimeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromKilogramSquareCentimeters(kilogramsquaremeter.KilogramSquareCentimeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromKilogramSquareDecimeters(kilogramsquaremeter.KilogramSquareDecimeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromKilogramSquareMeters(kilogramsquaremeter.KilogramSquareMeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromKilogramSquareMillimeters(kilogramsquaremeter.KilogramSquareMillimeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromKilotonneSquareCentimeters(kilogramsquaremeter.KilotonneSquareCentimeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromKilotonneSquareDecimeters(kilogramsquaremeter.KilotonneSquareDecimeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromKilotonneSquareMeters(kilogramsquaremeter.KilotonneSquareMeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromKilotonneSquareMillimeters(kilogramsquaremeter.KilotonneSquareMillimeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromMegatonneSquareCentimeters(kilogramsquaremeter.MegatonneSquareCentimeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromMegatonneSquareDecimeters(kilogramsquaremeter.MegatonneSquareDecimeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromMegatonneSquareMeters(kilogramsquaremeter.MegatonneSquareMeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromMegatonneSquareMillimeters(kilogramsquaremeter.MegatonneSquareMillimeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromMilligramSquareCentimeters(kilogramsquaremeter.MilligramSquareCentimeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromMilligramSquareDecimeters(kilogramsquaremeter.MilligramSquareDecimeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromMilligramSquareMeters(kilogramsquaremeter.MilligramSquareMeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromMilligramSquareMillimeters(kilogramsquaremeter.MilligramSquareMillimeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromPoundSquareFeet(kilogramsquaremeter.PoundSquareFeet).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromPoundSquareInches(kilogramsquaremeter.PoundSquareInches).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromSlugSquareFeet(kilogramsquaremeter.SlugSquareFeet).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromSlugSquareInches(kilogramsquaremeter.SlugSquareInches).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromTonneSquareCentimeters(kilogramsquaremeter.TonneSquareCentimeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromTonneSquareDecimeters(kilogramsquaremeter.TonneSquareDecimeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromTonneSquareMeters(kilogramsquaremeter.TonneSquareMeters).KilogramSquareMeters); + Assert.Equal(3, MassMomentOfInertia.FromTonneSquareMillimeters(kilogramsquaremeter.TonneSquareMillimeters).KilogramSquareMeters); } [Fact] public void ArithmeticOperators() { MassMomentOfInertia v = MassMomentOfInertia.FromKilogramSquareMeters(1); - AssertEx.EqualTolerance(-1, -v.KilogramSquareMeters, KilogramSquareMetersTolerance); - AssertEx.EqualTolerance(2, (MassMomentOfInertia.FromKilogramSquareMeters(3)-v).KilogramSquareMeters, KilogramSquareMetersTolerance); - AssertEx.EqualTolerance(2, (v + v).KilogramSquareMeters, KilogramSquareMetersTolerance); - AssertEx.EqualTolerance(10, (v*10).KilogramSquareMeters, KilogramSquareMetersTolerance); - AssertEx.EqualTolerance(10, (10*v).KilogramSquareMeters, KilogramSquareMetersTolerance); - AssertEx.EqualTolerance(2, (MassMomentOfInertia.FromKilogramSquareMeters(10)/5).KilogramSquareMeters, KilogramSquareMetersTolerance); - AssertEx.EqualTolerance(2, MassMomentOfInertia.FromKilogramSquareMeters(10)/MassMomentOfInertia.FromKilogramSquareMeters(5), KilogramSquareMetersTolerance); + Assert.Equal(-1, -v.KilogramSquareMeters); + Assert.Equal(2, (MassMomentOfInertia.FromKilogramSquareMeters(3) - v).KilogramSquareMeters); + Assert.Equal(2, (v + v).KilogramSquareMeters); + Assert.Equal(10, (v * 10).KilogramSquareMeters); + Assert.Equal(10, (10 * v).KilogramSquareMeters); + Assert.Equal(2, (MassMomentOfInertia.FromKilogramSquareMeters(10) / 5).KilogramSquareMeters); + Assert.Equal(2, MassMomentOfInertia.FromKilogramSquareMeters(10) / MassMomentOfInertia.FromKilogramSquareMeters(5)); } [Fact] @@ -999,8 +1016,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, MassMomentOfInertiaUnit.KilogramSquareMeter, 1, MassMomentOfInertiaUnit.KilogramSquareMeter, true)] // Same value and unit. [InlineData(1, MassMomentOfInertiaUnit.KilogramSquareMeter, 2, MassMomentOfInertiaUnit.KilogramSquareMeter, false)] // Different value. - [InlineData(2, MassMomentOfInertiaUnit.KilogramSquareMeter, 1, MassMomentOfInertiaUnit.GramSquareCentimeter, false)] // Different value and unit. - [InlineData(1, MassMomentOfInertiaUnit.KilogramSquareMeter, 1, MassMomentOfInertiaUnit.GramSquareCentimeter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, MassMomentOfInertiaUnit unitA, double valueB, MassMomentOfInertiaUnit unitB, bool expectEqual) { var a = new MassMomentOfInertia(valueA, unitA); @@ -1060,8 +1075,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = MassMomentOfInertia.FromKilogramSquareMeters(firstValue); var otherQuantity = MassMomentOfInertia.FromKilogramSquareMeters(secondValue); MassMomentOfInertia maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, MassMomentOfInertia.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1080,7 +1095,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1093,6 +1108,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(MassMomentOfInertia.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(MassMomentOfInertia.Info.Units, MassMomentOfInertia.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, MassMomentOfInertia.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1209,7 +1236,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = MassMomentOfInertia.FromKilogramSquareMeters(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(MassMomentOfInertia), quantity.As(MassMomentOfInertia.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs index 8a6ee7d588..024d4b47bc 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MassTestsBase.g.cs @@ -229,6 +229,20 @@ public void Mass_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void MassInfo_CreateWithCustomUnitInfos() + { + MassUnit[] expectedUnits = [MassUnit.Kilogram]; + + Mass.MassInfo quantityInfo = Mass.MassInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Mass", quantityInfo.Name); + Assert.Equal(Mass.Zero, quantityInfo.Zero); + Assert.Equal(Mass.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void KilogramToMassUnits() { @@ -504,7 +518,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("zh-CN", "4.2 磅", MassUnit.Pound, 4.2)] [InlineData("zh-CN", "4.2 短吨", MassUnit.ShortTon, 4.2)] [InlineData("zh-CN", "4.2 吨", MassUnit.Tonne, 4.2)] - public void Parse(string culture, string quantityString, MassUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, MassUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Mass.Parse(quantityString); @@ -593,7 +607,7 @@ public void ParseWithAmbiguousAbbreviation(string culture, string quantityString [InlineData("zh-CN", "4.2 磅", MassUnit.Pound, 4.2)] [InlineData("zh-CN", "4.2 短吨", MassUnit.ShortTon, 4.2)] [InlineData("zh-CN", "4.2 吨", MassUnit.Tonne, 4.2)] - public void TryParse(string culture, string quantityString, MassUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, MassUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Mass.TryParse(quantityString, out Mass parsed)); @@ -1232,6 +1246,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MassUnit unit) var quantity = Mass.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -1255,58 +1270,60 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(MassUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Mass kilogram = Mass.FromKilograms(1); - AssertEx.EqualTolerance(1, Mass.FromCentigrams(kilogram.Centigrams).Kilograms, CentigramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromDecagrams(kilogram.Decagrams).Kilograms, DecagramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromDecigrams(kilogram.Decigrams).Kilograms, DecigramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromEarthMasses(kilogram.EarthMasses).Kilograms, EarthMassesTolerance); - AssertEx.EqualTolerance(1, Mass.FromFemtograms(kilogram.Femtograms).Kilograms, FemtogramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromGrains(kilogram.Grains).Kilograms, GrainsTolerance); - AssertEx.EqualTolerance(1, Mass.FromGrams(kilogram.Grams).Kilograms, GramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromHectograms(kilogram.Hectograms).Kilograms, HectogramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromKilograms(kilogram.Kilograms).Kilograms, KilogramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromKilopounds(kilogram.Kilopounds).Kilograms, KilopoundsTolerance); - AssertEx.EqualTolerance(1, Mass.FromKilotonnes(kilogram.Kilotonnes).Kilograms, KilotonnesTolerance); - AssertEx.EqualTolerance(1, Mass.FromLongHundredweight(kilogram.LongHundredweight).Kilograms, LongHundredweightTolerance); - AssertEx.EqualTolerance(1, Mass.FromLongTons(kilogram.LongTons).Kilograms, LongTonsTolerance); - AssertEx.EqualTolerance(1, Mass.FromMegapounds(kilogram.Megapounds).Kilograms, MegapoundsTolerance); - AssertEx.EqualTolerance(1, Mass.FromMegatonnes(kilogram.Megatonnes).Kilograms, MegatonnesTolerance); - AssertEx.EqualTolerance(1, Mass.FromMicrograms(kilogram.Micrograms).Kilograms, MicrogramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromMilligrams(kilogram.Milligrams).Kilograms, MilligramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromNanograms(kilogram.Nanograms).Kilograms, NanogramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromOunces(kilogram.Ounces).Kilograms, OuncesTolerance); - AssertEx.EqualTolerance(1, Mass.FromPicograms(kilogram.Picograms).Kilograms, PicogramsTolerance); - AssertEx.EqualTolerance(1, Mass.FromPounds(kilogram.Pounds).Kilograms, PoundsTolerance); - AssertEx.EqualTolerance(1, Mass.FromShortHundredweight(kilogram.ShortHundredweight).Kilograms, ShortHundredweightTolerance); - AssertEx.EqualTolerance(1, Mass.FromShortTons(kilogram.ShortTons).Kilograms, ShortTonsTolerance); - AssertEx.EqualTolerance(1, Mass.FromSlugs(kilogram.Slugs).Kilograms, SlugsTolerance); - AssertEx.EqualTolerance(1, Mass.FromSolarMasses(kilogram.SolarMasses).Kilograms, SolarMassesTolerance); - AssertEx.EqualTolerance(1, Mass.FromStone(kilogram.Stone).Kilograms, StoneTolerance); - AssertEx.EqualTolerance(1, Mass.FromTonnes(kilogram.Tonnes).Kilograms, TonnesTolerance); + Mass kilogram = Mass.FromKilograms(3); + Assert.Equal(3, Mass.FromCentigrams(kilogram.Centigrams).Kilograms); + Assert.Equal(3, Mass.FromDecagrams(kilogram.Decagrams).Kilograms); + Assert.Equal(3, Mass.FromDecigrams(kilogram.Decigrams).Kilograms); + Assert.Equal(3, Mass.FromEarthMasses(kilogram.EarthMasses).Kilograms); + Assert.Equal(3, Mass.FromFemtograms(kilogram.Femtograms).Kilograms); + Assert.Equal(3, Mass.FromGrains(kilogram.Grains).Kilograms); + Assert.Equal(3, Mass.FromGrams(kilogram.Grams).Kilograms); + Assert.Equal(3, Mass.FromHectograms(kilogram.Hectograms).Kilograms); + Assert.Equal(3, Mass.FromKilograms(kilogram.Kilograms).Kilograms); + Assert.Equal(3, Mass.FromKilopounds(kilogram.Kilopounds).Kilograms); + Assert.Equal(3, Mass.FromKilotonnes(kilogram.Kilotonnes).Kilograms); + Assert.Equal(3, Mass.FromLongHundredweight(kilogram.LongHundredweight).Kilograms); + Assert.Equal(3, Mass.FromLongTons(kilogram.LongTons).Kilograms); + Assert.Equal(3, Mass.FromMegapounds(kilogram.Megapounds).Kilograms); + Assert.Equal(3, Mass.FromMegatonnes(kilogram.Megatonnes).Kilograms); + Assert.Equal(3, Mass.FromMicrograms(kilogram.Micrograms).Kilograms); + Assert.Equal(3, Mass.FromMilligrams(kilogram.Milligrams).Kilograms); + Assert.Equal(3, Mass.FromNanograms(kilogram.Nanograms).Kilograms); + Assert.Equal(3, Mass.FromOunces(kilogram.Ounces).Kilograms); + Assert.Equal(3, Mass.FromPicograms(kilogram.Picograms).Kilograms); + Assert.Equal(3, Mass.FromPounds(kilogram.Pounds).Kilograms); + Assert.Equal(3, Mass.FromShortHundredweight(kilogram.ShortHundredweight).Kilograms); + Assert.Equal(3, Mass.FromShortTons(kilogram.ShortTons).Kilograms); + Assert.Equal(3, Mass.FromSlugs(kilogram.Slugs).Kilograms); + Assert.Equal(3, Mass.FromSolarMasses(kilogram.SolarMasses).Kilograms); + Assert.Equal(3, Mass.FromStone(kilogram.Stone).Kilograms); + Assert.Equal(3, Mass.FromTonnes(kilogram.Tonnes).Kilograms); } [Fact] public void ArithmeticOperators() { Mass v = Mass.FromKilograms(1); - AssertEx.EqualTolerance(-1, -v.Kilograms, KilogramsTolerance); - AssertEx.EqualTolerance(2, (Mass.FromKilograms(3)-v).Kilograms, KilogramsTolerance); - AssertEx.EqualTolerance(2, (v + v).Kilograms, KilogramsTolerance); - AssertEx.EqualTolerance(10, (v*10).Kilograms, KilogramsTolerance); - AssertEx.EqualTolerance(10, (10*v).Kilograms, KilogramsTolerance); - AssertEx.EqualTolerance(2, (Mass.FromKilograms(10)/5).Kilograms, KilogramsTolerance); - AssertEx.EqualTolerance(2, Mass.FromKilograms(10)/Mass.FromKilograms(5), KilogramsTolerance); + Assert.Equal(-1, -v.Kilograms); + Assert.Equal(2, (Mass.FromKilograms(3) - v).Kilograms); + Assert.Equal(2, (v + v).Kilograms); + Assert.Equal(10, (v * 10).Kilograms); + Assert.Equal(10, (10 * v).Kilograms); + Assert.Equal(2, (Mass.FromKilograms(10) / 5).Kilograms); + Assert.Equal(2, Mass.FromKilograms(10) / Mass.FromKilograms(5)); } [Fact] @@ -1352,8 +1369,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, MassUnit.Kilogram, 1, MassUnit.Kilogram, true)] // Same value and unit. [InlineData(1, MassUnit.Kilogram, 2, MassUnit.Kilogram, false)] // Different value. - [InlineData(2, MassUnit.Kilogram, 1, MassUnit.Centigram, false)] // Different value and unit. - [InlineData(1, MassUnit.Kilogram, 1, MassUnit.Centigram, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, MassUnit unitA, double valueB, MassUnit unitB, bool expectEqual) { var a = new Mass(valueA, unitA); @@ -1413,8 +1428,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Mass.FromKilograms(firstValue); var otherQuantity = Mass.FromKilograms(secondValue); Mass maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Mass.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1433,7 +1448,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1446,6 +1461,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Mass.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Mass.Info.Units, Mass.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Mass.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1560,7 +1587,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Mass.FromKilograms(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Mass), quantity.As(Mass.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolalityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolalityTestsBase.g.cs index ca8967f67a..814c6b67fc 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolalityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolalityTestsBase.g.cs @@ -133,6 +133,20 @@ public void Molality_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void MolalityInfo_CreateWithCustomUnitInfos() + { + MolalityUnit[] expectedUnits = [MolalityUnit.MolePerKilogram]; + + Molality.MolalityInfo quantityInfo = Molality.MolalityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Molality", quantityInfo.Name); + Assert.Equal(Molality.Zero, quantityInfo.Zero); + Assert.Equal(Molality.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void MolePerKilogramToMolalityUnits() { @@ -290,7 +304,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 mmol/kg", MolalityUnit.MillimolePerKilogram, 4.2)] [InlineData("en-US", "4.2 mol/g", MolalityUnit.MolePerGram, 4.2)] [InlineData("en-US", "4.2 mol/kg", MolalityUnit.MolePerKilogram, 4.2)] - public void Parse(string culture, string quantityString, MolalityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, MolalityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Molality.Parse(quantityString); @@ -302,7 +316,7 @@ public void Parse(string culture, string quantityString, MolalityUnit expectedUn [InlineData("en-US", "4.2 mmol/kg", MolalityUnit.MillimolePerKilogram, 4.2)] [InlineData("en-US", "4.2 mol/g", MolalityUnit.MolePerGram, 4.2)] [InlineData("en-US", "4.2 mol/kg", MolalityUnit.MolePerKilogram, 4.2)] - public void TryParse(string culture, string quantityString, MolalityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, MolalityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Molality.TryParse(quantityString, out Molality parsed)); @@ -453,6 +467,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolalityUnit uni var quantity = Molality.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -476,34 +491,36 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(MolalityUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Molality moleperkilogram = Molality.FromMolesPerKilogram(1); - AssertEx.EqualTolerance(1, Molality.FromMillimolesPerKilogram(moleperkilogram.MillimolesPerKilogram).MolesPerKilogram, MillimolesPerKilogramTolerance); - AssertEx.EqualTolerance(1, Molality.FromMolesPerGram(moleperkilogram.MolesPerGram).MolesPerKilogram, MolesPerGramTolerance); - AssertEx.EqualTolerance(1, Molality.FromMolesPerKilogram(moleperkilogram.MolesPerKilogram).MolesPerKilogram, MolesPerKilogramTolerance); + Molality moleperkilogram = Molality.FromMolesPerKilogram(3); + Assert.Equal(3, Molality.FromMillimolesPerKilogram(moleperkilogram.MillimolesPerKilogram).MolesPerKilogram); + Assert.Equal(3, Molality.FromMolesPerGram(moleperkilogram.MolesPerGram).MolesPerKilogram); + Assert.Equal(3, Molality.FromMolesPerKilogram(moleperkilogram.MolesPerKilogram).MolesPerKilogram); } [Fact] public void ArithmeticOperators() { Molality v = Molality.FromMolesPerKilogram(1); - AssertEx.EqualTolerance(-1, -v.MolesPerKilogram, MolesPerKilogramTolerance); - AssertEx.EqualTolerance(2, (Molality.FromMolesPerKilogram(3)-v).MolesPerKilogram, MolesPerKilogramTolerance); - AssertEx.EqualTolerance(2, (v + v).MolesPerKilogram, MolesPerKilogramTolerance); - AssertEx.EqualTolerance(10, (v*10).MolesPerKilogram, MolesPerKilogramTolerance); - AssertEx.EqualTolerance(10, (10*v).MolesPerKilogram, MolesPerKilogramTolerance); - AssertEx.EqualTolerance(2, (Molality.FromMolesPerKilogram(10)/5).MolesPerKilogram, MolesPerKilogramTolerance); - AssertEx.EqualTolerance(2, Molality.FromMolesPerKilogram(10)/Molality.FromMolesPerKilogram(5), MolesPerKilogramTolerance); + Assert.Equal(-1, -v.MolesPerKilogram); + Assert.Equal(2, (Molality.FromMolesPerKilogram(3) - v).MolesPerKilogram); + Assert.Equal(2, (v + v).MolesPerKilogram); + Assert.Equal(10, (v * 10).MolesPerKilogram); + Assert.Equal(10, (10 * v).MolesPerKilogram); + Assert.Equal(2, (Molality.FromMolesPerKilogram(10) / 5).MolesPerKilogram); + Assert.Equal(2, Molality.FromMolesPerKilogram(10) / Molality.FromMolesPerKilogram(5)); } [Fact] @@ -549,8 +566,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, MolalityUnit.MolePerKilogram, 1, MolalityUnit.MolePerKilogram, true)] // Same value and unit. [InlineData(1, MolalityUnit.MolePerKilogram, 2, MolalityUnit.MolePerKilogram, false)] // Different value. - [InlineData(2, MolalityUnit.MolePerKilogram, 1, MolalityUnit.MillimolePerKilogram, false)] // Different value and unit. - [InlineData(1, MolalityUnit.MolePerKilogram, 1, MolalityUnit.MillimolePerKilogram, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, MolalityUnit unitA, double valueB, MolalityUnit unitB, bool expectEqual) { var a = new Molality(valueA, unitA); @@ -610,8 +625,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Molality.FromMolesPerKilogram(firstValue); var otherQuantity = Molality.FromMolesPerKilogram(secondValue); Molality maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Molality.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -630,7 +645,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -643,6 +658,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Molality.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Molality.Info.Units, Molality.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Molality.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -709,7 +736,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Molality.FromMolesPerKilogram(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Molality), quantity.As(Molality.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs index de719d4b11..1a94eb9f5e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEnergyTestsBase.g.cs @@ -133,6 +133,20 @@ public void MolarEnergy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void MolarEnergyInfo_CreateWithCustomUnitInfos() + { + MolarEnergyUnit[] expectedUnits = [MolarEnergyUnit.JoulePerMole]; + + MolarEnergy.MolarEnergyInfo quantityInfo = MolarEnergy.MolarEnergyInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("MolarEnergy", quantityInfo.Name); + Assert.Equal(MolarEnergy.Zero, quantityInfo.Zero); + Assert.Equal(MolarEnergy.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void JoulePerMoleToMolarEnergyUnits() { @@ -290,7 +304,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 J/mol", MolarEnergyUnit.JoulePerMole, 4.2)] [InlineData("en-US", "4.2 kJ/mol", MolarEnergyUnit.KilojoulePerMole, 4.2)] [InlineData("en-US", "4.2 MJ/mol", MolarEnergyUnit.MegajoulePerMole, 4.2)] - public void Parse(string culture, string quantityString, MolarEnergyUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, MolarEnergyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = MolarEnergy.Parse(quantityString); @@ -302,7 +316,7 @@ public void Parse(string culture, string quantityString, MolarEnergyUnit expecte [InlineData("en-US", "4.2 J/mol", MolarEnergyUnit.JoulePerMole, 4.2)] [InlineData("en-US", "4.2 kJ/mol", MolarEnergyUnit.KilojoulePerMole, 4.2)] [InlineData("en-US", "4.2 MJ/mol", MolarEnergyUnit.MegajoulePerMole, 4.2)] - public void TryParse(string culture, string quantityString, MolarEnergyUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, MolarEnergyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(MolarEnergy.TryParse(quantityString, out MolarEnergy parsed)); @@ -453,6 +467,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolarEnergyUnit var quantity = MolarEnergy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -476,34 +491,36 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(MolarEnergyUnit uni IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - MolarEnergy joulepermole = MolarEnergy.FromJoulesPerMole(1); - AssertEx.EqualTolerance(1, MolarEnergy.FromJoulesPerMole(joulepermole.JoulesPerMole).JoulesPerMole, JoulesPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarEnergy.FromKilojoulesPerMole(joulepermole.KilojoulesPerMole).JoulesPerMole, KilojoulesPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarEnergy.FromMegajoulesPerMole(joulepermole.MegajoulesPerMole).JoulesPerMole, MegajoulesPerMoleTolerance); + MolarEnergy joulepermole = MolarEnergy.FromJoulesPerMole(3); + Assert.Equal(3, MolarEnergy.FromJoulesPerMole(joulepermole.JoulesPerMole).JoulesPerMole); + Assert.Equal(3, MolarEnergy.FromKilojoulesPerMole(joulepermole.KilojoulesPerMole).JoulesPerMole); + Assert.Equal(3, MolarEnergy.FromMegajoulesPerMole(joulepermole.MegajoulesPerMole).JoulesPerMole); } [Fact] public void ArithmeticOperators() { MolarEnergy v = MolarEnergy.FromJoulesPerMole(1); - AssertEx.EqualTolerance(-1, -v.JoulesPerMole, JoulesPerMoleTolerance); - AssertEx.EqualTolerance(2, (MolarEnergy.FromJoulesPerMole(3)-v).JoulesPerMole, JoulesPerMoleTolerance); - AssertEx.EqualTolerance(2, (v + v).JoulesPerMole, JoulesPerMoleTolerance); - AssertEx.EqualTolerance(10, (v*10).JoulesPerMole, JoulesPerMoleTolerance); - AssertEx.EqualTolerance(10, (10*v).JoulesPerMole, JoulesPerMoleTolerance); - AssertEx.EqualTolerance(2, (MolarEnergy.FromJoulesPerMole(10)/5).JoulesPerMole, JoulesPerMoleTolerance); - AssertEx.EqualTolerance(2, MolarEnergy.FromJoulesPerMole(10)/MolarEnergy.FromJoulesPerMole(5), JoulesPerMoleTolerance); + Assert.Equal(-1, -v.JoulesPerMole); + Assert.Equal(2, (MolarEnergy.FromJoulesPerMole(3) - v).JoulesPerMole); + Assert.Equal(2, (v + v).JoulesPerMole); + Assert.Equal(10, (v * 10).JoulesPerMole); + Assert.Equal(10, (10 * v).JoulesPerMole); + Assert.Equal(2, (MolarEnergy.FromJoulesPerMole(10) / 5).JoulesPerMole); + Assert.Equal(2, MolarEnergy.FromJoulesPerMole(10) / MolarEnergy.FromJoulesPerMole(5)); } [Fact] @@ -549,8 +566,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, MolarEnergyUnit.JoulePerMole, 1, MolarEnergyUnit.JoulePerMole, true)] // Same value and unit. [InlineData(1, MolarEnergyUnit.JoulePerMole, 2, MolarEnergyUnit.JoulePerMole, false)] // Different value. - [InlineData(2, MolarEnergyUnit.JoulePerMole, 1, MolarEnergyUnit.KilojoulePerMole, false)] // Different value and unit. - [InlineData(1, MolarEnergyUnit.JoulePerMole, 1, MolarEnergyUnit.KilojoulePerMole, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, MolarEnergyUnit unitA, double valueB, MolarEnergyUnit unitB, bool expectEqual) { var a = new MolarEnergy(valueA, unitA); @@ -610,8 +625,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = MolarEnergy.FromJoulesPerMole(firstValue); var otherQuantity = MolarEnergy.FromJoulesPerMole(secondValue); MolarEnergy maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, MolarEnergy.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -630,7 +645,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -643,6 +658,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(MolarEnergy.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(MolarEnergy.Info.Units, MolarEnergy.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, MolarEnergy.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -709,7 +736,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = MolarEnergy.FromJoulesPerMole(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(MolarEnergy), quantity.As(MolarEnergy.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs index d9c5a504a4..3f2dbc851f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarEntropyTestsBase.g.cs @@ -133,6 +133,20 @@ public void MolarEntropy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void MolarEntropyInfo_CreateWithCustomUnitInfos() + { + MolarEntropyUnit[] expectedUnits = [MolarEntropyUnit.JoulePerMoleKelvin]; + + MolarEntropy.MolarEntropyInfo quantityInfo = MolarEntropy.MolarEntropyInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("MolarEntropy", quantityInfo.Name); + Assert.Equal(MolarEntropy.Zero, quantityInfo.Zero); + Assert.Equal(MolarEntropy.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void JoulePerMoleKelvinToMolarEntropyUnits() { @@ -290,7 +304,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 J/(mol·K)", MolarEntropyUnit.JoulePerMoleKelvin, 4.2)] [InlineData("en-US", "4.2 kJ/(mol·K)", MolarEntropyUnit.KilojoulePerMoleKelvin, 4.2)] [InlineData("en-US", "4.2 MJ/(mol·K)", MolarEntropyUnit.MegajoulePerMoleKelvin, 4.2)] - public void Parse(string culture, string quantityString, MolarEntropyUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, MolarEntropyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = MolarEntropy.Parse(quantityString); @@ -302,7 +316,7 @@ public void Parse(string culture, string quantityString, MolarEntropyUnit expect [InlineData("en-US", "4.2 J/(mol·K)", MolarEntropyUnit.JoulePerMoleKelvin, 4.2)] [InlineData("en-US", "4.2 kJ/(mol·K)", MolarEntropyUnit.KilojoulePerMoleKelvin, 4.2)] [InlineData("en-US", "4.2 MJ/(mol·K)", MolarEntropyUnit.MegajoulePerMoleKelvin, 4.2)] - public void TryParse(string culture, string quantityString, MolarEntropyUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, MolarEntropyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(MolarEntropy.TryParse(quantityString, out MolarEntropy parsed)); @@ -453,6 +467,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolarEntropyUnit var quantity = MolarEntropy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -476,34 +491,36 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(MolarEntropyUnit un IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - MolarEntropy joulepermolekelvin = MolarEntropy.FromJoulesPerMoleKelvin(1); - AssertEx.EqualTolerance(1, MolarEntropy.FromJoulesPerMoleKelvin(joulepermolekelvin.JoulesPerMoleKelvin).JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(1, MolarEntropy.FromKilojoulesPerMoleKelvin(joulepermolekelvin.KilojoulesPerMoleKelvin).JoulesPerMoleKelvin, KilojoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(1, MolarEntropy.FromMegajoulesPerMoleKelvin(joulepermolekelvin.MegajoulesPerMoleKelvin).JoulesPerMoleKelvin, MegajoulesPerMoleKelvinTolerance); + MolarEntropy joulepermolekelvin = MolarEntropy.FromJoulesPerMoleKelvin(3); + Assert.Equal(3, MolarEntropy.FromJoulesPerMoleKelvin(joulepermolekelvin.JoulesPerMoleKelvin).JoulesPerMoleKelvin); + Assert.Equal(3, MolarEntropy.FromKilojoulesPerMoleKelvin(joulepermolekelvin.KilojoulesPerMoleKelvin).JoulesPerMoleKelvin); + Assert.Equal(3, MolarEntropy.FromMegajoulesPerMoleKelvin(joulepermolekelvin.MegajoulesPerMoleKelvin).JoulesPerMoleKelvin); } [Fact] public void ArithmeticOperators() { MolarEntropy v = MolarEntropy.FromJoulesPerMoleKelvin(1); - AssertEx.EqualTolerance(-1, -v.JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(2, (MolarEntropy.FromJoulesPerMoleKelvin(3)-v).JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(2, (v + v).JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(10, (v*10).JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(10, (10*v).JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(2, (MolarEntropy.FromJoulesPerMoleKelvin(10)/5).JoulesPerMoleKelvin, JoulesPerMoleKelvinTolerance); - AssertEx.EqualTolerance(2, MolarEntropy.FromJoulesPerMoleKelvin(10)/MolarEntropy.FromJoulesPerMoleKelvin(5), JoulesPerMoleKelvinTolerance); + Assert.Equal(-1, -v.JoulesPerMoleKelvin); + Assert.Equal(2, (MolarEntropy.FromJoulesPerMoleKelvin(3) - v).JoulesPerMoleKelvin); + Assert.Equal(2, (v + v).JoulesPerMoleKelvin); + Assert.Equal(10, (v * 10).JoulesPerMoleKelvin); + Assert.Equal(10, (10 * v).JoulesPerMoleKelvin); + Assert.Equal(2, (MolarEntropy.FromJoulesPerMoleKelvin(10) / 5).JoulesPerMoleKelvin); + Assert.Equal(2, MolarEntropy.FromJoulesPerMoleKelvin(10) / MolarEntropy.FromJoulesPerMoleKelvin(5)); } [Fact] @@ -549,8 +566,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, MolarEntropyUnit.JoulePerMoleKelvin, 1, MolarEntropyUnit.JoulePerMoleKelvin, true)] // Same value and unit. [InlineData(1, MolarEntropyUnit.JoulePerMoleKelvin, 2, MolarEntropyUnit.JoulePerMoleKelvin, false)] // Different value. - [InlineData(2, MolarEntropyUnit.JoulePerMoleKelvin, 1, MolarEntropyUnit.KilojoulePerMoleKelvin, false)] // Different value and unit. - [InlineData(1, MolarEntropyUnit.JoulePerMoleKelvin, 1, MolarEntropyUnit.KilojoulePerMoleKelvin, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, MolarEntropyUnit unitA, double valueB, MolarEntropyUnit unitB, bool expectEqual) { var a = new MolarEntropy(valueA, unitA); @@ -610,8 +625,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = MolarEntropy.FromJoulesPerMoleKelvin(firstValue); var otherQuantity = MolarEntropy.FromJoulesPerMoleKelvin(secondValue); MolarEntropy maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, MolarEntropy.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -630,7 +645,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -643,6 +658,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(MolarEntropy.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(MolarEntropy.Info.Units, MolarEntropy.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, MolarEntropy.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -709,7 +736,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = MolarEntropy.FromJoulesPerMoleKelvin(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(MolarEntropy), quantity.As(MolarEntropy.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarFlowTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarFlowTestsBase.g.cs index c1a6faad87..6f870b1385 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarFlowTestsBase.g.cs @@ -157,6 +157,20 @@ public void MolarFlow_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void MolarFlowInfo_CreateWithCustomUnitInfos() + { + MolarFlowUnit[] expectedUnits = [MolarFlowUnit.MolePerSecond]; + + MolarFlow.MolarFlowInfo quantityInfo = MolarFlow.MolarFlowInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("MolarFlow", quantityInfo.Name); + Assert.Equal(MolarFlow.Zero, quantityInfo.Zero); + Assert.Equal(MolarFlow.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void MolePerSecondToMolarFlowUnits() { @@ -332,7 +346,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 lbmol/h", MolarFlowUnit.PoundMolePerHour, 4.2)] [InlineData("en-US", "4.2 lbmol/min", MolarFlowUnit.PoundMolePerMinute, 4.2)] [InlineData("en-US", "4.2 lbmol/s", MolarFlowUnit.PoundMolePerSecond, 4.2)] - public void Parse(string culture, string quantityString, MolarFlowUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, MolarFlowUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = MolarFlow.Parse(quantityString); @@ -350,7 +364,7 @@ public void Parse(string culture, string quantityString, MolarFlowUnit expectedU [InlineData("en-US", "4.2 lbmol/h", MolarFlowUnit.PoundMolePerHour, 4.2)] [InlineData("en-US", "4.2 lbmol/min", MolarFlowUnit.PoundMolePerMinute, 4.2)] [InlineData("en-US", "4.2 lbmol/s", MolarFlowUnit.PoundMolePerSecond, 4.2)] - public void TryParse(string culture, string quantityString, MolarFlowUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, MolarFlowUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(MolarFlow.TryParse(quantityString, out MolarFlow parsed)); @@ -555,6 +569,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolarFlowUnit un var quantity = MolarFlow.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -578,40 +593,42 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(MolarFlowUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - MolarFlow molepersecond = MolarFlow.FromMolesPerSecond(1); - AssertEx.EqualTolerance(1, MolarFlow.FromKilomolesPerHour(molepersecond.KilomolesPerHour).MolesPerSecond, KilomolesPerHourTolerance); - AssertEx.EqualTolerance(1, MolarFlow.FromKilomolesPerMinute(molepersecond.KilomolesPerMinute).MolesPerSecond, KilomolesPerMinuteTolerance); - AssertEx.EqualTolerance(1, MolarFlow.FromKilomolesPerSecond(molepersecond.KilomolesPerSecond).MolesPerSecond, KilomolesPerSecondTolerance); - AssertEx.EqualTolerance(1, MolarFlow.FromMolesPerHour(molepersecond.MolesPerHour).MolesPerSecond, MolesPerHourTolerance); - AssertEx.EqualTolerance(1, MolarFlow.FromMolesPerMinute(molepersecond.MolesPerMinute).MolesPerSecond, MolesPerMinuteTolerance); - AssertEx.EqualTolerance(1, MolarFlow.FromMolesPerSecond(molepersecond.MolesPerSecond).MolesPerSecond, MolesPerSecondTolerance); - AssertEx.EqualTolerance(1, MolarFlow.FromPoundMolesPerHour(molepersecond.PoundMolesPerHour).MolesPerSecond, PoundMolesPerHourTolerance); - AssertEx.EqualTolerance(1, MolarFlow.FromPoundMolesPerMinute(molepersecond.PoundMolesPerMinute).MolesPerSecond, PoundMolesPerMinuteTolerance); - AssertEx.EqualTolerance(1, MolarFlow.FromPoundMolesPerSecond(molepersecond.PoundMolesPerSecond).MolesPerSecond, PoundMolesPerSecondTolerance); + MolarFlow molepersecond = MolarFlow.FromMolesPerSecond(3); + Assert.Equal(3, MolarFlow.FromKilomolesPerHour(molepersecond.KilomolesPerHour).MolesPerSecond); + Assert.Equal(3, MolarFlow.FromKilomolesPerMinute(molepersecond.KilomolesPerMinute).MolesPerSecond); + Assert.Equal(3, MolarFlow.FromKilomolesPerSecond(molepersecond.KilomolesPerSecond).MolesPerSecond); + Assert.Equal(3, MolarFlow.FromMolesPerHour(molepersecond.MolesPerHour).MolesPerSecond); + Assert.Equal(3, MolarFlow.FromMolesPerMinute(molepersecond.MolesPerMinute).MolesPerSecond); + Assert.Equal(3, MolarFlow.FromMolesPerSecond(molepersecond.MolesPerSecond).MolesPerSecond); + Assert.Equal(3, MolarFlow.FromPoundMolesPerHour(molepersecond.PoundMolesPerHour).MolesPerSecond); + Assert.Equal(3, MolarFlow.FromPoundMolesPerMinute(molepersecond.PoundMolesPerMinute).MolesPerSecond); + Assert.Equal(3, MolarFlow.FromPoundMolesPerSecond(molepersecond.PoundMolesPerSecond).MolesPerSecond); } [Fact] public void ArithmeticOperators() { MolarFlow v = MolarFlow.FromMolesPerSecond(1); - AssertEx.EqualTolerance(-1, -v.MolesPerSecond, MolesPerSecondTolerance); - AssertEx.EqualTolerance(2, (MolarFlow.FromMolesPerSecond(3)-v).MolesPerSecond, MolesPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).MolesPerSecond, MolesPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).MolesPerSecond, MolesPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).MolesPerSecond, MolesPerSecondTolerance); - AssertEx.EqualTolerance(2, (MolarFlow.FromMolesPerSecond(10)/5).MolesPerSecond, MolesPerSecondTolerance); - AssertEx.EqualTolerance(2, MolarFlow.FromMolesPerSecond(10)/MolarFlow.FromMolesPerSecond(5), MolesPerSecondTolerance); + Assert.Equal(-1, -v.MolesPerSecond); + Assert.Equal(2, (MolarFlow.FromMolesPerSecond(3) - v).MolesPerSecond); + Assert.Equal(2, (v + v).MolesPerSecond); + Assert.Equal(10, (v * 10).MolesPerSecond); + Assert.Equal(10, (10 * v).MolesPerSecond); + Assert.Equal(2, (MolarFlow.FromMolesPerSecond(10) / 5).MolesPerSecond); + Assert.Equal(2, MolarFlow.FromMolesPerSecond(10) / MolarFlow.FromMolesPerSecond(5)); } [Fact] @@ -657,8 +674,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, MolarFlowUnit.MolePerSecond, 1, MolarFlowUnit.MolePerSecond, true)] // Same value and unit. [InlineData(1, MolarFlowUnit.MolePerSecond, 2, MolarFlowUnit.MolePerSecond, false)] // Different value. - [InlineData(2, MolarFlowUnit.MolePerSecond, 1, MolarFlowUnit.KilomolePerHour, false)] // Different value and unit. - [InlineData(1, MolarFlowUnit.MolePerSecond, 1, MolarFlowUnit.KilomolePerHour, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, MolarFlowUnit unitA, double valueB, MolarFlowUnit unitB, bool expectEqual) { var a = new MolarFlow(valueA, unitA); @@ -718,8 +733,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = MolarFlow.FromMolesPerSecond(firstValue); var otherQuantity = MolarFlow.FromMolesPerSecond(secondValue); MolarFlow maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, MolarFlow.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -738,7 +753,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -751,6 +766,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(MolarFlow.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(MolarFlow.Info.Units, MolarFlow.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, MolarFlow.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -829,7 +856,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = MolarFlow.FromMolesPerSecond(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(MolarFlow), quantity.As(MolarFlow.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs index 0ce1268d78..d06daadb55 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarMassTestsBase.g.cs @@ -173,6 +173,20 @@ public void MolarMass_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void MolarMassInfo_CreateWithCustomUnitInfos() + { + MolarMassUnit[] expectedUnits = [MolarMassUnit.KilogramPerMole]; + + MolarMass.MolarMassInfo quantityInfo = MolarMass.MolarMassInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("MolarMass", quantityInfo.Name); + Assert.Equal(MolarMass.Zero, quantityInfo.Zero); + Assert.Equal(MolarMass.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void KilogramPerMoleToMolarMassUnits() { @@ -372,7 +386,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 мг/моль", MolarMassUnit.MilligramPerMole, 4.2)] [InlineData("ru-RU", "4,2 нг/моль", MolarMassUnit.NanogramPerMole, 4.2)] [InlineData("ru-RU", "4,2 фунт/моль", MolarMassUnit.PoundPerMole, 4.2)] - public void Parse(string culture, string quantityString, MolarMassUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, MolarMassUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = MolarMass.Parse(quantityString); @@ -406,7 +420,7 @@ public void Parse(string culture, string quantityString, MolarMassUnit expectedU [InlineData("ru-RU", "4,2 мг/моль", MolarMassUnit.MilligramPerMole, 4.2)] [InlineData("ru-RU", "4,2 нг/моль", MolarMassUnit.NanogramPerMole, 4.2)] [InlineData("ru-RU", "4,2 фунт/моль", MolarMassUnit.PoundPerMole, 4.2)] - public void TryParse(string culture, string quantityString, MolarMassUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, MolarMassUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(MolarMass.TryParse(quantityString, out MolarMass parsed)); @@ -707,6 +721,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolarMassUnit un var quantity = MolarMass.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -730,44 +745,46 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(MolarMassUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - MolarMass kilogrampermole = MolarMass.FromKilogramsPerMole(1); - AssertEx.EqualTolerance(1, MolarMass.FromCentigramsPerMole(kilogrampermole.CentigramsPerMole).KilogramsPerMole, CentigramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromDecagramsPerMole(kilogrampermole.DecagramsPerMole).KilogramsPerMole, DecagramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromDecigramsPerMole(kilogrampermole.DecigramsPerMole).KilogramsPerMole, DecigramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromGramsPerMole(kilogrampermole.GramsPerMole).KilogramsPerMole, GramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromHectogramsPerMole(kilogrampermole.HectogramsPerMole).KilogramsPerMole, HectogramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromKilogramsPerKilomole(kilogrampermole.KilogramsPerKilomole).KilogramsPerMole, KilogramsPerKilomoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromKilogramsPerMole(kilogrampermole.KilogramsPerMole).KilogramsPerMole, KilogramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromKilopoundsPerMole(kilogrampermole.KilopoundsPerMole).KilogramsPerMole, KilopoundsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromMegapoundsPerMole(kilogrampermole.MegapoundsPerMole).KilogramsPerMole, MegapoundsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromMicrogramsPerMole(kilogrampermole.MicrogramsPerMole).KilogramsPerMole, MicrogramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromMilligramsPerMole(kilogrampermole.MilligramsPerMole).KilogramsPerMole, MilligramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromNanogramsPerMole(kilogrampermole.NanogramsPerMole).KilogramsPerMole, NanogramsPerMoleTolerance); - AssertEx.EqualTolerance(1, MolarMass.FromPoundsPerMole(kilogrampermole.PoundsPerMole).KilogramsPerMole, PoundsPerMoleTolerance); + MolarMass kilogrampermole = MolarMass.FromKilogramsPerMole(3); + Assert.Equal(3, MolarMass.FromCentigramsPerMole(kilogrampermole.CentigramsPerMole).KilogramsPerMole); + Assert.Equal(3, MolarMass.FromDecagramsPerMole(kilogrampermole.DecagramsPerMole).KilogramsPerMole); + Assert.Equal(3, MolarMass.FromDecigramsPerMole(kilogrampermole.DecigramsPerMole).KilogramsPerMole); + Assert.Equal(3, MolarMass.FromGramsPerMole(kilogrampermole.GramsPerMole).KilogramsPerMole); + Assert.Equal(3, MolarMass.FromHectogramsPerMole(kilogrampermole.HectogramsPerMole).KilogramsPerMole); + Assert.Equal(3, MolarMass.FromKilogramsPerKilomole(kilogrampermole.KilogramsPerKilomole).KilogramsPerMole); + Assert.Equal(3, MolarMass.FromKilogramsPerMole(kilogrampermole.KilogramsPerMole).KilogramsPerMole); + Assert.Equal(3, MolarMass.FromKilopoundsPerMole(kilogrampermole.KilopoundsPerMole).KilogramsPerMole); + Assert.Equal(3, MolarMass.FromMegapoundsPerMole(kilogrampermole.MegapoundsPerMole).KilogramsPerMole); + Assert.Equal(3, MolarMass.FromMicrogramsPerMole(kilogrampermole.MicrogramsPerMole).KilogramsPerMole); + Assert.Equal(3, MolarMass.FromMilligramsPerMole(kilogrampermole.MilligramsPerMole).KilogramsPerMole); + Assert.Equal(3, MolarMass.FromNanogramsPerMole(kilogrampermole.NanogramsPerMole).KilogramsPerMole); + Assert.Equal(3, MolarMass.FromPoundsPerMole(kilogrampermole.PoundsPerMole).KilogramsPerMole); } [Fact] public void ArithmeticOperators() { MolarMass v = MolarMass.FromKilogramsPerMole(1); - AssertEx.EqualTolerance(-1, -v.KilogramsPerMole, KilogramsPerMoleTolerance); - AssertEx.EqualTolerance(2, (MolarMass.FromKilogramsPerMole(3)-v).KilogramsPerMole, KilogramsPerMoleTolerance); - AssertEx.EqualTolerance(2, (v + v).KilogramsPerMole, KilogramsPerMoleTolerance); - AssertEx.EqualTolerance(10, (v*10).KilogramsPerMole, KilogramsPerMoleTolerance); - AssertEx.EqualTolerance(10, (10*v).KilogramsPerMole, KilogramsPerMoleTolerance); - AssertEx.EqualTolerance(2, (MolarMass.FromKilogramsPerMole(10)/5).KilogramsPerMole, KilogramsPerMoleTolerance); - AssertEx.EqualTolerance(2, MolarMass.FromKilogramsPerMole(10)/MolarMass.FromKilogramsPerMole(5), KilogramsPerMoleTolerance); + Assert.Equal(-1, -v.KilogramsPerMole); + Assert.Equal(2, (MolarMass.FromKilogramsPerMole(3) - v).KilogramsPerMole); + Assert.Equal(2, (v + v).KilogramsPerMole); + Assert.Equal(10, (v * 10).KilogramsPerMole); + Assert.Equal(10, (10 * v).KilogramsPerMole); + Assert.Equal(2, (MolarMass.FromKilogramsPerMole(10) / 5).KilogramsPerMole); + Assert.Equal(2, MolarMass.FromKilogramsPerMole(10) / MolarMass.FromKilogramsPerMole(5)); } [Fact] @@ -813,8 +830,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, MolarMassUnit.KilogramPerMole, 1, MolarMassUnit.KilogramPerMole, true)] // Same value and unit. [InlineData(1, MolarMassUnit.KilogramPerMole, 2, MolarMassUnit.KilogramPerMole, false)] // Different value. - [InlineData(2, MolarMassUnit.KilogramPerMole, 1, MolarMassUnit.CentigramPerMole, false)] // Different value and unit. - [InlineData(1, MolarMassUnit.KilogramPerMole, 1, MolarMassUnit.CentigramPerMole, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, MolarMassUnit unitA, double valueB, MolarMassUnit unitB, bool expectEqual) { var a = new MolarMass(valueA, unitA); @@ -874,8 +889,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = MolarMass.FromKilogramsPerMole(firstValue); var otherQuantity = MolarMass.FromKilogramsPerMole(secondValue); MolarMass maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, MolarMass.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -894,7 +909,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -907,6 +922,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(MolarMass.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(MolarMass.Info.Units, MolarMass.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, MolarMass.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -993,7 +1020,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = MolarMass.FromKilogramsPerMole(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(MolarMass), quantity.As(MolarMass.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs index 359d0c9f88..f54338ccfa 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/MolarityTestsBase.g.cs @@ -165,6 +165,20 @@ public void Molarity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void MolarityInfo_CreateWithCustomUnitInfos() + { + MolarityUnit[] expectedUnits = [MolarityUnit.MolePerCubicMeter]; + + Molarity.MolarityInfo quantityInfo = Molarity.MolarityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Molarity", quantityInfo.Name); + Assert.Equal(Molarity.Zero, quantityInfo.Zero); + Assert.Equal(Molarity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void MolePerCubicMeterToMolarityUnits() { @@ -354,7 +368,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 pmol/l", MolarityUnit.PicomolePerLiter, 4.2)] [InlineData("en-US", "4.2 pM", MolarityUnit.PicomolePerLiter, 4.2)] [InlineData("en-US", "4.2 lbmol/ft³", MolarityUnit.PoundMolePerCubicFoot, 4.2)] - public void Parse(string culture, string quantityString, MolarityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, MolarityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Molarity.Parse(quantityString); @@ -382,7 +396,7 @@ public void Parse(string culture, string quantityString, MolarityUnit expectedUn [InlineData("en-US", "4.2 pmol/l", MolarityUnit.PicomolePerLiter, 4.2)] [InlineData("en-US", "4.2 pM", MolarityUnit.PicomolePerLiter, 4.2)] [InlineData("en-US", "4.2 lbmol/ft³", MolarityUnit.PoundMolePerCubicFoot, 4.2)] - public void TryParse(string culture, string quantityString, MolarityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, MolarityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Molarity.TryParse(quantityString, out Molarity parsed)); @@ -669,6 +683,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(MolarityUnit uni var quantity = Molarity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -692,42 +707,44 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(MolarityUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Molarity molepercubicmeter = Molarity.FromMolesPerCubicMeter(1); - AssertEx.EqualTolerance(1, Molarity.FromCentimolesPerLiter(molepercubicmeter.CentimolesPerLiter).MolesPerCubicMeter, CentimolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.FromDecimolesPerLiter(molepercubicmeter.DecimolesPerLiter).MolesPerCubicMeter, DecimolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.FromFemtomolesPerLiter(molepercubicmeter.FemtomolesPerLiter).MolesPerCubicMeter, FemtomolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.FromKilomolesPerCubicMeter(molepercubicmeter.KilomolesPerCubicMeter).MolesPerCubicMeter, KilomolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Molarity.FromMicromolesPerLiter(molepercubicmeter.MicromolesPerLiter).MolesPerCubicMeter, MicromolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.FromMillimolesPerLiter(molepercubicmeter.MillimolesPerLiter).MolesPerCubicMeter, MillimolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.FromMolesPerCubicMeter(molepercubicmeter.MolesPerCubicMeter).MolesPerCubicMeter, MolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, Molarity.FromMolesPerLiter(molepercubicmeter.MolesPerLiter).MolesPerCubicMeter, MolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.FromNanomolesPerLiter(molepercubicmeter.NanomolesPerLiter).MolesPerCubicMeter, NanomolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.FromPicomolesPerLiter(molepercubicmeter.PicomolesPerLiter).MolesPerCubicMeter, PicomolesPerLiterTolerance); - AssertEx.EqualTolerance(1, Molarity.FromPoundMolesPerCubicFoot(molepercubicmeter.PoundMolesPerCubicFoot).MolesPerCubicMeter, PoundMolesPerCubicFootTolerance); + Molarity molepercubicmeter = Molarity.FromMolesPerCubicMeter(3); + Assert.Equal(3, Molarity.FromCentimolesPerLiter(molepercubicmeter.CentimolesPerLiter).MolesPerCubicMeter); + Assert.Equal(3, Molarity.FromDecimolesPerLiter(molepercubicmeter.DecimolesPerLiter).MolesPerCubicMeter); + Assert.Equal(3, Molarity.FromFemtomolesPerLiter(molepercubicmeter.FemtomolesPerLiter).MolesPerCubicMeter); + Assert.Equal(3, Molarity.FromKilomolesPerCubicMeter(molepercubicmeter.KilomolesPerCubicMeter).MolesPerCubicMeter); + Assert.Equal(3, Molarity.FromMicromolesPerLiter(molepercubicmeter.MicromolesPerLiter).MolesPerCubicMeter); + Assert.Equal(3, Molarity.FromMillimolesPerLiter(molepercubicmeter.MillimolesPerLiter).MolesPerCubicMeter); + Assert.Equal(3, Molarity.FromMolesPerCubicMeter(molepercubicmeter.MolesPerCubicMeter).MolesPerCubicMeter); + Assert.Equal(3, Molarity.FromMolesPerLiter(molepercubicmeter.MolesPerLiter).MolesPerCubicMeter); + Assert.Equal(3, Molarity.FromNanomolesPerLiter(molepercubicmeter.NanomolesPerLiter).MolesPerCubicMeter); + Assert.Equal(3, Molarity.FromPicomolesPerLiter(molepercubicmeter.PicomolesPerLiter).MolesPerCubicMeter); + Assert.Equal(3, Molarity.FromPoundMolesPerCubicFoot(molepercubicmeter.PoundMolesPerCubicFoot).MolesPerCubicMeter); } [Fact] public void ArithmeticOperators() { Molarity v = Molarity.FromMolesPerCubicMeter(1); - AssertEx.EqualTolerance(-1, -v.MolesPerCubicMeter, MolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (Molarity.FromMolesPerCubicMeter(3)-v).MolesPerCubicMeter, MolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).MolesPerCubicMeter, MolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).MolesPerCubicMeter, MolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).MolesPerCubicMeter, MolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (Molarity.FromMolesPerCubicMeter(10)/5).MolesPerCubicMeter, MolesPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, Molarity.FromMolesPerCubicMeter(10)/Molarity.FromMolesPerCubicMeter(5), MolesPerCubicMeterTolerance); + Assert.Equal(-1, -v.MolesPerCubicMeter); + Assert.Equal(2, (Molarity.FromMolesPerCubicMeter(3) - v).MolesPerCubicMeter); + Assert.Equal(2, (v + v).MolesPerCubicMeter); + Assert.Equal(10, (v * 10).MolesPerCubicMeter); + Assert.Equal(10, (10 * v).MolesPerCubicMeter); + Assert.Equal(2, (Molarity.FromMolesPerCubicMeter(10) / 5).MolesPerCubicMeter); + Assert.Equal(2, Molarity.FromMolesPerCubicMeter(10) / Molarity.FromMolesPerCubicMeter(5)); } [Fact] @@ -773,8 +790,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, MolarityUnit.MolePerCubicMeter, 1, MolarityUnit.MolePerCubicMeter, true)] // Same value and unit. [InlineData(1, MolarityUnit.MolePerCubicMeter, 2, MolarityUnit.MolePerCubicMeter, false)] // Different value. - [InlineData(2, MolarityUnit.MolePerCubicMeter, 1, MolarityUnit.CentimolePerLiter, false)] // Different value and unit. - [InlineData(1, MolarityUnit.MolePerCubicMeter, 1, MolarityUnit.CentimolePerLiter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, MolarityUnit unitA, double valueB, MolarityUnit unitB, bool expectEqual) { var a = new Molarity(valueA, unitA); @@ -834,8 +849,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Molarity.FromMolesPerCubicMeter(firstValue); var otherQuantity = Molarity.FromMolesPerCubicMeter(secondValue); Molarity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Molarity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -854,7 +869,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -867,6 +882,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Molarity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Molarity.Info.Units, Molarity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Molarity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -949,7 +976,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Molarity.FromMolesPerCubicMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Molarity), quantity.As(Molarity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs index ea51af65ed..8e0380fce2 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PermeabilityTestsBase.g.cs @@ -125,6 +125,20 @@ public void Permeability_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void PermeabilityInfo_CreateWithCustomUnitInfos() + { + PermeabilityUnit[] expectedUnits = [PermeabilityUnit.HenryPerMeter]; + + Permeability.PermeabilityInfo quantityInfo = Permeability.PermeabilityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Permeability", quantityInfo.Name); + Assert.Equal(Permeability.Zero, quantityInfo.Zero); + Assert.Equal(Permeability.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void HenryPerMeterToPermeabilityUnits() { @@ -276,7 +290,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Theory] [InlineData("en-US", "4.2 H/m", PermeabilityUnit.HenryPerMeter, 4.2)] - public void Parse(string culture, string quantityString, PermeabilityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, PermeabilityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Permeability.Parse(quantityString); @@ -286,7 +300,7 @@ public void Parse(string culture, string quantityString, PermeabilityUnit expect [Theory] [InlineData("en-US", "4.2 H/m", PermeabilityUnit.HenryPerMeter, 4.2)] - public void TryParse(string culture, string quantityString, PermeabilityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, PermeabilityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Permeability.TryParse(quantityString, out Permeability parsed)); @@ -419,6 +433,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PermeabilityUnit var quantity = Permeability.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -442,32 +457,34 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(PermeabilityUnit un IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Permeability henrypermeter = Permeability.FromHenriesPerMeter(1); - AssertEx.EqualTolerance(1, Permeability.FromHenriesPerMeter(henrypermeter.HenriesPerMeter).HenriesPerMeter, HenriesPerMeterTolerance); + Permeability henrypermeter = Permeability.FromHenriesPerMeter(3); + Assert.Equal(3, Permeability.FromHenriesPerMeter(henrypermeter.HenriesPerMeter).HenriesPerMeter); } [Fact] public void ArithmeticOperators() { Permeability v = Permeability.FromHenriesPerMeter(1); - AssertEx.EqualTolerance(-1, -v.HenriesPerMeter, HenriesPerMeterTolerance); - AssertEx.EqualTolerance(2, (Permeability.FromHenriesPerMeter(3)-v).HenriesPerMeter, HenriesPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).HenriesPerMeter, HenriesPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).HenriesPerMeter, HenriesPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).HenriesPerMeter, HenriesPerMeterTolerance); - AssertEx.EqualTolerance(2, (Permeability.FromHenriesPerMeter(10)/5).HenriesPerMeter, HenriesPerMeterTolerance); - AssertEx.EqualTolerance(2, Permeability.FromHenriesPerMeter(10)/Permeability.FromHenriesPerMeter(5), HenriesPerMeterTolerance); + Assert.Equal(-1, -v.HenriesPerMeter); + Assert.Equal(2, (Permeability.FromHenriesPerMeter(3) - v).HenriesPerMeter); + Assert.Equal(2, (v + v).HenriesPerMeter); + Assert.Equal(10, (v * 10).HenriesPerMeter); + Assert.Equal(10, (10 * v).HenriesPerMeter); + Assert.Equal(2, (Permeability.FromHenriesPerMeter(10) / 5).HenriesPerMeter); + Assert.Equal(2, Permeability.FromHenriesPerMeter(10) / Permeability.FromHenriesPerMeter(5)); } [Fact] @@ -513,7 +530,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, PermeabilityUnit.HenryPerMeter, 1, PermeabilityUnit.HenryPerMeter, true)] // Same value and unit. [InlineData(1, PermeabilityUnit.HenryPerMeter, 2, PermeabilityUnit.HenryPerMeter, false)] // Different value. - [InlineData(2, PermeabilityUnit.HenryPerMeter, 1, PermeabilityUnit.HenryPerMeter, false)] // Different value and unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, PermeabilityUnit unitA, double valueB, PermeabilityUnit unitB, bool expectEqual) { var a = new Permeability(valueA, unitA); @@ -573,8 +589,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Permeability.FromHenriesPerMeter(firstValue); var otherQuantity = Permeability.FromHenriesPerMeter(secondValue); Permeability maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Permeability.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -593,7 +609,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -606,6 +622,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Permeability.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Permeability.Info.Units, Permeability.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Permeability.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -668,7 +696,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Permeability.FromHenriesPerMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Permeability), quantity.As(Permeability.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs index 3aa330660f..c46a13198d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PermittivityTestsBase.g.cs @@ -125,6 +125,20 @@ public void Permittivity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void PermittivityInfo_CreateWithCustomUnitInfos() + { + PermittivityUnit[] expectedUnits = [PermittivityUnit.FaradPerMeter]; + + Permittivity.PermittivityInfo quantityInfo = Permittivity.PermittivityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Permittivity", quantityInfo.Name); + Assert.Equal(Permittivity.Zero, quantityInfo.Zero); + Assert.Equal(Permittivity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void FaradPerMeterToPermittivityUnits() { @@ -276,7 +290,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Theory] [InlineData("en-US", "4.2 F/m", PermittivityUnit.FaradPerMeter, 4.2)] - public void Parse(string culture, string quantityString, PermittivityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, PermittivityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Permittivity.Parse(quantityString); @@ -286,7 +300,7 @@ public void Parse(string culture, string quantityString, PermittivityUnit expect [Theory] [InlineData("en-US", "4.2 F/m", PermittivityUnit.FaradPerMeter, 4.2)] - public void TryParse(string culture, string quantityString, PermittivityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, PermittivityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Permittivity.TryParse(quantityString, out Permittivity parsed)); @@ -419,6 +433,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PermittivityUnit var quantity = Permittivity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -442,32 +457,34 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(PermittivityUnit un IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Permittivity faradpermeter = Permittivity.FromFaradsPerMeter(1); - AssertEx.EqualTolerance(1, Permittivity.FromFaradsPerMeter(faradpermeter.FaradsPerMeter).FaradsPerMeter, FaradsPerMeterTolerance); + Permittivity faradpermeter = Permittivity.FromFaradsPerMeter(3); + Assert.Equal(3, Permittivity.FromFaradsPerMeter(faradpermeter.FaradsPerMeter).FaradsPerMeter); } [Fact] public void ArithmeticOperators() { Permittivity v = Permittivity.FromFaradsPerMeter(1); - AssertEx.EqualTolerance(-1, -v.FaradsPerMeter, FaradsPerMeterTolerance); - AssertEx.EqualTolerance(2, (Permittivity.FromFaradsPerMeter(3)-v).FaradsPerMeter, FaradsPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).FaradsPerMeter, FaradsPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).FaradsPerMeter, FaradsPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).FaradsPerMeter, FaradsPerMeterTolerance); - AssertEx.EqualTolerance(2, (Permittivity.FromFaradsPerMeter(10)/5).FaradsPerMeter, FaradsPerMeterTolerance); - AssertEx.EqualTolerance(2, Permittivity.FromFaradsPerMeter(10)/Permittivity.FromFaradsPerMeter(5), FaradsPerMeterTolerance); + Assert.Equal(-1, -v.FaradsPerMeter); + Assert.Equal(2, (Permittivity.FromFaradsPerMeter(3) - v).FaradsPerMeter); + Assert.Equal(2, (v + v).FaradsPerMeter); + Assert.Equal(10, (v * 10).FaradsPerMeter); + Assert.Equal(10, (10 * v).FaradsPerMeter); + Assert.Equal(2, (Permittivity.FromFaradsPerMeter(10) / 5).FaradsPerMeter); + Assert.Equal(2, Permittivity.FromFaradsPerMeter(10) / Permittivity.FromFaradsPerMeter(5)); } [Fact] @@ -513,7 +530,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, PermittivityUnit.FaradPerMeter, 1, PermittivityUnit.FaradPerMeter, true)] // Same value and unit. [InlineData(1, PermittivityUnit.FaradPerMeter, 2, PermittivityUnit.FaradPerMeter, false)] // Different value. - [InlineData(2, PermittivityUnit.FaradPerMeter, 1, PermittivityUnit.FaradPerMeter, false)] // Different value and unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, PermittivityUnit unitA, double valueB, PermittivityUnit unitB, bool expectEqual) { var a = new Permittivity(valueA, unitA); @@ -573,8 +589,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Permittivity.FromFaradsPerMeter(firstValue); var otherQuantity = Permittivity.FromFaradsPerMeter(secondValue); Permittivity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Permittivity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -593,7 +609,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -606,6 +622,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Permittivity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Permittivity.Info.Units, Permittivity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Permittivity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -668,7 +696,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Permittivity.FromFaradsPerMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Permittivity), quantity.As(Permittivity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PorousMediumPermeabilityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PorousMediumPermeabilityTestsBase.g.cs index b269407e13..74affff96e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PorousMediumPermeabilityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PorousMediumPermeabilityTestsBase.g.cs @@ -141,6 +141,20 @@ public void PorousMediumPermeability_QuantityInfo_ReturnsQuantityInfoDescribingQ Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void PorousMediumPermeabilityInfo_CreateWithCustomUnitInfos() + { + PorousMediumPermeabilityUnit[] expectedUnits = [PorousMediumPermeabilityUnit.SquareMeter]; + + PorousMediumPermeability.PorousMediumPermeabilityInfo quantityInfo = PorousMediumPermeability.PorousMediumPermeabilityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("PorousMediumPermeability", quantityInfo.Name); + Assert.Equal(PorousMediumPermeability.Zero, quantityInfo.Zero); + Assert.Equal(PorousMediumPermeability.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void SquareMeterToPorousMediumPermeabilityUnits() { @@ -304,7 +318,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 mD", PorousMediumPermeabilityUnit.Millidarcy, 4.2)] [InlineData("en-US", "4.2 cm²", PorousMediumPermeabilityUnit.SquareCentimeter, 4.2)] [InlineData("en-US", "4.2 m²", PorousMediumPermeabilityUnit.SquareMeter, 4.2)] - public void Parse(string culture, string quantityString, PorousMediumPermeabilityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, PorousMediumPermeabilityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = PorousMediumPermeability.Parse(quantityString); @@ -318,7 +332,7 @@ public void Parse(string culture, string quantityString, PorousMediumPermeabilit [InlineData("en-US", "4.2 mD", PorousMediumPermeabilityUnit.Millidarcy, 4.2)] [InlineData("en-US", "4.2 cm²", PorousMediumPermeabilityUnit.SquareCentimeter, 4.2)] [InlineData("en-US", "4.2 m²", PorousMediumPermeabilityUnit.SquareMeter, 4.2)] - public void TryParse(string culture, string quantityString, PorousMediumPermeabilityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, PorousMediumPermeabilityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(PorousMediumPermeability.TryParse(quantityString, out PorousMediumPermeability parsed)); @@ -487,6 +501,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PorousMediumPerm var quantity = PorousMediumPermeability.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -510,36 +525,38 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(PorousMediumPermeab IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - PorousMediumPermeability squaremeter = PorousMediumPermeability.FromSquareMeters(1); - AssertEx.EqualTolerance(1, PorousMediumPermeability.FromDarcys(squaremeter.Darcys).SquareMeters, DarcysTolerance); - AssertEx.EqualTolerance(1, PorousMediumPermeability.FromMicrodarcys(squaremeter.Microdarcys).SquareMeters, MicrodarcysTolerance); - AssertEx.EqualTolerance(1, PorousMediumPermeability.FromMillidarcys(squaremeter.Millidarcys).SquareMeters, MillidarcysTolerance); - AssertEx.EqualTolerance(1, PorousMediumPermeability.FromSquareCentimeters(squaremeter.SquareCentimeters).SquareMeters, SquareCentimetersTolerance); - AssertEx.EqualTolerance(1, PorousMediumPermeability.FromSquareMeters(squaremeter.SquareMeters).SquareMeters, SquareMetersTolerance); + PorousMediumPermeability squaremeter = PorousMediumPermeability.FromSquareMeters(3); + Assert.Equal(3, PorousMediumPermeability.FromDarcys(squaremeter.Darcys).SquareMeters); + Assert.Equal(3, PorousMediumPermeability.FromMicrodarcys(squaremeter.Microdarcys).SquareMeters); + Assert.Equal(3, PorousMediumPermeability.FromMillidarcys(squaremeter.Millidarcys).SquareMeters); + Assert.Equal(3, PorousMediumPermeability.FromSquareCentimeters(squaremeter.SquareCentimeters).SquareMeters); + Assert.Equal(3, PorousMediumPermeability.FromSquareMeters(squaremeter.SquareMeters).SquareMeters); } [Fact] public void ArithmeticOperators() { PorousMediumPermeability v = PorousMediumPermeability.FromSquareMeters(1); - AssertEx.EqualTolerance(-1, -v.SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(2, (PorousMediumPermeability.FromSquareMeters(3)-v).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(2, (v + v).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(10, (v*10).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(10, (10*v).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(2, (PorousMediumPermeability.FromSquareMeters(10)/5).SquareMeters, SquareMetersTolerance); - AssertEx.EqualTolerance(2, PorousMediumPermeability.FromSquareMeters(10)/PorousMediumPermeability.FromSquareMeters(5), SquareMetersTolerance); + Assert.Equal(-1, -v.SquareMeters); + Assert.Equal(2, (PorousMediumPermeability.FromSquareMeters(3) - v).SquareMeters); + Assert.Equal(2, (v + v).SquareMeters); + Assert.Equal(10, (v * 10).SquareMeters); + Assert.Equal(10, (10 * v).SquareMeters); + Assert.Equal(2, (PorousMediumPermeability.FromSquareMeters(10) / 5).SquareMeters); + Assert.Equal(2, PorousMediumPermeability.FromSquareMeters(10) / PorousMediumPermeability.FromSquareMeters(5)); } [Fact] @@ -585,8 +602,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, PorousMediumPermeabilityUnit.SquareMeter, 1, PorousMediumPermeabilityUnit.SquareMeter, true)] // Same value and unit. [InlineData(1, PorousMediumPermeabilityUnit.SquareMeter, 2, PorousMediumPermeabilityUnit.SquareMeter, false)] // Different value. - [InlineData(2, PorousMediumPermeabilityUnit.SquareMeter, 1, PorousMediumPermeabilityUnit.Darcy, false)] // Different value and unit. - [InlineData(1, PorousMediumPermeabilityUnit.SquareMeter, 1, PorousMediumPermeabilityUnit.Darcy, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, PorousMediumPermeabilityUnit unitA, double valueB, PorousMediumPermeabilityUnit unitB, bool expectEqual) { var a = new PorousMediumPermeability(valueA, unitA); @@ -646,8 +661,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = PorousMediumPermeability.FromSquareMeters(firstValue); var otherQuantity = PorousMediumPermeability.FromSquareMeters(secondValue); PorousMediumPermeability maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, PorousMediumPermeability.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -666,7 +681,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -679,6 +694,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(PorousMediumPermeability.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(PorousMediumPermeability.Info.Units, PorousMediumPermeability.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, PorousMediumPermeability.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -749,7 +776,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = PorousMediumPermeability.FromSquareMeters(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(PorousMediumPermeability), quantity.As(PorousMediumPermeability.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs index aeac9f35fa..8770efe20b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerDensityTestsBase.g.cs @@ -297,6 +297,20 @@ public void PowerDensity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void PowerDensityInfo_CreateWithCustomUnitInfos() + { + PowerDensityUnit[] expectedUnits = [PowerDensityUnit.WattPerCubicMeter]; + + PowerDensity.PowerDensityInfo quantityInfo = PowerDensity.PowerDensityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("PowerDensity", quantityInfo.Name); + Assert.Equal(PowerDensity.Zero, quantityInfo.Zero); + Assert.Equal(PowerDensity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void WattPerCubicMeterToPowerDensityUnits() { @@ -577,7 +591,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 W/in³", PowerDensityUnit.WattPerCubicInch, 4.2)] [InlineData("en-US", "4.2 W/m³", PowerDensityUnit.WattPerCubicMeter, 4.2)] [InlineData("en-US", "4.2 W/l", PowerDensityUnit.WattPerLiter, 4.2)] - public void Parse(string culture, string quantityString, PowerDensityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, PowerDensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = PowerDensity.Parse(quantityString); @@ -630,7 +644,7 @@ public void Parse(string culture, string quantityString, PowerDensityUnit expect [InlineData("en-US", "4.2 W/in³", PowerDensityUnit.WattPerCubicInch, 4.2)] [InlineData("en-US", "4.2 W/m³", PowerDensityUnit.WattPerCubicMeter, 4.2)] [InlineData("en-US", "4.2 W/l", PowerDensityUnit.WattPerLiter, 4.2)] - public void TryParse(string culture, string quantityString, PowerDensityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, PowerDensityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(PowerDensity.TryParse(quantityString, out PowerDensity parsed)); @@ -1150,6 +1164,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PowerDensityUnit var quantity = PowerDensity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -1173,75 +1188,77 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(PowerDensityUnit un IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - PowerDensity wattpercubicmeter = PowerDensity.FromWattsPerCubicMeter(1); - AssertEx.EqualTolerance(1, PowerDensity.FromDecawattsPerCubicFoot(wattpercubicmeter.DecawattsPerCubicFoot).WattsPerCubicMeter, DecawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromDecawattsPerCubicInch(wattpercubicmeter.DecawattsPerCubicInch).WattsPerCubicMeter, DecawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromDecawattsPerCubicMeter(wattpercubicmeter.DecawattsPerCubicMeter).WattsPerCubicMeter, DecawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromDecawattsPerLiter(wattpercubicmeter.DecawattsPerLiter).WattsPerCubicMeter, DecawattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromDeciwattsPerCubicFoot(wattpercubicmeter.DeciwattsPerCubicFoot).WattsPerCubicMeter, DeciwattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromDeciwattsPerCubicInch(wattpercubicmeter.DeciwattsPerCubicInch).WattsPerCubicMeter, DeciwattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromDeciwattsPerCubicMeter(wattpercubicmeter.DeciwattsPerCubicMeter).WattsPerCubicMeter, DeciwattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromDeciwattsPerLiter(wattpercubicmeter.DeciwattsPerLiter).WattsPerCubicMeter, DeciwattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromGigawattsPerCubicFoot(wattpercubicmeter.GigawattsPerCubicFoot).WattsPerCubicMeter, GigawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromGigawattsPerCubicInch(wattpercubicmeter.GigawattsPerCubicInch).WattsPerCubicMeter, GigawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromGigawattsPerCubicMeter(wattpercubicmeter.GigawattsPerCubicMeter).WattsPerCubicMeter, GigawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromGigawattsPerLiter(wattpercubicmeter.GigawattsPerLiter).WattsPerCubicMeter, GigawattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromKilowattsPerCubicFoot(wattpercubicmeter.KilowattsPerCubicFoot).WattsPerCubicMeter, KilowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromKilowattsPerCubicInch(wattpercubicmeter.KilowattsPerCubicInch).WattsPerCubicMeter, KilowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromKilowattsPerCubicMeter(wattpercubicmeter.KilowattsPerCubicMeter).WattsPerCubicMeter, KilowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromKilowattsPerLiter(wattpercubicmeter.KilowattsPerLiter).WattsPerCubicMeter, KilowattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMegawattsPerCubicFoot(wattpercubicmeter.MegawattsPerCubicFoot).WattsPerCubicMeter, MegawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMegawattsPerCubicInch(wattpercubicmeter.MegawattsPerCubicInch).WattsPerCubicMeter, MegawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMegawattsPerCubicMeter(wattpercubicmeter.MegawattsPerCubicMeter).WattsPerCubicMeter, MegawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMegawattsPerLiter(wattpercubicmeter.MegawattsPerLiter).WattsPerCubicMeter, MegawattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMicrowattsPerCubicFoot(wattpercubicmeter.MicrowattsPerCubicFoot).WattsPerCubicMeter, MicrowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMicrowattsPerCubicInch(wattpercubicmeter.MicrowattsPerCubicInch).WattsPerCubicMeter, MicrowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMicrowattsPerCubicMeter(wattpercubicmeter.MicrowattsPerCubicMeter).WattsPerCubicMeter, MicrowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMicrowattsPerLiter(wattpercubicmeter.MicrowattsPerLiter).WattsPerCubicMeter, MicrowattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMilliwattsPerCubicFoot(wattpercubicmeter.MilliwattsPerCubicFoot).WattsPerCubicMeter, MilliwattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMilliwattsPerCubicInch(wattpercubicmeter.MilliwattsPerCubicInch).WattsPerCubicMeter, MilliwattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMilliwattsPerCubicMeter(wattpercubicmeter.MilliwattsPerCubicMeter).WattsPerCubicMeter, MilliwattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromMilliwattsPerLiter(wattpercubicmeter.MilliwattsPerLiter).WattsPerCubicMeter, MilliwattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromNanowattsPerCubicFoot(wattpercubicmeter.NanowattsPerCubicFoot).WattsPerCubicMeter, NanowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromNanowattsPerCubicInch(wattpercubicmeter.NanowattsPerCubicInch).WattsPerCubicMeter, NanowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromNanowattsPerCubicMeter(wattpercubicmeter.NanowattsPerCubicMeter).WattsPerCubicMeter, NanowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromNanowattsPerLiter(wattpercubicmeter.NanowattsPerLiter).WattsPerCubicMeter, NanowattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromPicowattsPerCubicFoot(wattpercubicmeter.PicowattsPerCubicFoot).WattsPerCubicMeter, PicowattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromPicowattsPerCubicInch(wattpercubicmeter.PicowattsPerCubicInch).WattsPerCubicMeter, PicowattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromPicowattsPerCubicMeter(wattpercubicmeter.PicowattsPerCubicMeter).WattsPerCubicMeter, PicowattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromPicowattsPerLiter(wattpercubicmeter.PicowattsPerLiter).WattsPerCubicMeter, PicowattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromTerawattsPerCubicFoot(wattpercubicmeter.TerawattsPerCubicFoot).WattsPerCubicMeter, TerawattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromTerawattsPerCubicInch(wattpercubicmeter.TerawattsPerCubicInch).WattsPerCubicMeter, TerawattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromTerawattsPerCubicMeter(wattpercubicmeter.TerawattsPerCubicMeter).WattsPerCubicMeter, TerawattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromTerawattsPerLiter(wattpercubicmeter.TerawattsPerLiter).WattsPerCubicMeter, TerawattsPerLiterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromWattsPerCubicFoot(wattpercubicmeter.WattsPerCubicFoot).WattsPerCubicMeter, WattsPerCubicFootTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromWattsPerCubicInch(wattpercubicmeter.WattsPerCubicInch).WattsPerCubicMeter, WattsPerCubicInchTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromWattsPerCubicMeter(wattpercubicmeter.WattsPerCubicMeter).WattsPerCubicMeter, WattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, PowerDensity.FromWattsPerLiter(wattpercubicmeter.WattsPerLiter).WattsPerCubicMeter, WattsPerLiterTolerance); + PowerDensity wattpercubicmeter = PowerDensity.FromWattsPerCubicMeter(3); + Assert.Equal(3, PowerDensity.FromDecawattsPerCubicFoot(wattpercubicmeter.DecawattsPerCubicFoot).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromDecawattsPerCubicInch(wattpercubicmeter.DecawattsPerCubicInch).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromDecawattsPerCubicMeter(wattpercubicmeter.DecawattsPerCubicMeter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromDecawattsPerLiter(wattpercubicmeter.DecawattsPerLiter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromDeciwattsPerCubicFoot(wattpercubicmeter.DeciwattsPerCubicFoot).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromDeciwattsPerCubicInch(wattpercubicmeter.DeciwattsPerCubicInch).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromDeciwattsPerCubicMeter(wattpercubicmeter.DeciwattsPerCubicMeter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromDeciwattsPerLiter(wattpercubicmeter.DeciwattsPerLiter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromGigawattsPerCubicFoot(wattpercubicmeter.GigawattsPerCubicFoot).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromGigawattsPerCubicInch(wattpercubicmeter.GigawattsPerCubicInch).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromGigawattsPerCubicMeter(wattpercubicmeter.GigawattsPerCubicMeter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromGigawattsPerLiter(wattpercubicmeter.GigawattsPerLiter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromKilowattsPerCubicFoot(wattpercubicmeter.KilowattsPerCubicFoot).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromKilowattsPerCubicInch(wattpercubicmeter.KilowattsPerCubicInch).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromKilowattsPerCubicMeter(wattpercubicmeter.KilowattsPerCubicMeter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromKilowattsPerLiter(wattpercubicmeter.KilowattsPerLiter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromMegawattsPerCubicFoot(wattpercubicmeter.MegawattsPerCubicFoot).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromMegawattsPerCubicInch(wattpercubicmeter.MegawattsPerCubicInch).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromMegawattsPerCubicMeter(wattpercubicmeter.MegawattsPerCubicMeter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromMegawattsPerLiter(wattpercubicmeter.MegawattsPerLiter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromMicrowattsPerCubicFoot(wattpercubicmeter.MicrowattsPerCubicFoot).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromMicrowattsPerCubicInch(wattpercubicmeter.MicrowattsPerCubicInch).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromMicrowattsPerCubicMeter(wattpercubicmeter.MicrowattsPerCubicMeter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromMicrowattsPerLiter(wattpercubicmeter.MicrowattsPerLiter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromMilliwattsPerCubicFoot(wattpercubicmeter.MilliwattsPerCubicFoot).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromMilliwattsPerCubicInch(wattpercubicmeter.MilliwattsPerCubicInch).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromMilliwattsPerCubicMeter(wattpercubicmeter.MilliwattsPerCubicMeter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromMilliwattsPerLiter(wattpercubicmeter.MilliwattsPerLiter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromNanowattsPerCubicFoot(wattpercubicmeter.NanowattsPerCubicFoot).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromNanowattsPerCubicInch(wattpercubicmeter.NanowattsPerCubicInch).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromNanowattsPerCubicMeter(wattpercubicmeter.NanowattsPerCubicMeter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromNanowattsPerLiter(wattpercubicmeter.NanowattsPerLiter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromPicowattsPerCubicFoot(wattpercubicmeter.PicowattsPerCubicFoot).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromPicowattsPerCubicInch(wattpercubicmeter.PicowattsPerCubicInch).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromPicowattsPerCubicMeter(wattpercubicmeter.PicowattsPerCubicMeter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromPicowattsPerLiter(wattpercubicmeter.PicowattsPerLiter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromTerawattsPerCubicFoot(wattpercubicmeter.TerawattsPerCubicFoot).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromTerawattsPerCubicInch(wattpercubicmeter.TerawattsPerCubicInch).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromTerawattsPerCubicMeter(wattpercubicmeter.TerawattsPerCubicMeter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromTerawattsPerLiter(wattpercubicmeter.TerawattsPerLiter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromWattsPerCubicFoot(wattpercubicmeter.WattsPerCubicFoot).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromWattsPerCubicInch(wattpercubicmeter.WattsPerCubicInch).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromWattsPerCubicMeter(wattpercubicmeter.WattsPerCubicMeter).WattsPerCubicMeter); + Assert.Equal(3, PowerDensity.FromWattsPerLiter(wattpercubicmeter.WattsPerLiter).WattsPerCubicMeter); } [Fact] public void ArithmeticOperators() { PowerDensity v = PowerDensity.FromWattsPerCubicMeter(1); - AssertEx.EqualTolerance(-1, -v.WattsPerCubicMeter, WattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (PowerDensity.FromWattsPerCubicMeter(3)-v).WattsPerCubicMeter, WattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).WattsPerCubicMeter, WattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).WattsPerCubicMeter, WattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).WattsPerCubicMeter, WattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (PowerDensity.FromWattsPerCubicMeter(10)/5).WattsPerCubicMeter, WattsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, PowerDensity.FromWattsPerCubicMeter(10)/PowerDensity.FromWattsPerCubicMeter(5), WattsPerCubicMeterTolerance); + Assert.Equal(-1, -v.WattsPerCubicMeter); + Assert.Equal(2, (PowerDensity.FromWattsPerCubicMeter(3) - v).WattsPerCubicMeter); + Assert.Equal(2, (v + v).WattsPerCubicMeter); + Assert.Equal(10, (v * 10).WattsPerCubicMeter); + Assert.Equal(10, (10 * v).WattsPerCubicMeter); + Assert.Equal(2, (PowerDensity.FromWattsPerCubicMeter(10) / 5).WattsPerCubicMeter); + Assert.Equal(2, PowerDensity.FromWattsPerCubicMeter(10) / PowerDensity.FromWattsPerCubicMeter(5)); } [Fact] @@ -1287,8 +1304,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, PowerDensityUnit.WattPerCubicMeter, 1, PowerDensityUnit.WattPerCubicMeter, true)] // Same value and unit. [InlineData(1, PowerDensityUnit.WattPerCubicMeter, 2, PowerDensityUnit.WattPerCubicMeter, false)] // Different value. - [InlineData(2, PowerDensityUnit.WattPerCubicMeter, 1, PowerDensityUnit.DecawattPerCubicFoot, false)] // Different value and unit. - [InlineData(1, PowerDensityUnit.WattPerCubicMeter, 1, PowerDensityUnit.DecawattPerCubicFoot, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, PowerDensityUnit unitA, double valueB, PowerDensityUnit unitB, bool expectEqual) { var a = new PowerDensity(valueA, unitA); @@ -1348,8 +1363,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = PowerDensity.FromWattsPerCubicMeter(firstValue); var otherQuantity = PowerDensity.FromWattsPerCubicMeter(secondValue); PowerDensity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, PowerDensity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1368,7 +1383,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1381,6 +1396,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(PowerDensity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(PowerDensity.Info.Units, PowerDensity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, PowerDensity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1529,7 +1556,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = PowerDensity.FromWattsPerCubicMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(PowerDensity), quantity.As(PowerDensity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs index 5814633c88..7583b1a7a0 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerRatioTestsBase.g.cs @@ -108,6 +108,20 @@ public void PowerRatio_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void PowerRatioInfo_CreateWithCustomUnitInfos() + { + PowerRatioUnit[] expectedUnits = [PowerRatioUnit.DecibelWatt]; + + PowerRatio.PowerRatioInfo quantityInfo = PowerRatio.PowerRatioInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("PowerRatio", quantityInfo.Name); + Assert.Equal(PowerRatio.Zero, quantityInfo.Zero); + Assert.Equal(PowerRatio.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void DecibelWattToPowerRatioUnits() { @@ -224,7 +238,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() [InlineData("en-US", "4.2 dBmW", PowerRatioUnit.DecibelMilliwatt, 4.2)] [InlineData("en-US", "4.2 dBm", PowerRatioUnit.DecibelMilliwatt, 4.2)] [InlineData("en-US", "4.2 dBW", PowerRatioUnit.DecibelWatt, 4.2)] - public void Parse(string culture, string quantityString, PowerRatioUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, PowerRatioUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = PowerRatio.Parse(quantityString); @@ -236,7 +250,7 @@ public void Parse(string culture, string quantityString, PowerRatioUnit expected [InlineData("en-US", "4.2 dBmW", PowerRatioUnit.DecibelMilliwatt, 4.2)] [InlineData("en-US", "4.2 dBm", PowerRatioUnit.DecibelMilliwatt, 4.2)] [InlineData("en-US", "4.2 dBW", PowerRatioUnit.DecibelWatt, 4.2)] - public void TryParse(string culture, string quantityString, PowerRatioUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, PowerRatioUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(PowerRatio.TryParse(quantityString, out PowerRatio parsed)); @@ -386,6 +400,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PowerRatioUnit u var quantity = PowerRatio.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -409,33 +424,35 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(PowerRatioUnit unit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - PowerRatio decibelwatt = PowerRatio.FromDecibelWatts(1); - AssertEx.EqualTolerance(1, PowerRatio.FromDecibelMilliwatts(decibelwatt.DecibelMilliwatts).DecibelWatts, DecibelMilliwattsTolerance); - AssertEx.EqualTolerance(1, PowerRatio.FromDecibelWatts(decibelwatt.DecibelWatts).DecibelWatts, DecibelWattsTolerance); + PowerRatio decibelwatt = PowerRatio.FromDecibelWatts(3); + Assert.Equal(3, PowerRatio.FromDecibelMilliwatts(decibelwatt.DecibelMilliwatts).DecibelWatts); + Assert.Equal(3, PowerRatio.FromDecibelWatts(decibelwatt.DecibelWatts).DecibelWatts); } [Fact] public void LogarithmicArithmeticOperators() { PowerRatio v = PowerRatio.FromDecibelWatts(40); - AssertEx.EqualTolerance(-40, -v.DecibelWatts, DecibelWattsTolerance); + Assert.Equal(-40, -v.DecibelWatts); AssertLogarithmicAddition(); AssertLogarithmicSubtraction(); - AssertEx.EqualTolerance(50, (v*10).DecibelWatts, DecibelWattsTolerance); - AssertEx.EqualTolerance(50, (10*v).DecibelWatts, DecibelWattsTolerance); - AssertEx.EqualTolerance(35, (v/5).DecibelWatts, DecibelWattsTolerance); - AssertEx.EqualTolerance(35, v/PowerRatio.FromDecibelWatts(5), DecibelWattsTolerance); + Assert.Equal(50, (v * 10).DecibelWatts); + Assert.Equal(50, (10 * v).DecibelWatts); + Assert.Equal(35, (v / 5).DecibelWatts); + Assert.Equal(35, v / PowerRatio.FromDecibelWatts(5)); } protected abstract void AssertLogarithmicAddition(); @@ -485,8 +502,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, PowerRatioUnit.DecibelWatt, 1, PowerRatioUnit.DecibelWatt, true)] // Same value and unit. [InlineData(1, PowerRatioUnit.DecibelWatt, 2, PowerRatioUnit.DecibelWatt, false)] // Different value. - [InlineData(2, PowerRatioUnit.DecibelWatt, 1, PowerRatioUnit.DecibelMilliwatt, false)] // Different value and unit. - [InlineData(1, PowerRatioUnit.DecibelWatt, 1, PowerRatioUnit.DecibelMilliwatt, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, PowerRatioUnit unitA, double valueB, PowerRatioUnit unitB, bool expectEqual) { var a = new PowerRatio(valueA, unitA); @@ -546,8 +561,8 @@ public void Equals_Logarithmic_WithTolerance(double firstValue, double secondVal var quantity = PowerRatio.FromDecibelWatts(firstValue); var otherQuantity = PowerRatio.FromDecibelWatts(secondValue); PowerRatio maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, PowerRatio.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, largerTolerance)); @@ -568,7 +583,7 @@ public void Equals_Logarithmic_WithNegativeTolerance_DoesNotThrowArgumentOutOfRa [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -581,6 +596,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(PowerRatio.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(PowerRatio.Info.Units, PowerRatio.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, PowerRatio.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -645,7 +672,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = PowerRatio.FromDecibelWatts(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(PowerRatio), quantity.As(PowerRatio.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs index 4743c9bbf4..9b0800f1d2 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PowerTestsBase.g.cs @@ -229,6 +229,20 @@ public void Power_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void PowerInfo_CreateWithCustomUnitInfos() + { + PowerUnit[] expectedUnits = [PowerUnit.Watt]; + + Power.PowerInfo quantityInfo = Power.PowerInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Power", quantityInfo.Name); + Assert.Equal(Power.Zero, quantityInfo.Zero); + Assert.Equal(Power.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void WattToPowerUnits() { @@ -461,7 +475,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 TW", PowerUnit.Terawatt, 4.2)] [InlineData("en-US", "4.2 TR", PowerUnit.TonOfRefrigeration, 4.2)] [InlineData("en-US", "4.2 W", PowerUnit.Watt, 4.2)] - public void Parse(string culture, string quantityString, PowerUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, PowerUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Power.Parse(quantityString); @@ -500,7 +514,7 @@ public void Parse(string culture, string quantityString, PowerUnit expectedUnit, [InlineData("en-US", "4.2 TW", PowerUnit.Terawatt, 4.2)] [InlineData("en-US", "4.2 TR", PowerUnit.TonOfRefrigeration, 4.2)] [InlineData("en-US", "4.2 W", PowerUnit.Watt, 4.2)] - public void TryParse(string culture, string quantityString, PowerUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, PowerUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Power.TryParse(quantityString, out Power parsed)); @@ -891,6 +905,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PowerUnit unit) var quantity = Power.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -914,58 +929,60 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(PowerUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Power watt = Power.FromWatts(1); - AssertEx.EqualTolerance(1, Power.FromBoilerHorsepower(watt.BoilerHorsepower).Watts, BoilerHorsepowerTolerance); - AssertEx.EqualTolerance(1, Power.FromBritishThermalUnitsPerHour(watt.BritishThermalUnitsPerHour).Watts, BritishThermalUnitsPerHourTolerance); - AssertEx.EqualTolerance(1, Power.FromDecawatts(watt.Decawatts).Watts, DecawattsTolerance); - AssertEx.EqualTolerance(1, Power.FromDeciwatts(watt.Deciwatts).Watts, DeciwattsTolerance); - AssertEx.EqualTolerance(1, Power.FromElectricalHorsepower(watt.ElectricalHorsepower).Watts, ElectricalHorsepowerTolerance); - AssertEx.EqualTolerance(1, Power.FromFemtowatts(watt.Femtowatts).Watts, FemtowattsTolerance); - AssertEx.EqualTolerance(1, Power.FromGigajoulesPerHour(watt.GigajoulesPerHour).Watts, GigajoulesPerHourTolerance); - AssertEx.EqualTolerance(1, Power.FromGigawatts(watt.Gigawatts).Watts, GigawattsTolerance); - AssertEx.EqualTolerance(1, Power.FromHydraulicHorsepower(watt.HydraulicHorsepower).Watts, HydraulicHorsepowerTolerance); - AssertEx.EqualTolerance(1, Power.FromJoulesPerHour(watt.JoulesPerHour).Watts, JoulesPerHourTolerance); - AssertEx.EqualTolerance(1, Power.FromKilobritishThermalUnitsPerHour(watt.KilobritishThermalUnitsPerHour).Watts, KilobritishThermalUnitsPerHourTolerance); - AssertEx.EqualTolerance(1, Power.FromKilojoulesPerHour(watt.KilojoulesPerHour).Watts, KilojoulesPerHourTolerance); - AssertEx.EqualTolerance(1, Power.FromKilowatts(watt.Kilowatts).Watts, KilowattsTolerance); - AssertEx.EqualTolerance(1, Power.FromMechanicalHorsepower(watt.MechanicalHorsepower).Watts, MechanicalHorsepowerTolerance); - AssertEx.EqualTolerance(1, Power.FromMegabritishThermalUnitsPerHour(watt.MegabritishThermalUnitsPerHour).Watts, MegabritishThermalUnitsPerHourTolerance); - AssertEx.EqualTolerance(1, Power.FromMegajoulesPerHour(watt.MegajoulesPerHour).Watts, MegajoulesPerHourTolerance); - AssertEx.EqualTolerance(1, Power.FromMegawatts(watt.Megawatts).Watts, MegawattsTolerance); - AssertEx.EqualTolerance(1, Power.FromMetricHorsepower(watt.MetricHorsepower).Watts, MetricHorsepowerTolerance); - AssertEx.EqualTolerance(1, Power.FromMicrowatts(watt.Microwatts).Watts, MicrowattsTolerance); - AssertEx.EqualTolerance(1, Power.FromMillijoulesPerHour(watt.MillijoulesPerHour).Watts, MillijoulesPerHourTolerance); - AssertEx.EqualTolerance(1, Power.FromMilliwatts(watt.Milliwatts).Watts, MilliwattsTolerance); - AssertEx.EqualTolerance(1, Power.FromNanowatts(watt.Nanowatts).Watts, NanowattsTolerance); - AssertEx.EqualTolerance(1, Power.FromPetawatts(watt.Petawatts).Watts, PetawattsTolerance); - AssertEx.EqualTolerance(1, Power.FromPicowatts(watt.Picowatts).Watts, PicowattsTolerance); - AssertEx.EqualTolerance(1, Power.FromTerawatts(watt.Terawatts).Watts, TerawattsTolerance); - AssertEx.EqualTolerance(1, Power.FromTonsOfRefrigeration(watt.TonsOfRefrigeration).Watts, TonsOfRefrigerationTolerance); - AssertEx.EqualTolerance(1, Power.FromWatts(watt.Watts).Watts, WattsTolerance); + Power watt = Power.FromWatts(3); + Assert.Equal(3, Power.FromBoilerHorsepower(watt.BoilerHorsepower).Watts); + Assert.Equal(3, Power.FromBritishThermalUnitsPerHour(watt.BritishThermalUnitsPerHour).Watts); + Assert.Equal(3, Power.FromDecawatts(watt.Decawatts).Watts); + Assert.Equal(3, Power.FromDeciwatts(watt.Deciwatts).Watts); + Assert.Equal(3, Power.FromElectricalHorsepower(watt.ElectricalHorsepower).Watts); + Assert.Equal(3, Power.FromFemtowatts(watt.Femtowatts).Watts); + Assert.Equal(3, Power.FromGigajoulesPerHour(watt.GigajoulesPerHour).Watts); + Assert.Equal(3, Power.FromGigawatts(watt.Gigawatts).Watts); + Assert.Equal(3, Power.FromHydraulicHorsepower(watt.HydraulicHorsepower).Watts); + Assert.Equal(3, Power.FromJoulesPerHour(watt.JoulesPerHour).Watts); + Assert.Equal(3, Power.FromKilobritishThermalUnitsPerHour(watt.KilobritishThermalUnitsPerHour).Watts); + Assert.Equal(3, Power.FromKilojoulesPerHour(watt.KilojoulesPerHour).Watts); + Assert.Equal(3, Power.FromKilowatts(watt.Kilowatts).Watts); + Assert.Equal(3, Power.FromMechanicalHorsepower(watt.MechanicalHorsepower).Watts); + Assert.Equal(3, Power.FromMegabritishThermalUnitsPerHour(watt.MegabritishThermalUnitsPerHour).Watts); + Assert.Equal(3, Power.FromMegajoulesPerHour(watt.MegajoulesPerHour).Watts); + Assert.Equal(3, Power.FromMegawatts(watt.Megawatts).Watts); + Assert.Equal(3, Power.FromMetricHorsepower(watt.MetricHorsepower).Watts); + Assert.Equal(3, Power.FromMicrowatts(watt.Microwatts).Watts); + Assert.Equal(3, Power.FromMillijoulesPerHour(watt.MillijoulesPerHour).Watts); + Assert.Equal(3, Power.FromMilliwatts(watt.Milliwatts).Watts); + Assert.Equal(3, Power.FromNanowatts(watt.Nanowatts).Watts); + Assert.Equal(3, Power.FromPetawatts(watt.Petawatts).Watts); + Assert.Equal(3, Power.FromPicowatts(watt.Picowatts).Watts); + Assert.Equal(3, Power.FromTerawatts(watt.Terawatts).Watts); + Assert.Equal(3, Power.FromTonsOfRefrigeration(watt.TonsOfRefrigeration).Watts); + Assert.Equal(3, Power.FromWatts(watt.Watts).Watts); } [Fact] public void ArithmeticOperators() { Power v = Power.FromWatts(1); - AssertEx.EqualTolerance(-1, -v.Watts, WattsTolerance); - AssertEx.EqualTolerance(2, (Power.FromWatts(3)-v).Watts, WattsTolerance); - AssertEx.EqualTolerance(2, (v + v).Watts, WattsTolerance); - AssertEx.EqualTolerance(10, (v*10).Watts, WattsTolerance); - AssertEx.EqualTolerance(10, (10*v).Watts, WattsTolerance); - AssertEx.EqualTolerance(2, (Power.FromWatts(10)/5).Watts, WattsTolerance); - AssertEx.EqualTolerance(2, Power.FromWatts(10)/Power.FromWatts(5), WattsTolerance); + Assert.Equal(-1, -v.Watts); + Assert.Equal(2, (Power.FromWatts(3) - v).Watts); + Assert.Equal(2, (v + v).Watts); + Assert.Equal(10, (v * 10).Watts); + Assert.Equal(10, (10 * v).Watts); + Assert.Equal(2, (Power.FromWatts(10) / 5).Watts); + Assert.Equal(2, Power.FromWatts(10) / Power.FromWatts(5)); } [Fact] @@ -1011,8 +1028,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, PowerUnit.Watt, 1, PowerUnit.Watt, true)] // Same value and unit. [InlineData(1, PowerUnit.Watt, 2, PowerUnit.Watt, false)] // Different value. - [InlineData(2, PowerUnit.Watt, 1, PowerUnit.BoilerHorsepower, false)] // Different value and unit. - [InlineData(1, PowerUnit.Watt, 1, PowerUnit.BoilerHorsepower, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, PowerUnit unitA, double valueB, PowerUnit unitB, bool expectEqual) { var a = new Power(valueA, unitA); @@ -1072,8 +1087,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Power.FromWatts(firstValue); var otherQuantity = Power.FromWatts(secondValue); Power maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Power.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1092,7 +1107,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1105,6 +1120,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Power.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Power.Info.Units, Power.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Power.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1219,7 +1246,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Power.FromWatts(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Power), quantity.As(Power.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs index c7cdcf8619..b24ddf0325 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureChangeRateTestsBase.g.cs @@ -193,6 +193,20 @@ public void PressureChangeRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantit Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void PressureChangeRateInfo_CreateWithCustomUnitInfos() + { + PressureChangeRateUnit[] expectedUnits = [PressureChangeRateUnit.PascalPerSecond]; + + PressureChangeRate.PressureChangeRateInfo quantityInfo = PressureChangeRate.PressureChangeRateInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("PressureChangeRate", quantityInfo.Name); + Assert.Equal(PressureChangeRate.Zero, quantityInfo.Zero); + Assert.Equal(PressureChangeRate.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void PascalPerSecondToPressureChangeRateUnits() { @@ -425,7 +439,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 lb/in²/мин", PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, 4.2)] [InlineData("ru-RU", "4,2 psi/с", PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, 4.2)] [InlineData("ru-RU", "4,2 lb/in²/с", PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, 4.2)] - public void Parse(string culture, string quantityString, PressureChangeRateUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, PressureChangeRateUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = PressureChangeRate.Parse(quantityString); @@ -482,7 +496,7 @@ public void Parse(string culture, string quantityString, PressureChangeRateUnit [InlineData("ru-RU", "4,2 lb/in²/мин", PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, 4.2)] [InlineData("ru-RU", "4,2 psi/с", PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, 4.2)] [InlineData("ru-RU", "4,2 lb/in²/с", PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, 4.2)] - public void TryParse(string culture, string quantityString, PressureChangeRateUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, PressureChangeRateUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(PressureChangeRate.TryParse(quantityString, out PressureChangeRate parsed)); @@ -930,6 +944,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PressureChangeRa var quantity = PressureChangeRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -953,49 +968,51 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(PressureChangeRateU IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - PressureChangeRate pascalpersecond = PressureChangeRate.FromPascalsPerSecond(1); - AssertEx.EqualTolerance(1, PressureChangeRate.FromAtmospheresPerSecond(pascalpersecond.AtmospheresPerSecond).PascalsPerSecond, AtmospheresPerSecondTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromBarsPerMinute(pascalpersecond.BarsPerMinute).PascalsPerSecond, BarsPerMinuteTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromBarsPerSecond(pascalpersecond.BarsPerSecond).PascalsPerSecond, BarsPerSecondTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromKilopascalsPerMinute(pascalpersecond.KilopascalsPerMinute).PascalsPerSecond, KilopascalsPerMinuteTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromKilopascalsPerSecond(pascalpersecond.KilopascalsPerSecond).PascalsPerSecond, KilopascalsPerSecondTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromKilopoundsForcePerSquareInchPerMinute(pascalpersecond.KilopoundsForcePerSquareInchPerMinute).PascalsPerSecond, KilopoundsForcePerSquareInchPerMinuteTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromKilopoundsForcePerSquareInchPerSecond(pascalpersecond.KilopoundsForcePerSquareInchPerSecond).PascalsPerSecond, KilopoundsForcePerSquareInchPerSecondTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromMegapascalsPerMinute(pascalpersecond.MegapascalsPerMinute).PascalsPerSecond, MegapascalsPerMinuteTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromMegapascalsPerSecond(pascalpersecond.MegapascalsPerSecond).PascalsPerSecond, MegapascalsPerSecondTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromMegapoundsForcePerSquareInchPerMinute(pascalpersecond.MegapoundsForcePerSquareInchPerMinute).PascalsPerSecond, MegapoundsForcePerSquareInchPerMinuteTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromMegapoundsForcePerSquareInchPerSecond(pascalpersecond.MegapoundsForcePerSquareInchPerSecond).PascalsPerSecond, MegapoundsForcePerSquareInchPerSecondTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromMillibarsPerMinute(pascalpersecond.MillibarsPerMinute).PascalsPerSecond, MillibarsPerMinuteTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromMillibarsPerSecond(pascalpersecond.MillibarsPerSecond).PascalsPerSecond, MillibarsPerSecondTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromMillimetersOfMercuryPerSecond(pascalpersecond.MillimetersOfMercuryPerSecond).PascalsPerSecond, MillimetersOfMercuryPerSecondTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromPascalsPerMinute(pascalpersecond.PascalsPerMinute).PascalsPerSecond, PascalsPerMinuteTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromPascalsPerSecond(pascalpersecond.PascalsPerSecond).PascalsPerSecond, PascalsPerSecondTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromPoundsForcePerSquareInchPerMinute(pascalpersecond.PoundsForcePerSquareInchPerMinute).PascalsPerSecond, PoundsForcePerSquareInchPerMinuteTolerance); - AssertEx.EqualTolerance(1, PressureChangeRate.FromPoundsForcePerSquareInchPerSecond(pascalpersecond.PoundsForcePerSquareInchPerSecond).PascalsPerSecond, PoundsForcePerSquareInchPerSecondTolerance); + PressureChangeRate pascalpersecond = PressureChangeRate.FromPascalsPerSecond(3); + Assert.Equal(3, PressureChangeRate.FromAtmospheresPerSecond(pascalpersecond.AtmospheresPerSecond).PascalsPerSecond); + Assert.Equal(3, PressureChangeRate.FromBarsPerMinute(pascalpersecond.BarsPerMinute).PascalsPerSecond); + Assert.Equal(3, PressureChangeRate.FromBarsPerSecond(pascalpersecond.BarsPerSecond).PascalsPerSecond); + Assert.Equal(3, PressureChangeRate.FromKilopascalsPerMinute(pascalpersecond.KilopascalsPerMinute).PascalsPerSecond); + Assert.Equal(3, PressureChangeRate.FromKilopascalsPerSecond(pascalpersecond.KilopascalsPerSecond).PascalsPerSecond); + Assert.Equal(3, PressureChangeRate.FromKilopoundsForcePerSquareInchPerMinute(pascalpersecond.KilopoundsForcePerSquareInchPerMinute).PascalsPerSecond); + Assert.Equal(3, PressureChangeRate.FromKilopoundsForcePerSquareInchPerSecond(pascalpersecond.KilopoundsForcePerSquareInchPerSecond).PascalsPerSecond); + Assert.Equal(3, PressureChangeRate.FromMegapascalsPerMinute(pascalpersecond.MegapascalsPerMinute).PascalsPerSecond); + Assert.Equal(3, PressureChangeRate.FromMegapascalsPerSecond(pascalpersecond.MegapascalsPerSecond).PascalsPerSecond); + Assert.Equal(3, PressureChangeRate.FromMegapoundsForcePerSquareInchPerMinute(pascalpersecond.MegapoundsForcePerSquareInchPerMinute).PascalsPerSecond); + Assert.Equal(3, PressureChangeRate.FromMegapoundsForcePerSquareInchPerSecond(pascalpersecond.MegapoundsForcePerSquareInchPerSecond).PascalsPerSecond); + Assert.Equal(3, PressureChangeRate.FromMillibarsPerMinute(pascalpersecond.MillibarsPerMinute).PascalsPerSecond); + Assert.Equal(3, PressureChangeRate.FromMillibarsPerSecond(pascalpersecond.MillibarsPerSecond).PascalsPerSecond); + Assert.Equal(3, PressureChangeRate.FromMillimetersOfMercuryPerSecond(pascalpersecond.MillimetersOfMercuryPerSecond).PascalsPerSecond); + Assert.Equal(3, PressureChangeRate.FromPascalsPerMinute(pascalpersecond.PascalsPerMinute).PascalsPerSecond); + Assert.Equal(3, PressureChangeRate.FromPascalsPerSecond(pascalpersecond.PascalsPerSecond).PascalsPerSecond); + Assert.Equal(3, PressureChangeRate.FromPoundsForcePerSquareInchPerMinute(pascalpersecond.PoundsForcePerSquareInchPerMinute).PascalsPerSecond); + Assert.Equal(3, PressureChangeRate.FromPoundsForcePerSquareInchPerSecond(pascalpersecond.PoundsForcePerSquareInchPerSecond).PascalsPerSecond); } [Fact] public void ArithmeticOperators() { PressureChangeRate v = PressureChangeRate.FromPascalsPerSecond(1); - AssertEx.EqualTolerance(-1, -v.PascalsPerSecond, PascalsPerSecondTolerance); - AssertEx.EqualTolerance(2, (PressureChangeRate.FromPascalsPerSecond(3)-v).PascalsPerSecond, PascalsPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).PascalsPerSecond, PascalsPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).PascalsPerSecond, PascalsPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).PascalsPerSecond, PascalsPerSecondTolerance); - AssertEx.EqualTolerance(2, (PressureChangeRate.FromPascalsPerSecond(10)/5).PascalsPerSecond, PascalsPerSecondTolerance); - AssertEx.EqualTolerance(2, PressureChangeRate.FromPascalsPerSecond(10)/PressureChangeRate.FromPascalsPerSecond(5), PascalsPerSecondTolerance); + Assert.Equal(-1, -v.PascalsPerSecond); + Assert.Equal(2, (PressureChangeRate.FromPascalsPerSecond(3) - v).PascalsPerSecond); + Assert.Equal(2, (v + v).PascalsPerSecond); + Assert.Equal(10, (v * 10).PascalsPerSecond); + Assert.Equal(10, (10 * v).PascalsPerSecond); + Assert.Equal(2, (PressureChangeRate.FromPascalsPerSecond(10) / 5).PascalsPerSecond); + Assert.Equal(2, PressureChangeRate.FromPascalsPerSecond(10) / PressureChangeRate.FromPascalsPerSecond(5)); } [Fact] @@ -1041,8 +1058,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, PressureChangeRateUnit.PascalPerSecond, 1, PressureChangeRateUnit.PascalPerSecond, true)] // Same value and unit. [InlineData(1, PressureChangeRateUnit.PascalPerSecond, 2, PressureChangeRateUnit.PascalPerSecond, false)] // Different value. - [InlineData(2, PressureChangeRateUnit.PascalPerSecond, 1, PressureChangeRateUnit.AtmospherePerSecond, false)] // Different value and unit. - [InlineData(1, PressureChangeRateUnit.PascalPerSecond, 1, PressureChangeRateUnit.AtmospherePerSecond, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, PressureChangeRateUnit unitA, double valueB, PressureChangeRateUnit unitB, bool expectEqual) { var a = new PressureChangeRate(valueA, unitA); @@ -1102,8 +1117,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = PressureChangeRate.FromPascalsPerSecond(firstValue); var otherQuantity = PressureChangeRate.FromPascalsPerSecond(secondValue); PressureChangeRate maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, PressureChangeRate.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1122,7 +1137,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1135,6 +1150,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(PressureChangeRate.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(PressureChangeRate.Info.Units, PressureChangeRate.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, PressureChangeRate.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1231,7 +1258,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = PressureChangeRate.FromPascalsPerSecond(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(PressureChangeRate), quantity.As(PressureChangeRate.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs index 95606cfe2a..84ddad5565 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/PressureTestsBase.g.cs @@ -313,6 +313,20 @@ public void Pressure_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void PressureInfo_CreateWithCustomUnitInfos() + { + PressureUnit[] expectedUnits = [PressureUnit.Pascal]; + + Pressure.PressureInfo quantityInfo = Pressure.PressureInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Pressure", quantityInfo.Name); + Assert.Equal(Pressure.Zero, quantityInfo.Zero); + Assert.Equal(Pressure.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void PascalToPressureUnits() { @@ -654,7 +668,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 lb/in²", PressureUnit.PoundForcePerSquareInch, 4.2)] [InlineData("ru-RU", "4,2 ат", PressureUnit.TechnicalAtmosphere, 4.2)] [InlineData("ru-RU", "4,2 торр", PressureUnit.Torr, 4.2)] - public void Parse(string culture, string quantityString, PressureUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, PressureUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Pressure.Parse(quantityString); @@ -760,7 +774,7 @@ public void Parse(string culture, string quantityString, PressureUnit expectedUn [InlineData("ru-RU", "4,2 lb/in²", PressureUnit.PoundForcePerSquareInch, 4.2)] [InlineData("ru-RU", "4,2 ат", PressureUnit.TechnicalAtmosphere, 4.2)] [InlineData("ru-RU", "4,2 торр", PressureUnit.Torr, 4.2)] - public void TryParse(string culture, string quantityString, PressureUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, PressureUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Pressure.TryParse(quantityString, out Pressure parsed)); @@ -1604,6 +1618,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(PressureUnit uni var quantity = Pressure.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -1627,79 +1642,81 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(PressureUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Pressure pascal = Pressure.FromPascals(1); - AssertEx.EqualTolerance(1, Pressure.FromAtmospheres(pascal.Atmospheres).Pascals, AtmospheresTolerance); - AssertEx.EqualTolerance(1, Pressure.FromBars(pascal.Bars).Pascals, BarsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromCentibars(pascal.Centibars).Pascals, CentibarsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromCentimetersOfWaterColumn(pascal.CentimetersOfWaterColumn).Pascals, CentimetersOfWaterColumnTolerance); - AssertEx.EqualTolerance(1, Pressure.FromDecapascals(pascal.Decapascals).Pascals, DecapascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromDecibars(pascal.Decibars).Pascals, DecibarsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromDynesPerSquareCentimeter(pascal.DynesPerSquareCentimeter).Pascals, DynesPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromFeetOfHead(pascal.FeetOfHead).Pascals, FeetOfHeadTolerance); - AssertEx.EqualTolerance(1, Pressure.FromGigapascals(pascal.Gigapascals).Pascals, GigapascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromHectopascals(pascal.Hectopascals).Pascals, HectopascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromInchesOfMercury(pascal.InchesOfMercury).Pascals, InchesOfMercuryTolerance); - AssertEx.EqualTolerance(1, Pressure.FromInchesOfWaterColumn(pascal.InchesOfWaterColumn).Pascals, InchesOfWaterColumnTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilobars(pascal.Kilobars).Pascals, KilobarsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilogramsForcePerSquareCentimeter(pascal.KilogramsForcePerSquareCentimeter).Pascals, KilogramsForcePerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilogramsForcePerSquareMeter(pascal.KilogramsForcePerSquareMeter).Pascals, KilogramsForcePerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilogramsForcePerSquareMillimeter(pascal.KilogramsForcePerSquareMillimeter).Pascals, KilogramsForcePerSquareMillimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilonewtonsPerSquareCentimeter(pascal.KilonewtonsPerSquareCentimeter).Pascals, KilonewtonsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilonewtonsPerSquareMeter(pascal.KilonewtonsPerSquareMeter).Pascals, KilonewtonsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilonewtonsPerSquareMillimeter(pascal.KilonewtonsPerSquareMillimeter).Pascals, KilonewtonsPerSquareMillimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilopascals(pascal.Kilopascals).Pascals, KilopascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilopoundsForcePerSquareFoot(pascal.KilopoundsForcePerSquareFoot).Pascals, KilopoundsForcePerSquareFootTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilopoundsForcePerSquareInch(pascal.KilopoundsForcePerSquareInch).Pascals, KilopoundsForcePerSquareInchTolerance); - AssertEx.EqualTolerance(1, Pressure.FromKilopoundsForcePerSquareMil(pascal.KilopoundsForcePerSquareMil).Pascals, KilopoundsForcePerSquareMilTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMegabars(pascal.Megabars).Pascals, MegabarsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMeganewtonsPerSquareMeter(pascal.MeganewtonsPerSquareMeter).Pascals, MeganewtonsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMegapascals(pascal.Megapascals).Pascals, MegapascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMetersOfHead(pascal.MetersOfHead).Pascals, MetersOfHeadTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMetersOfWaterColumn(pascal.MetersOfWaterColumn).Pascals, MetersOfWaterColumnTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMicrobars(pascal.Microbars).Pascals, MicrobarsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMicropascals(pascal.Micropascals).Pascals, MicropascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMillibars(pascal.Millibars).Pascals, MillibarsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMillimetersOfMercury(pascal.MillimetersOfMercury).Pascals, MillimetersOfMercuryTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMillimetersOfWaterColumn(pascal.MillimetersOfWaterColumn).Pascals, MillimetersOfWaterColumnTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMillipascals(pascal.Millipascals).Pascals, MillipascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromMillitorrs(pascal.Millitorrs).Pascals, MillitorrsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromNewtonsPerSquareCentimeter(pascal.NewtonsPerSquareCentimeter).Pascals, NewtonsPerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromNewtonsPerSquareMeter(pascal.NewtonsPerSquareMeter).Pascals, NewtonsPerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromNewtonsPerSquareMillimeter(pascal.NewtonsPerSquareMillimeter).Pascals, NewtonsPerSquareMillimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromPascals(pascal.Pascals).Pascals, PascalsTolerance); - AssertEx.EqualTolerance(1, Pressure.FromPoundsForcePerSquareFoot(pascal.PoundsForcePerSquareFoot).Pascals, PoundsForcePerSquareFootTolerance); - AssertEx.EqualTolerance(1, Pressure.FromPoundsForcePerSquareInch(pascal.PoundsForcePerSquareInch).Pascals, PoundsForcePerSquareInchTolerance); - AssertEx.EqualTolerance(1, Pressure.FromPoundsForcePerSquareMil(pascal.PoundsForcePerSquareMil).Pascals, PoundsForcePerSquareMilTolerance); - AssertEx.EqualTolerance(1, Pressure.FromPoundsPerInchSecondSquared(pascal.PoundsPerInchSecondSquared).Pascals, PoundsPerInchSecondSquaredTolerance); - AssertEx.EqualTolerance(1, Pressure.FromTechnicalAtmospheres(pascal.TechnicalAtmospheres).Pascals, TechnicalAtmospheresTolerance); - AssertEx.EqualTolerance(1, Pressure.FromTonnesForcePerSquareCentimeter(pascal.TonnesForcePerSquareCentimeter).Pascals, TonnesForcePerSquareCentimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromTonnesForcePerSquareMeter(pascal.TonnesForcePerSquareMeter).Pascals, TonnesForcePerSquareMeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromTonnesForcePerSquareMillimeter(pascal.TonnesForcePerSquareMillimeter).Pascals, TonnesForcePerSquareMillimeterTolerance); - AssertEx.EqualTolerance(1, Pressure.FromTorrs(pascal.Torrs).Pascals, TorrsTolerance); + Pressure pascal = Pressure.FromPascals(3); + Assert.Equal(3, Pressure.FromAtmospheres(pascal.Atmospheres).Pascals); + Assert.Equal(3, Pressure.FromBars(pascal.Bars).Pascals); + Assert.Equal(3, Pressure.FromCentibars(pascal.Centibars).Pascals); + Assert.Equal(3, Pressure.FromCentimetersOfWaterColumn(pascal.CentimetersOfWaterColumn).Pascals); + Assert.Equal(3, Pressure.FromDecapascals(pascal.Decapascals).Pascals); + Assert.Equal(3, Pressure.FromDecibars(pascal.Decibars).Pascals); + Assert.Equal(3, Pressure.FromDynesPerSquareCentimeter(pascal.DynesPerSquareCentimeter).Pascals); + Assert.Equal(3, Pressure.FromFeetOfHead(pascal.FeetOfHead).Pascals); + Assert.Equal(3, Pressure.FromGigapascals(pascal.Gigapascals).Pascals); + Assert.Equal(3, Pressure.FromHectopascals(pascal.Hectopascals).Pascals); + Assert.Equal(3, Pressure.FromInchesOfMercury(pascal.InchesOfMercury).Pascals); + Assert.Equal(3, Pressure.FromInchesOfWaterColumn(pascal.InchesOfWaterColumn).Pascals); + Assert.Equal(3, Pressure.FromKilobars(pascal.Kilobars).Pascals); + Assert.Equal(3, Pressure.FromKilogramsForcePerSquareCentimeter(pascal.KilogramsForcePerSquareCentimeter).Pascals); + Assert.Equal(3, Pressure.FromKilogramsForcePerSquareMeter(pascal.KilogramsForcePerSquareMeter).Pascals); + Assert.Equal(3, Pressure.FromKilogramsForcePerSquareMillimeter(pascal.KilogramsForcePerSquareMillimeter).Pascals); + Assert.Equal(3, Pressure.FromKilonewtonsPerSquareCentimeter(pascal.KilonewtonsPerSquareCentimeter).Pascals); + Assert.Equal(3, Pressure.FromKilonewtonsPerSquareMeter(pascal.KilonewtonsPerSquareMeter).Pascals); + Assert.Equal(3, Pressure.FromKilonewtonsPerSquareMillimeter(pascal.KilonewtonsPerSquareMillimeter).Pascals); + Assert.Equal(3, Pressure.FromKilopascals(pascal.Kilopascals).Pascals); + Assert.Equal(3, Pressure.FromKilopoundsForcePerSquareFoot(pascal.KilopoundsForcePerSquareFoot).Pascals); + Assert.Equal(3, Pressure.FromKilopoundsForcePerSquareInch(pascal.KilopoundsForcePerSquareInch).Pascals); + Assert.Equal(3, Pressure.FromKilopoundsForcePerSquareMil(pascal.KilopoundsForcePerSquareMil).Pascals); + Assert.Equal(3, Pressure.FromMegabars(pascal.Megabars).Pascals); + Assert.Equal(3, Pressure.FromMeganewtonsPerSquareMeter(pascal.MeganewtonsPerSquareMeter).Pascals); + Assert.Equal(3, Pressure.FromMegapascals(pascal.Megapascals).Pascals); + Assert.Equal(3, Pressure.FromMetersOfHead(pascal.MetersOfHead).Pascals); + Assert.Equal(3, Pressure.FromMetersOfWaterColumn(pascal.MetersOfWaterColumn).Pascals); + Assert.Equal(3, Pressure.FromMicrobars(pascal.Microbars).Pascals); + Assert.Equal(3, Pressure.FromMicropascals(pascal.Micropascals).Pascals); + Assert.Equal(3, Pressure.FromMillibars(pascal.Millibars).Pascals); + Assert.Equal(3, Pressure.FromMillimetersOfMercury(pascal.MillimetersOfMercury).Pascals); + Assert.Equal(3, Pressure.FromMillimetersOfWaterColumn(pascal.MillimetersOfWaterColumn).Pascals); + Assert.Equal(3, Pressure.FromMillipascals(pascal.Millipascals).Pascals); + Assert.Equal(3, Pressure.FromMillitorrs(pascal.Millitorrs).Pascals); + Assert.Equal(3, Pressure.FromNewtonsPerSquareCentimeter(pascal.NewtonsPerSquareCentimeter).Pascals); + Assert.Equal(3, Pressure.FromNewtonsPerSquareMeter(pascal.NewtonsPerSquareMeter).Pascals); + Assert.Equal(3, Pressure.FromNewtonsPerSquareMillimeter(pascal.NewtonsPerSquareMillimeter).Pascals); + Assert.Equal(3, Pressure.FromPascals(pascal.Pascals).Pascals); + Assert.Equal(3, Pressure.FromPoundsForcePerSquareFoot(pascal.PoundsForcePerSquareFoot).Pascals); + Assert.Equal(3, Pressure.FromPoundsForcePerSquareInch(pascal.PoundsForcePerSquareInch).Pascals); + Assert.Equal(3, Pressure.FromPoundsForcePerSquareMil(pascal.PoundsForcePerSquareMil).Pascals); + Assert.Equal(3, Pressure.FromPoundsPerInchSecondSquared(pascal.PoundsPerInchSecondSquared).Pascals); + Assert.Equal(3, Pressure.FromTechnicalAtmospheres(pascal.TechnicalAtmospheres).Pascals); + Assert.Equal(3, Pressure.FromTonnesForcePerSquareCentimeter(pascal.TonnesForcePerSquareCentimeter).Pascals); + Assert.Equal(3, Pressure.FromTonnesForcePerSquareMeter(pascal.TonnesForcePerSquareMeter).Pascals); + Assert.Equal(3, Pressure.FromTonnesForcePerSquareMillimeter(pascal.TonnesForcePerSquareMillimeter).Pascals); + Assert.Equal(3, Pressure.FromTorrs(pascal.Torrs).Pascals); } [Fact] public void ArithmeticOperators() { Pressure v = Pressure.FromPascals(1); - AssertEx.EqualTolerance(-1, -v.Pascals, PascalsTolerance); - AssertEx.EqualTolerance(2, (Pressure.FromPascals(3)-v).Pascals, PascalsTolerance); - AssertEx.EqualTolerance(2, (v + v).Pascals, PascalsTolerance); - AssertEx.EqualTolerance(10, (v*10).Pascals, PascalsTolerance); - AssertEx.EqualTolerance(10, (10*v).Pascals, PascalsTolerance); - AssertEx.EqualTolerance(2, (Pressure.FromPascals(10)/5).Pascals, PascalsTolerance); - AssertEx.EqualTolerance(2, Pressure.FromPascals(10)/Pressure.FromPascals(5), PascalsTolerance); + Assert.Equal(-1, -v.Pascals); + Assert.Equal(2, (Pressure.FromPascals(3) - v).Pascals); + Assert.Equal(2, (v + v).Pascals); + Assert.Equal(10, (v * 10).Pascals); + Assert.Equal(10, (10 * v).Pascals); + Assert.Equal(2, (Pressure.FromPascals(10) / 5).Pascals); + Assert.Equal(2, Pressure.FromPascals(10) / Pressure.FromPascals(5)); } [Fact] @@ -1745,8 +1762,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, PressureUnit.Pascal, 1, PressureUnit.Pascal, true)] // Same value and unit. [InlineData(1, PressureUnit.Pascal, 2, PressureUnit.Pascal, false)] // Different value. - [InlineData(2, PressureUnit.Pascal, 1, PressureUnit.Atmosphere, false)] // Different value and unit. - [InlineData(1, PressureUnit.Pascal, 1, PressureUnit.Atmosphere, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, PressureUnit unitA, double valueB, PressureUnit unitB, bool expectEqual) { var a = new Pressure(valueA, unitA); @@ -1806,8 +1821,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Pressure.FromPascals(firstValue); var otherQuantity = Pressure.FromPascals(secondValue); Pressure maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Pressure.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1826,7 +1841,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1839,6 +1854,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Pressure.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Pressure.Info.Units, Pressure.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Pressure.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1995,7 +2022,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Pressure.FromPascals(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Pressure), quantity.As(Pressure.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationEquivalentDoseRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationEquivalentDoseRateTestsBase.g.cs index 8afdf3b88b..4abf48f201 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationEquivalentDoseRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationEquivalentDoseRateTestsBase.g.cs @@ -161,6 +161,20 @@ public void RadiationEquivalentDoseRate_QuantityInfo_ReturnsQuantityInfoDescribi Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void RadiationEquivalentDoseRateInfo_CreateWithCustomUnitInfos() + { + RadiationEquivalentDoseRateUnit[] expectedUnits = [RadiationEquivalentDoseRateUnit.SievertPerSecond]; + + RadiationEquivalentDoseRate.RadiationEquivalentDoseRateInfo quantityInfo = RadiationEquivalentDoseRate.RadiationEquivalentDoseRateInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("RadiationEquivalentDoseRate", quantityInfo.Name); + Assert.Equal(RadiationEquivalentDoseRate.Zero, quantityInfo.Zero); + Assert.Equal(RadiationEquivalentDoseRate.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void SievertPerSecondToRadiationEquivalentDoseRateUnits() { @@ -347,7 +361,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 нЗв/с", RadiationEquivalentDoseRateUnit.NanosievertPerSecond, 4.2)] [InlineData("ru-RU", "4,2 Зв/ч", RadiationEquivalentDoseRateUnit.SievertPerHour, 4.2)] [InlineData("ru-RU", "4,2 Зв/с", RadiationEquivalentDoseRateUnit.SievertPerSecond, 4.2)] - public void Parse(string culture, string quantityString, RadiationEquivalentDoseRateUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, RadiationEquivalentDoseRateUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = RadiationEquivalentDoseRate.Parse(quantityString); @@ -374,7 +388,7 @@ public void Parse(string culture, string quantityString, RadiationEquivalentDose [InlineData("ru-RU", "4,2 нЗв/с", RadiationEquivalentDoseRateUnit.NanosievertPerSecond, 4.2)] [InlineData("ru-RU", "4,2 Зв/ч", RadiationEquivalentDoseRateUnit.SievertPerHour, 4.2)] [InlineData("ru-RU", "4,2 Зв/с", RadiationEquivalentDoseRateUnit.SievertPerSecond, 4.2)] - public void TryParse(string culture, string quantityString, RadiationEquivalentDoseRateUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, RadiationEquivalentDoseRateUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(RadiationEquivalentDoseRate.TryParse(quantityString, out RadiationEquivalentDoseRate parsed)); @@ -628,6 +642,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RadiationEquival var quantity = RadiationEquivalentDoseRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -651,41 +666,43 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(RadiationEquivalent IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - RadiationEquivalentDoseRate sievertpersecond = RadiationEquivalentDoseRate.FromSievertsPerSecond(1); - AssertEx.EqualTolerance(1, RadiationEquivalentDoseRate.FromMicrosievertsPerHour(sievertpersecond.MicrosievertsPerHour).SievertsPerSecond, MicrosievertsPerHourTolerance); - AssertEx.EqualTolerance(1, RadiationEquivalentDoseRate.FromMicrosievertsPerSecond(sievertpersecond.MicrosievertsPerSecond).SievertsPerSecond, MicrosievertsPerSecondTolerance); - AssertEx.EqualTolerance(1, RadiationEquivalentDoseRate.FromMilliroentgensEquivalentManPerHour(sievertpersecond.MilliroentgensEquivalentManPerHour).SievertsPerSecond, MilliroentgensEquivalentManPerHourTolerance); - AssertEx.EqualTolerance(1, RadiationEquivalentDoseRate.FromMillisievertsPerHour(sievertpersecond.MillisievertsPerHour).SievertsPerSecond, MillisievertsPerHourTolerance); - AssertEx.EqualTolerance(1, RadiationEquivalentDoseRate.FromMillisievertsPerSecond(sievertpersecond.MillisievertsPerSecond).SievertsPerSecond, MillisievertsPerSecondTolerance); - AssertEx.EqualTolerance(1, RadiationEquivalentDoseRate.FromNanosievertsPerHour(sievertpersecond.NanosievertsPerHour).SievertsPerSecond, NanosievertsPerHourTolerance); - AssertEx.EqualTolerance(1, RadiationEquivalentDoseRate.FromNanosievertsPerSecond(sievertpersecond.NanosievertsPerSecond).SievertsPerSecond, NanosievertsPerSecondTolerance); - AssertEx.EqualTolerance(1, RadiationEquivalentDoseRate.FromRoentgensEquivalentManPerHour(sievertpersecond.RoentgensEquivalentManPerHour).SievertsPerSecond, RoentgensEquivalentManPerHourTolerance); - AssertEx.EqualTolerance(1, RadiationEquivalentDoseRate.FromSievertsPerHour(sievertpersecond.SievertsPerHour).SievertsPerSecond, SievertsPerHourTolerance); - AssertEx.EqualTolerance(1, RadiationEquivalentDoseRate.FromSievertsPerSecond(sievertpersecond.SievertsPerSecond).SievertsPerSecond, SievertsPerSecondTolerance); + RadiationEquivalentDoseRate sievertpersecond = RadiationEquivalentDoseRate.FromSievertsPerSecond(3); + Assert.Equal(3, RadiationEquivalentDoseRate.FromMicrosievertsPerHour(sievertpersecond.MicrosievertsPerHour).SievertsPerSecond); + Assert.Equal(3, RadiationEquivalentDoseRate.FromMicrosievertsPerSecond(sievertpersecond.MicrosievertsPerSecond).SievertsPerSecond); + Assert.Equal(3, RadiationEquivalentDoseRate.FromMilliroentgensEquivalentManPerHour(sievertpersecond.MilliroentgensEquivalentManPerHour).SievertsPerSecond); + Assert.Equal(3, RadiationEquivalentDoseRate.FromMillisievertsPerHour(sievertpersecond.MillisievertsPerHour).SievertsPerSecond); + Assert.Equal(3, RadiationEquivalentDoseRate.FromMillisievertsPerSecond(sievertpersecond.MillisievertsPerSecond).SievertsPerSecond); + Assert.Equal(3, RadiationEquivalentDoseRate.FromNanosievertsPerHour(sievertpersecond.NanosievertsPerHour).SievertsPerSecond); + Assert.Equal(3, RadiationEquivalentDoseRate.FromNanosievertsPerSecond(sievertpersecond.NanosievertsPerSecond).SievertsPerSecond); + Assert.Equal(3, RadiationEquivalentDoseRate.FromRoentgensEquivalentManPerHour(sievertpersecond.RoentgensEquivalentManPerHour).SievertsPerSecond); + Assert.Equal(3, RadiationEquivalentDoseRate.FromSievertsPerHour(sievertpersecond.SievertsPerHour).SievertsPerSecond); + Assert.Equal(3, RadiationEquivalentDoseRate.FromSievertsPerSecond(sievertpersecond.SievertsPerSecond).SievertsPerSecond); } [Fact] public void ArithmeticOperators() { RadiationEquivalentDoseRate v = RadiationEquivalentDoseRate.FromSievertsPerSecond(1); - AssertEx.EqualTolerance(-1, -v.SievertsPerSecond, SievertsPerSecondTolerance); - AssertEx.EqualTolerance(2, (RadiationEquivalentDoseRate.FromSievertsPerSecond(3)-v).SievertsPerSecond, SievertsPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).SievertsPerSecond, SievertsPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).SievertsPerSecond, SievertsPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).SievertsPerSecond, SievertsPerSecondTolerance); - AssertEx.EqualTolerance(2, (RadiationEquivalentDoseRate.FromSievertsPerSecond(10)/5).SievertsPerSecond, SievertsPerSecondTolerance); - AssertEx.EqualTolerance(2, RadiationEquivalentDoseRate.FromSievertsPerSecond(10)/RadiationEquivalentDoseRate.FromSievertsPerSecond(5), SievertsPerSecondTolerance); + Assert.Equal(-1, -v.SievertsPerSecond); + Assert.Equal(2, (RadiationEquivalentDoseRate.FromSievertsPerSecond(3) - v).SievertsPerSecond); + Assert.Equal(2, (v + v).SievertsPerSecond); + Assert.Equal(10, (v * 10).SievertsPerSecond); + Assert.Equal(10, (10 * v).SievertsPerSecond); + Assert.Equal(2, (RadiationEquivalentDoseRate.FromSievertsPerSecond(10) / 5).SievertsPerSecond); + Assert.Equal(2, RadiationEquivalentDoseRate.FromSievertsPerSecond(10) / RadiationEquivalentDoseRate.FromSievertsPerSecond(5)); } [Fact] @@ -731,8 +748,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, RadiationEquivalentDoseRateUnit.SievertPerSecond, 1, RadiationEquivalentDoseRateUnit.SievertPerSecond, true)] // Same value and unit. [InlineData(1, RadiationEquivalentDoseRateUnit.SievertPerSecond, 2, RadiationEquivalentDoseRateUnit.SievertPerSecond, false)] // Different value. - [InlineData(2, RadiationEquivalentDoseRateUnit.SievertPerSecond, 1, RadiationEquivalentDoseRateUnit.MicrosievertPerHour, false)] // Different value and unit. - [InlineData(1, RadiationEquivalentDoseRateUnit.SievertPerSecond, 1, RadiationEquivalentDoseRateUnit.MicrosievertPerHour, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, RadiationEquivalentDoseRateUnit unitA, double valueB, RadiationEquivalentDoseRateUnit unitB, bool expectEqual) { var a = new RadiationEquivalentDoseRate(valueA, unitA); @@ -792,8 +807,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(firstValue); var otherQuantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(secondValue); RadiationEquivalentDoseRate maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, RadiationEquivalentDoseRate.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -812,7 +827,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -825,6 +840,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(RadiationEquivalentDoseRate.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(RadiationEquivalentDoseRate.Info.Units, RadiationEquivalentDoseRate.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, RadiationEquivalentDoseRate.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -905,7 +932,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = RadiationEquivalentDoseRate.FromSievertsPerSecond(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(RadiationEquivalentDoseRate), quantity.As(RadiationEquivalentDoseRate.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationEquivalentDoseTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationEquivalentDoseTestsBase.g.cs index e8dc49e1ef..dc8dc801f4 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationEquivalentDoseTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationEquivalentDoseTestsBase.g.cs @@ -145,6 +145,20 @@ public void RadiationEquivalentDose_QuantityInfo_ReturnsQuantityInfoDescribingQu Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void RadiationEquivalentDoseInfo_CreateWithCustomUnitInfos() + { + RadiationEquivalentDoseUnit[] expectedUnits = [RadiationEquivalentDoseUnit.Sievert]; + + RadiationEquivalentDose.RadiationEquivalentDoseInfo quantityInfo = RadiationEquivalentDose.RadiationEquivalentDoseInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("RadiationEquivalentDose", quantityInfo.Name); + Assert.Equal(RadiationEquivalentDose.Zero, quantityInfo.Zero); + Assert.Equal(RadiationEquivalentDose.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void SievertToRadiationEquivalentDoseUnits() { @@ -315,7 +329,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 мЗв", RadiationEquivalentDoseUnit.Millisievert, 4.2)] [InlineData("ru-RU", "4,2 нЗв", RadiationEquivalentDoseUnit.Nanosievert, 4.2)] [InlineData("ru-RU", "4,2 Зв", RadiationEquivalentDoseUnit.Sievert, 4.2)] - public void Parse(string culture, string quantityString, RadiationEquivalentDoseUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, RadiationEquivalentDoseUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = RadiationEquivalentDose.Parse(quantityString); @@ -334,7 +348,7 @@ public void Parse(string culture, string quantityString, RadiationEquivalentDose [InlineData("ru-RU", "4,2 мЗв", RadiationEquivalentDoseUnit.Millisievert, 4.2)] [InlineData("ru-RU", "4,2 нЗв", RadiationEquivalentDoseUnit.Nanosievert, 4.2)] [InlineData("ru-RU", "4,2 Зв", RadiationEquivalentDoseUnit.Sievert, 4.2)] - public void TryParse(string culture, string quantityString, RadiationEquivalentDoseUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, RadiationEquivalentDoseUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(RadiationEquivalentDose.TryParse(quantityString, out RadiationEquivalentDose parsed)); @@ -532,6 +546,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RadiationEquival var quantity = RadiationEquivalentDose.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -555,37 +570,39 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(RadiationEquivalent IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - RadiationEquivalentDose sievert = RadiationEquivalentDose.FromSieverts(1); - AssertEx.EqualTolerance(1, RadiationEquivalentDose.FromMicrosieverts(sievert.Microsieverts).Sieverts, MicrosievertsTolerance); - AssertEx.EqualTolerance(1, RadiationEquivalentDose.FromMilliroentgensEquivalentMan(sievert.MilliroentgensEquivalentMan).Sieverts, MilliroentgensEquivalentManTolerance); - AssertEx.EqualTolerance(1, RadiationEquivalentDose.FromMillisieverts(sievert.Millisieverts).Sieverts, MillisievertsTolerance); - AssertEx.EqualTolerance(1, RadiationEquivalentDose.FromNanosieverts(sievert.Nanosieverts).Sieverts, NanosievertsTolerance); - AssertEx.EqualTolerance(1, RadiationEquivalentDose.FromRoentgensEquivalentMan(sievert.RoentgensEquivalentMan).Sieverts, RoentgensEquivalentManTolerance); - AssertEx.EqualTolerance(1, RadiationEquivalentDose.FromSieverts(sievert.Sieverts).Sieverts, SievertsTolerance); + RadiationEquivalentDose sievert = RadiationEquivalentDose.FromSieverts(3); + Assert.Equal(3, RadiationEquivalentDose.FromMicrosieverts(sievert.Microsieverts).Sieverts); + Assert.Equal(3, RadiationEquivalentDose.FromMilliroentgensEquivalentMan(sievert.MilliroentgensEquivalentMan).Sieverts); + Assert.Equal(3, RadiationEquivalentDose.FromMillisieverts(sievert.Millisieverts).Sieverts); + Assert.Equal(3, RadiationEquivalentDose.FromNanosieverts(sievert.Nanosieverts).Sieverts); + Assert.Equal(3, RadiationEquivalentDose.FromRoentgensEquivalentMan(sievert.RoentgensEquivalentMan).Sieverts); + Assert.Equal(3, RadiationEquivalentDose.FromSieverts(sievert.Sieverts).Sieverts); } [Fact] public void ArithmeticOperators() { RadiationEquivalentDose v = RadiationEquivalentDose.FromSieverts(1); - AssertEx.EqualTolerance(-1, -v.Sieverts, SievertsTolerance); - AssertEx.EqualTolerance(2, (RadiationEquivalentDose.FromSieverts(3)-v).Sieverts, SievertsTolerance); - AssertEx.EqualTolerance(2, (v + v).Sieverts, SievertsTolerance); - AssertEx.EqualTolerance(10, (v*10).Sieverts, SievertsTolerance); - AssertEx.EqualTolerance(10, (10*v).Sieverts, SievertsTolerance); - AssertEx.EqualTolerance(2, (RadiationEquivalentDose.FromSieverts(10)/5).Sieverts, SievertsTolerance); - AssertEx.EqualTolerance(2, RadiationEquivalentDose.FromSieverts(10)/RadiationEquivalentDose.FromSieverts(5), SievertsTolerance); + Assert.Equal(-1, -v.Sieverts); + Assert.Equal(2, (RadiationEquivalentDose.FromSieverts(3) - v).Sieverts); + Assert.Equal(2, (v + v).Sieverts); + Assert.Equal(10, (v * 10).Sieverts); + Assert.Equal(10, (10 * v).Sieverts); + Assert.Equal(2, (RadiationEquivalentDose.FromSieverts(10) / 5).Sieverts); + Assert.Equal(2, RadiationEquivalentDose.FromSieverts(10) / RadiationEquivalentDose.FromSieverts(5)); } [Fact] @@ -631,8 +648,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, RadiationEquivalentDoseUnit.Sievert, 1, RadiationEquivalentDoseUnit.Sievert, true)] // Same value and unit. [InlineData(1, RadiationEquivalentDoseUnit.Sievert, 2, RadiationEquivalentDoseUnit.Sievert, false)] // Different value. - [InlineData(2, RadiationEquivalentDoseUnit.Sievert, 1, RadiationEquivalentDoseUnit.Microsievert, false)] // Different value and unit. - [InlineData(1, RadiationEquivalentDoseUnit.Sievert, 1, RadiationEquivalentDoseUnit.Microsievert, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, RadiationEquivalentDoseUnit unitA, double valueB, RadiationEquivalentDoseUnit unitB, bool expectEqual) { var a = new RadiationEquivalentDose(valueA, unitA); @@ -692,8 +707,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = RadiationEquivalentDose.FromSieverts(firstValue); var otherQuantity = RadiationEquivalentDose.FromSieverts(secondValue); RadiationEquivalentDose maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, RadiationEquivalentDose.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -712,7 +727,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -725,6 +740,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(RadiationEquivalentDose.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(RadiationEquivalentDose.Info.Units, RadiationEquivalentDose.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, RadiationEquivalentDose.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -797,7 +824,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = RadiationEquivalentDose.FromSieverts(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(RadiationEquivalentDose), quantity.As(RadiationEquivalentDose.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationExposureTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationExposureTestsBase.g.cs index 94f03bf78a..d1a942e978 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationExposureTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RadiationExposureTestsBase.g.cs @@ -153,6 +153,20 @@ public void RadiationExposure_QuantityInfo_ReturnsQuantityInfoDescribingQuantity Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void RadiationExposureInfo_CreateWithCustomUnitInfos() + { + RadiationExposureUnit[] expectedUnits = [RadiationExposureUnit.CoulombPerKilogram]; + + RadiationExposure.RadiationExposureInfo quantityInfo = RadiationExposure.RadiationExposureInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("RadiationExposure", quantityInfo.Name); + Assert.Equal(RadiationExposure.Zero, quantityInfo.Zero); + Assert.Equal(RadiationExposure.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void CoulombPerKilogramToRadiationExposureUnits() { @@ -325,7 +339,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 nC/kg", RadiationExposureUnit.NanocoulombPerKilogram, 4.2)] [InlineData("en-US", "4.2 pC/kg", RadiationExposureUnit.PicocoulombPerKilogram, 4.2)] [InlineData("en-US", "4.2 R", RadiationExposureUnit.Roentgen, 4.2)] - public void Parse(string culture, string quantityString, RadiationExposureUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, RadiationExposureUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = RadiationExposure.Parse(quantityString); @@ -342,7 +356,7 @@ public void Parse(string culture, string quantityString, RadiationExposureUnit e [InlineData("en-US", "4.2 nC/kg", RadiationExposureUnit.NanocoulombPerKilogram, 4.2)] [InlineData("en-US", "4.2 pC/kg", RadiationExposureUnit.PicocoulombPerKilogram, 4.2)] [InlineData("en-US", "4.2 R", RadiationExposureUnit.Roentgen, 4.2)] - public void TryParse(string culture, string quantityString, RadiationExposureUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, RadiationExposureUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(RadiationExposure.TryParse(quantityString, out RadiationExposure parsed)); @@ -538,6 +552,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RadiationExposur var quantity = RadiationExposure.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -561,39 +576,41 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(RadiationExposureUn IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - RadiationExposure coulombperkilogram = RadiationExposure.FromCoulombsPerKilogram(1); - AssertEx.EqualTolerance(1, RadiationExposure.FromCoulombsPerKilogram(coulombperkilogram.CoulombsPerKilogram).CoulombsPerKilogram, CoulombsPerKilogramTolerance); - AssertEx.EqualTolerance(1, RadiationExposure.FromMicrocoulombsPerKilogram(coulombperkilogram.MicrocoulombsPerKilogram).CoulombsPerKilogram, MicrocoulombsPerKilogramTolerance); - AssertEx.EqualTolerance(1, RadiationExposure.FromMicroroentgens(coulombperkilogram.Microroentgens).CoulombsPerKilogram, MicroroentgensTolerance); - AssertEx.EqualTolerance(1, RadiationExposure.FromMillicoulombsPerKilogram(coulombperkilogram.MillicoulombsPerKilogram).CoulombsPerKilogram, MillicoulombsPerKilogramTolerance); - AssertEx.EqualTolerance(1, RadiationExposure.FromMilliroentgens(coulombperkilogram.Milliroentgens).CoulombsPerKilogram, MilliroentgensTolerance); - AssertEx.EqualTolerance(1, RadiationExposure.FromNanocoulombsPerKilogram(coulombperkilogram.NanocoulombsPerKilogram).CoulombsPerKilogram, NanocoulombsPerKilogramTolerance); - AssertEx.EqualTolerance(1, RadiationExposure.FromPicocoulombsPerKilogram(coulombperkilogram.PicocoulombsPerKilogram).CoulombsPerKilogram, PicocoulombsPerKilogramTolerance); - AssertEx.EqualTolerance(1, RadiationExposure.FromRoentgens(coulombperkilogram.Roentgens).CoulombsPerKilogram, RoentgensTolerance); + RadiationExposure coulombperkilogram = RadiationExposure.FromCoulombsPerKilogram(3); + Assert.Equal(3, RadiationExposure.FromCoulombsPerKilogram(coulombperkilogram.CoulombsPerKilogram).CoulombsPerKilogram); + Assert.Equal(3, RadiationExposure.FromMicrocoulombsPerKilogram(coulombperkilogram.MicrocoulombsPerKilogram).CoulombsPerKilogram); + Assert.Equal(3, RadiationExposure.FromMicroroentgens(coulombperkilogram.Microroentgens).CoulombsPerKilogram); + Assert.Equal(3, RadiationExposure.FromMillicoulombsPerKilogram(coulombperkilogram.MillicoulombsPerKilogram).CoulombsPerKilogram); + Assert.Equal(3, RadiationExposure.FromMilliroentgens(coulombperkilogram.Milliroentgens).CoulombsPerKilogram); + Assert.Equal(3, RadiationExposure.FromNanocoulombsPerKilogram(coulombperkilogram.NanocoulombsPerKilogram).CoulombsPerKilogram); + Assert.Equal(3, RadiationExposure.FromPicocoulombsPerKilogram(coulombperkilogram.PicocoulombsPerKilogram).CoulombsPerKilogram); + Assert.Equal(3, RadiationExposure.FromRoentgens(coulombperkilogram.Roentgens).CoulombsPerKilogram); } [Fact] public void ArithmeticOperators() { RadiationExposure v = RadiationExposure.FromCoulombsPerKilogram(1); - AssertEx.EqualTolerance(-1, -v.CoulombsPerKilogram, CoulombsPerKilogramTolerance); - AssertEx.EqualTolerance(2, (RadiationExposure.FromCoulombsPerKilogram(3)-v).CoulombsPerKilogram, CoulombsPerKilogramTolerance); - AssertEx.EqualTolerance(2, (v + v).CoulombsPerKilogram, CoulombsPerKilogramTolerance); - AssertEx.EqualTolerance(10, (v*10).CoulombsPerKilogram, CoulombsPerKilogramTolerance); - AssertEx.EqualTolerance(10, (10*v).CoulombsPerKilogram, CoulombsPerKilogramTolerance); - AssertEx.EqualTolerance(2, (RadiationExposure.FromCoulombsPerKilogram(10)/5).CoulombsPerKilogram, CoulombsPerKilogramTolerance); - AssertEx.EqualTolerance(2, RadiationExposure.FromCoulombsPerKilogram(10)/RadiationExposure.FromCoulombsPerKilogram(5), CoulombsPerKilogramTolerance); + Assert.Equal(-1, -v.CoulombsPerKilogram); + Assert.Equal(2, (RadiationExposure.FromCoulombsPerKilogram(3) - v).CoulombsPerKilogram); + Assert.Equal(2, (v + v).CoulombsPerKilogram); + Assert.Equal(10, (v * 10).CoulombsPerKilogram); + Assert.Equal(10, (10 * v).CoulombsPerKilogram); + Assert.Equal(2, (RadiationExposure.FromCoulombsPerKilogram(10) / 5).CoulombsPerKilogram); + Assert.Equal(2, RadiationExposure.FromCoulombsPerKilogram(10) / RadiationExposure.FromCoulombsPerKilogram(5)); } [Fact] @@ -639,8 +656,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, RadiationExposureUnit.CoulombPerKilogram, 1, RadiationExposureUnit.CoulombPerKilogram, true)] // Same value and unit. [InlineData(1, RadiationExposureUnit.CoulombPerKilogram, 2, RadiationExposureUnit.CoulombPerKilogram, false)] // Different value. - [InlineData(2, RadiationExposureUnit.CoulombPerKilogram, 1, RadiationExposureUnit.MicrocoulombPerKilogram, false)] // Different value and unit. - [InlineData(1, RadiationExposureUnit.CoulombPerKilogram, 1, RadiationExposureUnit.MicrocoulombPerKilogram, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, RadiationExposureUnit unitA, double valueB, RadiationExposureUnit unitB, bool expectEqual) { var a = new RadiationExposure(valueA, unitA); @@ -700,8 +715,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = RadiationExposure.FromCoulombsPerKilogram(firstValue); var otherQuantity = RadiationExposure.FromCoulombsPerKilogram(secondValue); RadiationExposure maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, RadiationExposure.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -720,7 +735,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -733,6 +748,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(RadiationExposure.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(RadiationExposure.Info.Units, RadiationExposure.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, RadiationExposure.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -809,7 +836,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = RadiationExposure.FromCoulombsPerKilogram(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(RadiationExposure), quantity.As(RadiationExposure.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RadioactivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RadioactivityTestsBase.g.cs index 3330ad92e5..b332b946f3 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RadioactivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RadioactivityTestsBase.g.cs @@ -237,6 +237,20 @@ public void Radioactivity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void RadioactivityInfo_CreateWithCustomUnitInfos() + { + RadioactivityUnit[] expectedUnits = [RadioactivityUnit.Becquerel]; + + Radioactivity.RadioactivityInfo quantityInfo = Radioactivity.RadioactivityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Radioactivity", quantityInfo.Name); + Assert.Equal(Radioactivity.Zero, quantityInfo.Zero); + Assert.Equal(Radioactivity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void BecquerelToRadioactivityUnits() { @@ -501,7 +515,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 ТБк", RadioactivityUnit.Terabecquerel, 4.2)] [InlineData("ru-RU", "4,2 ТКи", RadioactivityUnit.Teracurie, 4.2)] [InlineData("ru-RU", "4,2 ТРд", RadioactivityUnit.Terarutherford, 4.2)] - public void Parse(string culture, string quantityString, RadioactivityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, RadioactivityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Radioactivity.Parse(quantityString); @@ -568,7 +582,7 @@ public void Parse(string culture, string quantityString, RadioactivityUnit expec [InlineData("ru-RU", "4,2 ТБк", RadioactivityUnit.Terabecquerel, 4.2)] [InlineData("ru-RU", "4,2 ТКи", RadioactivityUnit.Teracurie, 4.2)] [InlineData("ru-RU", "4,2 ТРд", RadioactivityUnit.Terarutherford, 4.2)] - public void TryParse(string culture, string quantityString, RadioactivityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, RadioactivityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Radioactivity.TryParse(quantityString, out Radioactivity parsed)); @@ -1098,6 +1112,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RadioactivityUni var quantity = Radioactivity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -1121,60 +1136,62 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(RadioactivityUnit u IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Radioactivity becquerel = Radioactivity.FromBecquerels(1); - AssertEx.EqualTolerance(1, Radioactivity.FromBecquerels(becquerel.Becquerels).Becquerels, BecquerelsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromCuries(becquerel.Curies).Becquerels, CuriesTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromExabecquerels(becquerel.Exabecquerels).Becquerels, ExabecquerelsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromGigabecquerels(becquerel.Gigabecquerels).Becquerels, GigabecquerelsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromGigacuries(becquerel.Gigacuries).Becquerels, GigacuriesTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromGigarutherfords(becquerel.Gigarutherfords).Becquerels, GigarutherfordsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromKilobecquerels(becquerel.Kilobecquerels).Becquerels, KilobecquerelsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromKilocuries(becquerel.Kilocuries).Becquerels, KilocuriesTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromKilorutherfords(becquerel.Kilorutherfords).Becquerels, KilorutherfordsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromMegabecquerels(becquerel.Megabecquerels).Becquerels, MegabecquerelsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromMegacuries(becquerel.Megacuries).Becquerels, MegacuriesTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromMegarutherfords(becquerel.Megarutherfords).Becquerels, MegarutherfordsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromMicrobecquerels(becquerel.Microbecquerels).Becquerels, MicrobecquerelsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromMicrocuries(becquerel.Microcuries).Becquerels, MicrocuriesTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromMicrorutherfords(becquerel.Microrutherfords).Becquerels, MicrorutherfordsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromMillibecquerels(becquerel.Millibecquerels).Becquerels, MillibecquerelsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromMillicuries(becquerel.Millicuries).Becquerels, MillicuriesTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromMillirutherfords(becquerel.Millirutherfords).Becquerels, MillirutherfordsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromNanobecquerels(becquerel.Nanobecquerels).Becquerels, NanobecquerelsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromNanocuries(becquerel.Nanocuries).Becquerels, NanocuriesTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromNanorutherfords(becquerel.Nanorutherfords).Becquerels, NanorutherfordsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromPetabecquerels(becquerel.Petabecquerels).Becquerels, PetabecquerelsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromPicobecquerels(becquerel.Picobecquerels).Becquerels, PicobecquerelsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromPicocuries(becquerel.Picocuries).Becquerels, PicocuriesTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromPicorutherfords(becquerel.Picorutherfords).Becquerels, PicorutherfordsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromRutherfords(becquerel.Rutherfords).Becquerels, RutherfordsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromTerabecquerels(becquerel.Terabecquerels).Becquerels, TerabecquerelsTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromTeracuries(becquerel.Teracuries).Becquerels, TeracuriesTolerance); - AssertEx.EqualTolerance(1, Radioactivity.FromTerarutherfords(becquerel.Terarutherfords).Becquerels, TerarutherfordsTolerance); + Radioactivity becquerel = Radioactivity.FromBecquerels(3); + Assert.Equal(3, Radioactivity.FromBecquerels(becquerel.Becquerels).Becquerels); + Assert.Equal(3, Radioactivity.FromCuries(becquerel.Curies).Becquerels); + Assert.Equal(3, Radioactivity.FromExabecquerels(becquerel.Exabecquerels).Becquerels); + Assert.Equal(3, Radioactivity.FromGigabecquerels(becquerel.Gigabecquerels).Becquerels); + Assert.Equal(3, Radioactivity.FromGigacuries(becquerel.Gigacuries).Becquerels); + Assert.Equal(3, Radioactivity.FromGigarutherfords(becquerel.Gigarutherfords).Becquerels); + Assert.Equal(3, Radioactivity.FromKilobecquerels(becquerel.Kilobecquerels).Becquerels); + Assert.Equal(3, Radioactivity.FromKilocuries(becquerel.Kilocuries).Becquerels); + Assert.Equal(3, Radioactivity.FromKilorutherfords(becquerel.Kilorutherfords).Becquerels); + Assert.Equal(3, Radioactivity.FromMegabecquerels(becquerel.Megabecquerels).Becquerels); + Assert.Equal(3, Radioactivity.FromMegacuries(becquerel.Megacuries).Becquerels); + Assert.Equal(3, Radioactivity.FromMegarutherfords(becquerel.Megarutherfords).Becquerels); + Assert.Equal(3, Radioactivity.FromMicrobecquerels(becquerel.Microbecquerels).Becquerels); + Assert.Equal(3, Radioactivity.FromMicrocuries(becquerel.Microcuries).Becquerels); + Assert.Equal(3, Radioactivity.FromMicrorutherfords(becquerel.Microrutherfords).Becquerels); + Assert.Equal(3, Radioactivity.FromMillibecquerels(becquerel.Millibecquerels).Becquerels); + Assert.Equal(3, Radioactivity.FromMillicuries(becquerel.Millicuries).Becquerels); + Assert.Equal(3, Radioactivity.FromMillirutherfords(becquerel.Millirutherfords).Becquerels); + Assert.Equal(3, Radioactivity.FromNanobecquerels(becquerel.Nanobecquerels).Becquerels); + Assert.Equal(3, Radioactivity.FromNanocuries(becquerel.Nanocuries).Becquerels); + Assert.Equal(3, Radioactivity.FromNanorutherfords(becquerel.Nanorutherfords).Becquerels); + Assert.Equal(3, Radioactivity.FromPetabecquerels(becquerel.Petabecquerels).Becquerels); + Assert.Equal(3, Radioactivity.FromPicobecquerels(becquerel.Picobecquerels).Becquerels); + Assert.Equal(3, Radioactivity.FromPicocuries(becquerel.Picocuries).Becquerels); + Assert.Equal(3, Radioactivity.FromPicorutherfords(becquerel.Picorutherfords).Becquerels); + Assert.Equal(3, Radioactivity.FromRutherfords(becquerel.Rutherfords).Becquerels); + Assert.Equal(3, Radioactivity.FromTerabecquerels(becquerel.Terabecquerels).Becquerels); + Assert.Equal(3, Radioactivity.FromTeracuries(becquerel.Teracuries).Becquerels); + Assert.Equal(3, Radioactivity.FromTerarutherfords(becquerel.Terarutherfords).Becquerels); } [Fact] public void ArithmeticOperators() { Radioactivity v = Radioactivity.FromBecquerels(1); - AssertEx.EqualTolerance(-1, -v.Becquerels, BecquerelsTolerance); - AssertEx.EqualTolerance(2, (Radioactivity.FromBecquerels(3)-v).Becquerels, BecquerelsTolerance); - AssertEx.EqualTolerance(2, (v + v).Becquerels, BecquerelsTolerance); - AssertEx.EqualTolerance(10, (v*10).Becquerels, BecquerelsTolerance); - AssertEx.EqualTolerance(10, (10*v).Becquerels, BecquerelsTolerance); - AssertEx.EqualTolerance(2, (Radioactivity.FromBecquerels(10)/5).Becquerels, BecquerelsTolerance); - AssertEx.EqualTolerance(2, Radioactivity.FromBecquerels(10)/Radioactivity.FromBecquerels(5), BecquerelsTolerance); + Assert.Equal(-1, -v.Becquerels); + Assert.Equal(2, (Radioactivity.FromBecquerels(3) - v).Becquerels); + Assert.Equal(2, (v + v).Becquerels); + Assert.Equal(10, (v * 10).Becquerels); + Assert.Equal(10, (10 * v).Becquerels); + Assert.Equal(2, (Radioactivity.FromBecquerels(10) / 5).Becquerels); + Assert.Equal(2, Radioactivity.FromBecquerels(10) / Radioactivity.FromBecquerels(5)); } [Fact] @@ -1220,8 +1237,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, RadioactivityUnit.Becquerel, 1, RadioactivityUnit.Becquerel, true)] // Same value and unit. [InlineData(1, RadioactivityUnit.Becquerel, 2, RadioactivityUnit.Becquerel, false)] // Different value. - [InlineData(2, RadioactivityUnit.Becquerel, 1, RadioactivityUnit.Curie, false)] // Different value and unit. - [InlineData(1, RadioactivityUnit.Becquerel, 1, RadioactivityUnit.Curie, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, RadioactivityUnit unitA, double valueB, RadioactivityUnit unitB, bool expectEqual) { var a = new Radioactivity(valueA, unitA); @@ -1281,8 +1296,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Radioactivity.FromBecquerels(firstValue); var otherQuantity = Radioactivity.FromBecquerels(secondValue); Radioactivity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Radioactivity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1301,7 +1316,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1314,6 +1329,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Radioactivity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Radioactivity.Info.Units, Radioactivity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Radioactivity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1432,7 +1459,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Radioactivity.FromBecquerels(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Radioactivity), quantity.As(Radioactivity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs index 1ef1b53086..21e6d3c596 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioChangeRateTestsBase.g.cs @@ -129,6 +129,20 @@ public void RatioChangeRate_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void RatioChangeRateInfo_CreateWithCustomUnitInfos() + { + RatioChangeRateUnit[] expectedUnits = [RatioChangeRateUnit.DecimalFractionPerSecond]; + + RatioChangeRate.RatioChangeRateInfo quantityInfo = RatioChangeRate.RatioChangeRateInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("RatioChangeRate", quantityInfo.Name); + Assert.Equal(RatioChangeRate.Zero, quantityInfo.Zero); + Assert.Equal(RatioChangeRate.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void DecimalFractionPerSecondToRatioChangeRateUnits() { @@ -283,7 +297,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Theory] [InlineData("en-US", "4.2 /s", RatioChangeRateUnit.DecimalFractionPerSecond, 4.2)] [InlineData("en-US", "4.2 %/s", RatioChangeRateUnit.PercentPerSecond, 4.2)] - public void Parse(string culture, string quantityString, RatioChangeRateUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, RatioChangeRateUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = RatioChangeRate.Parse(quantityString); @@ -294,7 +308,7 @@ public void Parse(string culture, string quantityString, RatioChangeRateUnit exp [Theory] [InlineData("en-US", "4.2 /s", RatioChangeRateUnit.DecimalFractionPerSecond, 4.2)] [InlineData("en-US", "4.2 %/s", RatioChangeRateUnit.PercentPerSecond, 4.2)] - public void TryParse(string culture, string quantityString, RatioChangeRateUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, RatioChangeRateUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(RatioChangeRate.TryParse(quantityString, out RatioChangeRate parsed)); @@ -436,6 +450,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RatioChangeRateU var quantity = RatioChangeRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -459,33 +474,35 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(RatioChangeRateUnit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - RatioChangeRate decimalfractionpersecond = RatioChangeRate.FromDecimalFractionsPerSecond(1); - AssertEx.EqualTolerance(1, RatioChangeRate.FromDecimalFractionsPerSecond(decimalfractionpersecond.DecimalFractionsPerSecond).DecimalFractionsPerSecond, DecimalFractionsPerSecondTolerance); - AssertEx.EqualTolerance(1, RatioChangeRate.FromPercentsPerSecond(decimalfractionpersecond.PercentsPerSecond).DecimalFractionsPerSecond, PercentsPerSecondTolerance); + RatioChangeRate decimalfractionpersecond = RatioChangeRate.FromDecimalFractionsPerSecond(3); + Assert.Equal(3, RatioChangeRate.FromDecimalFractionsPerSecond(decimalfractionpersecond.DecimalFractionsPerSecond).DecimalFractionsPerSecond); + Assert.Equal(3, RatioChangeRate.FromPercentsPerSecond(decimalfractionpersecond.PercentsPerSecond).DecimalFractionsPerSecond); } [Fact] public void ArithmeticOperators() { RatioChangeRate v = RatioChangeRate.FromDecimalFractionsPerSecond(1); - AssertEx.EqualTolerance(-1, -v.DecimalFractionsPerSecond, DecimalFractionsPerSecondTolerance); - AssertEx.EqualTolerance(2, (RatioChangeRate.FromDecimalFractionsPerSecond(3)-v).DecimalFractionsPerSecond, DecimalFractionsPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).DecimalFractionsPerSecond, DecimalFractionsPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).DecimalFractionsPerSecond, DecimalFractionsPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).DecimalFractionsPerSecond, DecimalFractionsPerSecondTolerance); - AssertEx.EqualTolerance(2, (RatioChangeRate.FromDecimalFractionsPerSecond(10)/5).DecimalFractionsPerSecond, DecimalFractionsPerSecondTolerance); - AssertEx.EqualTolerance(2, RatioChangeRate.FromDecimalFractionsPerSecond(10)/RatioChangeRate.FromDecimalFractionsPerSecond(5), DecimalFractionsPerSecondTolerance); + Assert.Equal(-1, -v.DecimalFractionsPerSecond); + Assert.Equal(2, (RatioChangeRate.FromDecimalFractionsPerSecond(3) - v).DecimalFractionsPerSecond); + Assert.Equal(2, (v + v).DecimalFractionsPerSecond); + Assert.Equal(10, (v * 10).DecimalFractionsPerSecond); + Assert.Equal(10, (10 * v).DecimalFractionsPerSecond); + Assert.Equal(2, (RatioChangeRate.FromDecimalFractionsPerSecond(10) / 5).DecimalFractionsPerSecond); + Assert.Equal(2, RatioChangeRate.FromDecimalFractionsPerSecond(10) / RatioChangeRate.FromDecimalFractionsPerSecond(5)); } [Fact] @@ -531,8 +548,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, RatioChangeRateUnit.DecimalFractionPerSecond, 1, RatioChangeRateUnit.DecimalFractionPerSecond, true)] // Same value and unit. [InlineData(1, RatioChangeRateUnit.DecimalFractionPerSecond, 2, RatioChangeRateUnit.DecimalFractionPerSecond, false)] // Different value. - [InlineData(2, RatioChangeRateUnit.DecimalFractionPerSecond, 1, RatioChangeRateUnit.PercentPerSecond, false)] // Different value and unit. - [InlineData(1, RatioChangeRateUnit.DecimalFractionPerSecond, 1, RatioChangeRateUnit.PercentPerSecond, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, RatioChangeRateUnit unitA, double valueB, RatioChangeRateUnit unitB, bool expectEqual) { var a = new RatioChangeRate(valueA, unitA); @@ -592,8 +607,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(firstValue); var otherQuantity = RatioChangeRate.FromDecimalFractionsPerSecond(secondValue); RatioChangeRate maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, RatioChangeRate.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -612,7 +627,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -625,6 +640,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(RatioChangeRate.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(RatioChangeRate.Info.Units, RatioChangeRate.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, RatioChangeRate.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -689,7 +716,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = RatioChangeRate.FromDecimalFractionsPerSecond(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(RatioChangeRate), quantity.As(RatioChangeRate.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs index 083c643bf9..baf83ad91f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RatioTestsBase.g.cs @@ -124,6 +124,20 @@ public void Ratio_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void RatioInfo_CreateWithCustomUnitInfos() + { + RatioUnit[] expectedUnits = [RatioUnit.DecimalFraction]; + + Ratio.RatioInfo quantityInfo = Ratio.RatioInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Ratio", quantityInfo.Name); + Assert.Equal(Ratio.Zero, quantityInfo.Zero); + Assert.Equal(Ratio.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void DecimalFractionToRatioUnits() { @@ -251,7 +265,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() [InlineData("en-US", "4.2 ‰", RatioUnit.PartPerThousand, 4.2)] [InlineData("en-US", "4.2 ppt", RatioUnit.PartPerTrillion, 4.2)] [InlineData("en-US", "4.2 %", RatioUnit.Percent, 4.2)] - public void Parse(string culture, string quantityString, RatioUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, RatioUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Ratio.Parse(quantityString); @@ -266,7 +280,7 @@ public void Parse(string culture, string quantityString, RatioUnit expectedUnit, [InlineData("en-US", "4.2 ‰", RatioUnit.PartPerThousand, 4.2)] [InlineData("en-US", "4.2 ppt", RatioUnit.PartPerTrillion, 4.2)] [InlineData("en-US", "4.2 %", RatioUnit.Percent, 4.2)] - public void TryParse(string culture, string quantityString, RatioUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, RatioUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Ratio.TryParse(quantityString, out Ratio parsed)); @@ -444,6 +458,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RatioUnit unit) var quantity = Ratio.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -467,37 +482,39 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(RatioUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Ratio decimalfraction = Ratio.FromDecimalFractions(1); - AssertEx.EqualTolerance(1, Ratio.FromDecimalFractions(decimalfraction.DecimalFractions).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(1, Ratio.FromPartsPerBillion(decimalfraction.PartsPerBillion).DecimalFractions, PartsPerBillionTolerance); - AssertEx.EqualTolerance(1, Ratio.FromPartsPerMillion(decimalfraction.PartsPerMillion).DecimalFractions, PartsPerMillionTolerance); - AssertEx.EqualTolerance(1, Ratio.FromPartsPerThousand(decimalfraction.PartsPerThousand).DecimalFractions, PartsPerThousandTolerance); - AssertEx.EqualTolerance(1, Ratio.FromPartsPerTrillion(decimalfraction.PartsPerTrillion).DecimalFractions, PartsPerTrillionTolerance); - AssertEx.EqualTolerance(1, Ratio.FromPercent(decimalfraction.Percent).DecimalFractions, PercentTolerance); + Ratio decimalfraction = Ratio.FromDecimalFractions(3); + Assert.Equal(3, Ratio.FromDecimalFractions(decimalfraction.DecimalFractions).DecimalFractions); + Assert.Equal(3, Ratio.FromPartsPerBillion(decimalfraction.PartsPerBillion).DecimalFractions); + Assert.Equal(3, Ratio.FromPartsPerMillion(decimalfraction.PartsPerMillion).DecimalFractions); + Assert.Equal(3, Ratio.FromPartsPerThousand(decimalfraction.PartsPerThousand).DecimalFractions); + Assert.Equal(3, Ratio.FromPartsPerTrillion(decimalfraction.PartsPerTrillion).DecimalFractions); + Assert.Equal(3, Ratio.FromPercent(decimalfraction.Percent).DecimalFractions); } [Fact] public void ArithmeticOperators() { Ratio v = Ratio.FromDecimalFractions(1); - AssertEx.EqualTolerance(-1, -v.DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(2, (Ratio.FromDecimalFractions(3)-v).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(2, (v + v).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(10, (v*10).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(10, (10*v).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(2, (Ratio.FromDecimalFractions(10)/5).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(2, Ratio.FromDecimalFractions(10)/Ratio.FromDecimalFractions(5), DecimalFractionsTolerance); + Assert.Equal(-1, -v.DecimalFractions); + Assert.Equal(2, (Ratio.FromDecimalFractions(3) - v).DecimalFractions); + Assert.Equal(2, (v + v).DecimalFractions); + Assert.Equal(10, (v * 10).DecimalFractions); + Assert.Equal(10, (10 * v).DecimalFractions); + Assert.Equal(2, (Ratio.FromDecimalFractions(10) / 5).DecimalFractions); + Assert.Equal(2, Ratio.FromDecimalFractions(10) / Ratio.FromDecimalFractions(5)); } [Fact] @@ -543,8 +560,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, RatioUnit.DecimalFraction, 1, RatioUnit.DecimalFraction, true)] // Same value and unit. [InlineData(1, RatioUnit.DecimalFraction, 2, RatioUnit.DecimalFraction, false)] // Different value. - [InlineData(2, RatioUnit.DecimalFraction, 1, RatioUnit.PartPerBillion, false)] // Different value and unit. - [InlineData(1, RatioUnit.DecimalFraction, 1, RatioUnit.PartPerBillion, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, RatioUnit unitA, double valueB, RatioUnit unitB, bool expectEqual) { var a = new Ratio(valueA, unitA); @@ -604,8 +619,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Ratio.FromDecimalFractions(firstValue); var otherQuantity = Ratio.FromDecimalFractions(secondValue); Ratio maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Ratio.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -624,7 +639,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -637,6 +652,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Ratio.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Ratio.Info.Units, Ratio.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Ratio.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -709,7 +736,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Ratio.FromDecimalFractions(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Ratio), quantity.As(Ratio.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs index 5473f6b620..4f8d800603 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalAreaTestsBase.g.cs @@ -165,6 +165,20 @@ public void ReciprocalArea_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ReciprocalAreaInfo_CreateWithCustomUnitInfos() + { + ReciprocalAreaUnit[] expectedUnits = [ReciprocalAreaUnit.InverseSquareMeter]; + + ReciprocalArea.ReciprocalAreaInfo quantityInfo = ReciprocalArea.ReciprocalAreaInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ReciprocalArea", quantityInfo.Name); + Assert.Equal(ReciprocalArea.Zero, quantityInfo.Zero); + Assert.Equal(ReciprocalArea.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void InverseSquareMeterToReciprocalAreaUnits() { @@ -346,7 +360,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 mm⁻²", ReciprocalAreaUnit.InverseSquareMillimeter, 4.2)] [InlineData("en-US", "4.2 yd⁻²", ReciprocalAreaUnit.InverseSquareYard, 4.2)] [InlineData("en-US", "4.2 ft⁻² (US)", ReciprocalAreaUnit.InverseUsSurveySquareFoot, 4.2)] - public void Parse(string culture, string quantityString, ReciprocalAreaUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ReciprocalAreaUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ReciprocalArea.Parse(quantityString); @@ -366,7 +380,7 @@ public void Parse(string culture, string quantityString, ReciprocalAreaUnit expe [InlineData("en-US", "4.2 mm⁻²", ReciprocalAreaUnit.InverseSquareMillimeter, 4.2)] [InlineData("en-US", "4.2 yd⁻²", ReciprocalAreaUnit.InverseSquareYard, 4.2)] [InlineData("en-US", "4.2 ft⁻² (US)", ReciprocalAreaUnit.InverseUsSurveySquareFoot, 4.2)] - public void TryParse(string culture, string quantityString, ReciprocalAreaUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ReciprocalAreaUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ReciprocalArea.TryParse(quantityString, out ReciprocalArea parsed)); @@ -589,6 +603,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ReciprocalAreaUn var quantity = ReciprocalArea.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -612,42 +627,44 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ReciprocalAreaUnit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ReciprocalArea inversesquaremeter = ReciprocalArea.FromInverseSquareMeters(1); - AssertEx.EqualTolerance(1, ReciprocalArea.FromInverseSquareCentimeters(inversesquaremeter.InverseSquareCentimeters).InverseSquareMeters, InverseSquareCentimetersTolerance); - AssertEx.EqualTolerance(1, ReciprocalArea.FromInverseSquareDecimeters(inversesquaremeter.InverseSquareDecimeters).InverseSquareMeters, InverseSquareDecimetersTolerance); - AssertEx.EqualTolerance(1, ReciprocalArea.FromInverseSquareFeet(inversesquaremeter.InverseSquareFeet).InverseSquareMeters, InverseSquareFeetTolerance); - AssertEx.EqualTolerance(1, ReciprocalArea.FromInverseSquareInches(inversesquaremeter.InverseSquareInches).InverseSquareMeters, InverseSquareInchesTolerance); - AssertEx.EqualTolerance(1, ReciprocalArea.FromInverseSquareKilometers(inversesquaremeter.InverseSquareKilometers).InverseSquareMeters, InverseSquareKilometersTolerance); - AssertEx.EqualTolerance(1, ReciprocalArea.FromInverseSquareMeters(inversesquaremeter.InverseSquareMeters).InverseSquareMeters, InverseSquareMetersTolerance); - AssertEx.EqualTolerance(1, ReciprocalArea.FromInverseSquareMicrometers(inversesquaremeter.InverseSquareMicrometers).InverseSquareMeters, InverseSquareMicrometersTolerance); - AssertEx.EqualTolerance(1, ReciprocalArea.FromInverseSquareMiles(inversesquaremeter.InverseSquareMiles).InverseSquareMeters, InverseSquareMilesTolerance); - AssertEx.EqualTolerance(1, ReciprocalArea.FromInverseSquareMillimeters(inversesquaremeter.InverseSquareMillimeters).InverseSquareMeters, InverseSquareMillimetersTolerance); - AssertEx.EqualTolerance(1, ReciprocalArea.FromInverseSquareYards(inversesquaremeter.InverseSquareYards).InverseSquareMeters, InverseSquareYardsTolerance); - AssertEx.EqualTolerance(1, ReciprocalArea.FromInverseUsSurveySquareFeet(inversesquaremeter.InverseUsSurveySquareFeet).InverseSquareMeters, InverseUsSurveySquareFeetTolerance); + ReciprocalArea inversesquaremeter = ReciprocalArea.FromInverseSquareMeters(3); + Assert.Equal(3, ReciprocalArea.FromInverseSquareCentimeters(inversesquaremeter.InverseSquareCentimeters).InverseSquareMeters); + Assert.Equal(3, ReciprocalArea.FromInverseSquareDecimeters(inversesquaremeter.InverseSquareDecimeters).InverseSquareMeters); + Assert.Equal(3, ReciprocalArea.FromInverseSquareFeet(inversesquaremeter.InverseSquareFeet).InverseSquareMeters); + Assert.Equal(3, ReciprocalArea.FromInverseSquareInches(inversesquaremeter.InverseSquareInches).InverseSquareMeters); + Assert.Equal(3, ReciprocalArea.FromInverseSquareKilometers(inversesquaremeter.InverseSquareKilometers).InverseSquareMeters); + Assert.Equal(3, ReciprocalArea.FromInverseSquareMeters(inversesquaremeter.InverseSquareMeters).InverseSquareMeters); + Assert.Equal(3, ReciprocalArea.FromInverseSquareMicrometers(inversesquaremeter.InverseSquareMicrometers).InverseSquareMeters); + Assert.Equal(3, ReciprocalArea.FromInverseSquareMiles(inversesquaremeter.InverseSquareMiles).InverseSquareMeters); + Assert.Equal(3, ReciprocalArea.FromInverseSquareMillimeters(inversesquaremeter.InverseSquareMillimeters).InverseSquareMeters); + Assert.Equal(3, ReciprocalArea.FromInverseSquareYards(inversesquaremeter.InverseSquareYards).InverseSquareMeters); + Assert.Equal(3, ReciprocalArea.FromInverseUsSurveySquareFeet(inversesquaremeter.InverseUsSurveySquareFeet).InverseSquareMeters); } [Fact] public void ArithmeticOperators() { ReciprocalArea v = ReciprocalArea.FromInverseSquareMeters(1); - AssertEx.EqualTolerance(-1, -v.InverseSquareMeters, InverseSquareMetersTolerance); - AssertEx.EqualTolerance(2, (ReciprocalArea.FromInverseSquareMeters(3)-v).InverseSquareMeters, InverseSquareMetersTolerance); - AssertEx.EqualTolerance(2, (v + v).InverseSquareMeters, InverseSquareMetersTolerance); - AssertEx.EqualTolerance(10, (v*10).InverseSquareMeters, InverseSquareMetersTolerance); - AssertEx.EqualTolerance(10, (10*v).InverseSquareMeters, InverseSquareMetersTolerance); - AssertEx.EqualTolerance(2, (ReciprocalArea.FromInverseSquareMeters(10)/5).InverseSquareMeters, InverseSquareMetersTolerance); - AssertEx.EqualTolerance(2, ReciprocalArea.FromInverseSquareMeters(10)/ReciprocalArea.FromInverseSquareMeters(5), InverseSquareMetersTolerance); + Assert.Equal(-1, -v.InverseSquareMeters); + Assert.Equal(2, (ReciprocalArea.FromInverseSquareMeters(3) - v).InverseSquareMeters); + Assert.Equal(2, (v + v).InverseSquareMeters); + Assert.Equal(10, (v * 10).InverseSquareMeters); + Assert.Equal(10, (10 * v).InverseSquareMeters); + Assert.Equal(2, (ReciprocalArea.FromInverseSquareMeters(10) / 5).InverseSquareMeters); + Assert.Equal(2, ReciprocalArea.FromInverseSquareMeters(10) / ReciprocalArea.FromInverseSquareMeters(5)); } [Fact] @@ -693,8 +710,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ReciprocalAreaUnit.InverseSquareMeter, 1, ReciprocalAreaUnit.InverseSquareMeter, true)] // Same value and unit. [InlineData(1, ReciprocalAreaUnit.InverseSquareMeter, 2, ReciprocalAreaUnit.InverseSquareMeter, false)] // Different value. - [InlineData(2, ReciprocalAreaUnit.InverseSquareMeter, 1, ReciprocalAreaUnit.InverseSquareCentimeter, false)] // Different value and unit. - [InlineData(1, ReciprocalAreaUnit.InverseSquareMeter, 1, ReciprocalAreaUnit.InverseSquareCentimeter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ReciprocalAreaUnit unitA, double valueB, ReciprocalAreaUnit unitB, bool expectEqual) { var a = new ReciprocalArea(valueA, unitA); @@ -754,8 +769,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ReciprocalArea.FromInverseSquareMeters(firstValue); var otherQuantity = ReciprocalArea.FromInverseSquareMeters(secondValue); ReciprocalArea maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ReciprocalArea.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -774,7 +789,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -787,6 +802,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ReciprocalArea.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ReciprocalArea.Info.Units, ReciprocalArea.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ReciprocalArea.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -869,7 +896,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ReciprocalArea.FromInverseSquareMeters(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ReciprocalArea), quantity.As(ReciprocalArea.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs index 79fa55a38e..61e8c34ec1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ReciprocalLengthTestsBase.g.cs @@ -161,6 +161,20 @@ public void ReciprocalLength_QuantityInfo_ReturnsQuantityInfoDescribingQuantity( Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ReciprocalLengthInfo_CreateWithCustomUnitInfos() + { + ReciprocalLengthUnit[] expectedUnits = [ReciprocalLengthUnit.InverseMeter]; + + ReciprocalLength.ReciprocalLengthInfo quantityInfo = ReciprocalLength.ReciprocalLengthInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ReciprocalLength", quantityInfo.Name); + Assert.Equal(ReciprocalLength.Zero, quantityInfo.Zero); + Assert.Equal(ReciprocalLength.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void InverseMeterToReciprocalLengthUnits() { @@ -349,7 +363,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 1/ftUS", ReciprocalLengthUnit.InverseUsSurveyFoot, 4.2)] [InlineData("en-US", "4.2 yd⁻¹", ReciprocalLengthUnit.InverseYard, 4.2)] [InlineData("en-US", "4.2 1/yd", ReciprocalLengthUnit.InverseYard, 4.2)] - public void Parse(string culture, string quantityString, ReciprocalLengthUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ReciprocalLengthUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ReciprocalLength.Parse(quantityString); @@ -378,7 +392,7 @@ public void Parse(string culture, string quantityString, ReciprocalLengthUnit ex [InlineData("en-US", "4.2 1/ftUS", ReciprocalLengthUnit.InverseUsSurveyFoot, 4.2)] [InlineData("en-US", "4.2 yd⁻¹", ReciprocalLengthUnit.InverseYard, 4.2)] [InlineData("en-US", "4.2 1/yd", ReciprocalLengthUnit.InverseYard, 4.2)] - public void TryParse(string culture, string quantityString, ReciprocalLengthUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ReciprocalLengthUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ReciprocalLength.TryParse(quantityString, out ReciprocalLength parsed)); @@ -672,6 +686,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ReciprocalLength var quantity = ReciprocalLength.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -695,41 +710,43 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ReciprocalLengthUni IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ReciprocalLength inversemeter = ReciprocalLength.FromInverseMeters(1); - AssertEx.EqualTolerance(1, ReciprocalLength.FromInverseCentimeters(inversemeter.InverseCentimeters).InverseMeters, InverseCentimetersTolerance); - AssertEx.EqualTolerance(1, ReciprocalLength.FromInverseFeet(inversemeter.InverseFeet).InverseMeters, InverseFeetTolerance); - AssertEx.EqualTolerance(1, ReciprocalLength.FromInverseInches(inversemeter.InverseInches).InverseMeters, InverseInchesTolerance); - AssertEx.EqualTolerance(1, ReciprocalLength.FromInverseMeters(inversemeter.InverseMeters).InverseMeters, InverseMetersTolerance); - AssertEx.EqualTolerance(1, ReciprocalLength.FromInverseMicroinches(inversemeter.InverseMicroinches).InverseMeters, InverseMicroinchesTolerance); - AssertEx.EqualTolerance(1, ReciprocalLength.FromInverseMils(inversemeter.InverseMils).InverseMeters, InverseMilsTolerance); - AssertEx.EqualTolerance(1, ReciprocalLength.FromInverseMiles(inversemeter.InverseMiles).InverseMeters, InverseMilesTolerance); - AssertEx.EqualTolerance(1, ReciprocalLength.FromInverseMillimeters(inversemeter.InverseMillimeters).InverseMeters, InverseMillimetersTolerance); - AssertEx.EqualTolerance(1, ReciprocalLength.FromInverseUsSurveyFeet(inversemeter.InverseUsSurveyFeet).InverseMeters, InverseUsSurveyFeetTolerance); - AssertEx.EqualTolerance(1, ReciprocalLength.FromInverseYards(inversemeter.InverseYards).InverseMeters, InverseYardsTolerance); + ReciprocalLength inversemeter = ReciprocalLength.FromInverseMeters(3); + Assert.Equal(3, ReciprocalLength.FromInverseCentimeters(inversemeter.InverseCentimeters).InverseMeters); + Assert.Equal(3, ReciprocalLength.FromInverseFeet(inversemeter.InverseFeet).InverseMeters); + Assert.Equal(3, ReciprocalLength.FromInverseInches(inversemeter.InverseInches).InverseMeters); + Assert.Equal(3, ReciprocalLength.FromInverseMeters(inversemeter.InverseMeters).InverseMeters); + Assert.Equal(3, ReciprocalLength.FromInverseMicroinches(inversemeter.InverseMicroinches).InverseMeters); + Assert.Equal(3, ReciprocalLength.FromInverseMils(inversemeter.InverseMils).InverseMeters); + Assert.Equal(3, ReciprocalLength.FromInverseMiles(inversemeter.InverseMiles).InverseMeters); + Assert.Equal(3, ReciprocalLength.FromInverseMillimeters(inversemeter.InverseMillimeters).InverseMeters); + Assert.Equal(3, ReciprocalLength.FromInverseUsSurveyFeet(inversemeter.InverseUsSurveyFeet).InverseMeters); + Assert.Equal(3, ReciprocalLength.FromInverseYards(inversemeter.InverseYards).InverseMeters); } [Fact] public void ArithmeticOperators() { ReciprocalLength v = ReciprocalLength.FromInverseMeters(1); - AssertEx.EqualTolerance(-1, -v.InverseMeters, InverseMetersTolerance); - AssertEx.EqualTolerance(2, (ReciprocalLength.FromInverseMeters(3)-v).InverseMeters, InverseMetersTolerance); - AssertEx.EqualTolerance(2, (v + v).InverseMeters, InverseMetersTolerance); - AssertEx.EqualTolerance(10, (v*10).InverseMeters, InverseMetersTolerance); - AssertEx.EqualTolerance(10, (10*v).InverseMeters, InverseMetersTolerance); - AssertEx.EqualTolerance(2, (ReciprocalLength.FromInverseMeters(10)/5).InverseMeters, InverseMetersTolerance); - AssertEx.EqualTolerance(2, ReciprocalLength.FromInverseMeters(10)/ReciprocalLength.FromInverseMeters(5), InverseMetersTolerance); + Assert.Equal(-1, -v.InverseMeters); + Assert.Equal(2, (ReciprocalLength.FromInverseMeters(3) - v).InverseMeters); + Assert.Equal(2, (v + v).InverseMeters); + Assert.Equal(10, (v * 10).InverseMeters); + Assert.Equal(10, (10 * v).InverseMeters); + Assert.Equal(2, (ReciprocalLength.FromInverseMeters(10) / 5).InverseMeters); + Assert.Equal(2, ReciprocalLength.FromInverseMeters(10) / ReciprocalLength.FromInverseMeters(5)); } [Fact] @@ -775,8 +792,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ReciprocalLengthUnit.InverseMeter, 1, ReciprocalLengthUnit.InverseMeter, true)] // Same value and unit. [InlineData(1, ReciprocalLengthUnit.InverseMeter, 2, ReciprocalLengthUnit.InverseMeter, false)] // Different value. - [InlineData(2, ReciprocalLengthUnit.InverseMeter, 1, ReciprocalLengthUnit.InverseCentimeter, false)] // Different value and unit. - [InlineData(1, ReciprocalLengthUnit.InverseMeter, 1, ReciprocalLengthUnit.InverseCentimeter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ReciprocalLengthUnit unitA, double valueB, ReciprocalLengthUnit unitB, bool expectEqual) { var a = new ReciprocalLength(valueA, unitA); @@ -836,8 +851,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ReciprocalLength.FromInverseMeters(firstValue); var otherQuantity = ReciprocalLength.FromInverseMeters(secondValue); ReciprocalLength maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ReciprocalLength.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -856,7 +871,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -869,6 +884,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ReciprocalLength.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ReciprocalLength.Info.Units, ReciprocalLength.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ReciprocalLength.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -949,7 +976,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ReciprocalLength.FromInverseMeters(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ReciprocalLength), quantity.As(ReciprocalLength.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs index eb2dfe961c..090de16e55 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RelativeHumidityTestsBase.g.cs @@ -104,6 +104,20 @@ public void RelativeHumidity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity( Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void RelativeHumidityInfo_CreateWithCustomUnitInfos() + { + RelativeHumidityUnit[] expectedUnits = [RelativeHumidityUnit.Percent]; + + RelativeHumidity.RelativeHumidityInfo quantityInfo = RelativeHumidity.RelativeHumidityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("RelativeHumidity", quantityInfo.Name); + Assert.Equal(RelativeHumidity.Zero, quantityInfo.Zero); + Assert.Equal(RelativeHumidity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void PercentToRelativeHumidityUnits() { @@ -216,7 +230,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() [Theory] [InlineData("en-US", "4.2 %RH", RelativeHumidityUnit.Percent, 4.2)] - public void Parse(string culture, string quantityString, RelativeHumidityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, RelativeHumidityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = RelativeHumidity.Parse(quantityString); @@ -226,7 +240,7 @@ public void Parse(string culture, string quantityString, RelativeHumidityUnit ex [Theory] [InlineData("en-US", "4.2 %RH", RelativeHumidityUnit.Percent, 4.2)] - public void TryParse(string culture, string quantityString, RelativeHumidityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, RelativeHumidityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(RelativeHumidity.TryParse(quantityString, out RelativeHumidity parsed)); @@ -359,6 +373,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RelativeHumidity var quantity = RelativeHumidity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -382,32 +397,34 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(RelativeHumidityUni IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - RelativeHumidity percent = RelativeHumidity.FromPercent(1); - AssertEx.EqualTolerance(1, RelativeHumidity.FromPercent(percent.Percent).Percent, PercentTolerance); + RelativeHumidity percent = RelativeHumidity.FromPercent(3); + Assert.Equal(3, RelativeHumidity.FromPercent(percent.Percent).Percent); } [Fact] public void ArithmeticOperators() { RelativeHumidity v = RelativeHumidity.FromPercent(1); - AssertEx.EqualTolerance(-1, -v.Percent, PercentTolerance); - AssertEx.EqualTolerance(2, (RelativeHumidity.FromPercent(3)-v).Percent, PercentTolerance); - AssertEx.EqualTolerance(2, (v + v).Percent, PercentTolerance); - AssertEx.EqualTolerance(10, (v*10).Percent, PercentTolerance); - AssertEx.EqualTolerance(10, (10*v).Percent, PercentTolerance); - AssertEx.EqualTolerance(2, (RelativeHumidity.FromPercent(10)/5).Percent, PercentTolerance); - AssertEx.EqualTolerance(2, RelativeHumidity.FromPercent(10)/RelativeHumidity.FromPercent(5), PercentTolerance); + Assert.Equal(-1, -v.Percent); + Assert.Equal(2, (RelativeHumidity.FromPercent(3) - v).Percent); + Assert.Equal(2, (v + v).Percent); + Assert.Equal(10, (v * 10).Percent); + Assert.Equal(10, (10 * v).Percent); + Assert.Equal(2, (RelativeHumidity.FromPercent(10) / 5).Percent); + Assert.Equal(2, RelativeHumidity.FromPercent(10) / RelativeHumidity.FromPercent(5)); } [Fact] @@ -453,7 +470,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, RelativeHumidityUnit.Percent, 1, RelativeHumidityUnit.Percent, true)] // Same value and unit. [InlineData(1, RelativeHumidityUnit.Percent, 2, RelativeHumidityUnit.Percent, false)] // Different value. - [InlineData(2, RelativeHumidityUnit.Percent, 1, RelativeHumidityUnit.Percent, false)] // Different value and unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, RelativeHumidityUnit unitA, double valueB, RelativeHumidityUnit unitB, bool expectEqual) { var a = new RelativeHumidity(valueA, unitA); @@ -513,8 +529,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = RelativeHumidity.FromPercent(firstValue); var otherQuantity = RelativeHumidity.FromPercent(secondValue); RelativeHumidity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, RelativeHumidity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -533,7 +549,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -546,6 +562,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(RelativeHumidity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(RelativeHumidity.Info.Units, RelativeHumidity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, RelativeHumidity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -608,7 +636,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = RelativeHumidity.FromPercent(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(RelativeHumidity), quantity.As(RelativeHumidity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs index 03fa7f54df..ad34cfdc24 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalAccelerationTestsBase.g.cs @@ -137,6 +137,20 @@ public void RotationalAcceleration_QuantityInfo_ReturnsQuantityInfoDescribingQua Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void RotationalAccelerationInfo_CreateWithCustomUnitInfos() + { + RotationalAccelerationUnit[] expectedUnits = [RotationalAccelerationUnit.RadianPerSecondSquared]; + + RotationalAcceleration.RotationalAccelerationInfo quantityInfo = RotationalAcceleration.RotationalAccelerationInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("RotationalAcceleration", quantityInfo.Name); + Assert.Equal(RotationalAcceleration.Zero, quantityInfo.Zero); + Assert.Equal(RotationalAcceleration.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void RadianPerSecondSquaredToRotationalAccelerationUnits() { @@ -298,7 +312,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 rad/s²", RotationalAccelerationUnit.RadianPerSecondSquared, 4.2)] [InlineData("en-US", "4.2 rpm/s", RotationalAccelerationUnit.RevolutionPerMinutePerSecond, 4.2)] [InlineData("en-US", "4.2 r/s²", RotationalAccelerationUnit.RevolutionPerSecondSquared, 4.2)] - public void Parse(string culture, string quantityString, RotationalAccelerationUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, RotationalAccelerationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = RotationalAcceleration.Parse(quantityString); @@ -312,7 +326,7 @@ public void Parse(string culture, string quantityString, RotationalAccelerationU [InlineData("en-US", "4.2 rad/s²", RotationalAccelerationUnit.RadianPerSecondSquared, 4.2)] [InlineData("en-US", "4.2 rpm/s", RotationalAccelerationUnit.RevolutionPerMinutePerSecond, 4.2)] [InlineData("en-US", "4.2 r/s²", RotationalAccelerationUnit.RevolutionPerSecondSquared, 4.2)] - public void TryParse(string culture, string quantityString, RotationalAccelerationUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, RotationalAccelerationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(RotationalAcceleration.TryParse(quantityString, out RotationalAcceleration parsed)); @@ -480,6 +494,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RotationalAccele var quantity = RotationalAcceleration.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -503,35 +518,37 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(RotationalAccelerat IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - RotationalAcceleration radianpersecondsquared = RotationalAcceleration.FromRadiansPerSecondSquared(1); - AssertEx.EqualTolerance(1, RotationalAcceleration.FromDegreesPerSecondSquared(radianpersecondsquared.DegreesPerSecondSquared).RadiansPerSecondSquared, DegreesPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, RotationalAcceleration.FromRadiansPerSecondSquared(radianpersecondsquared.RadiansPerSecondSquared).RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - AssertEx.EqualTolerance(1, RotationalAcceleration.FromRevolutionsPerMinutePerSecond(radianpersecondsquared.RevolutionsPerMinutePerSecond).RadiansPerSecondSquared, RevolutionsPerMinutePerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalAcceleration.FromRevolutionsPerSecondSquared(radianpersecondsquared.RevolutionsPerSecondSquared).RadiansPerSecondSquared, RevolutionsPerSecondSquaredTolerance); + RotationalAcceleration radianpersecondsquared = RotationalAcceleration.FromRadiansPerSecondSquared(3); + Assert.Equal(3, RotationalAcceleration.FromDegreesPerSecondSquared(radianpersecondsquared.DegreesPerSecondSquared).RadiansPerSecondSquared); + Assert.Equal(3, RotationalAcceleration.FromRadiansPerSecondSquared(radianpersecondsquared.RadiansPerSecondSquared).RadiansPerSecondSquared); + Assert.Equal(3, RotationalAcceleration.FromRevolutionsPerMinutePerSecond(radianpersecondsquared.RevolutionsPerMinutePerSecond).RadiansPerSecondSquared); + Assert.Equal(3, RotationalAcceleration.FromRevolutionsPerSecondSquared(radianpersecondsquared.RevolutionsPerSecondSquared).RadiansPerSecondSquared); } [Fact] public void ArithmeticOperators() { RotationalAcceleration v = RotationalAcceleration.FromRadiansPerSecondSquared(1); - AssertEx.EqualTolerance(-1, -v.RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - AssertEx.EqualTolerance(2, (RotationalAcceleration.FromRadiansPerSecondSquared(3)-v).RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - AssertEx.EqualTolerance(2, (v + v).RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - AssertEx.EqualTolerance(10, (v*10).RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - AssertEx.EqualTolerance(10, (10*v).RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - AssertEx.EqualTolerance(2, (RotationalAcceleration.FromRadiansPerSecondSquared(10)/5).RadiansPerSecondSquared, RadiansPerSecondSquaredTolerance); - AssertEx.EqualTolerance(2, RotationalAcceleration.FromRadiansPerSecondSquared(10)/RotationalAcceleration.FromRadiansPerSecondSquared(5), RadiansPerSecondSquaredTolerance); + Assert.Equal(-1, -v.RadiansPerSecondSquared); + Assert.Equal(2, (RotationalAcceleration.FromRadiansPerSecondSquared(3) - v).RadiansPerSecondSquared); + Assert.Equal(2, (v + v).RadiansPerSecondSquared); + Assert.Equal(10, (v * 10).RadiansPerSecondSquared); + Assert.Equal(10, (10 * v).RadiansPerSecondSquared); + Assert.Equal(2, (RotationalAcceleration.FromRadiansPerSecondSquared(10) / 5).RadiansPerSecondSquared); + Assert.Equal(2, RotationalAcceleration.FromRadiansPerSecondSquared(10) / RotationalAcceleration.FromRadiansPerSecondSquared(5)); } [Fact] @@ -577,8 +594,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, RotationalAccelerationUnit.RadianPerSecondSquared, 1, RotationalAccelerationUnit.RadianPerSecondSquared, true)] // Same value and unit. [InlineData(1, RotationalAccelerationUnit.RadianPerSecondSquared, 2, RotationalAccelerationUnit.RadianPerSecondSquared, false)] // Different value. - [InlineData(2, RotationalAccelerationUnit.RadianPerSecondSquared, 1, RotationalAccelerationUnit.DegreePerSecondSquared, false)] // Different value and unit. - [InlineData(1, RotationalAccelerationUnit.RadianPerSecondSquared, 1, RotationalAccelerationUnit.DegreePerSecondSquared, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, RotationalAccelerationUnit unitA, double valueB, RotationalAccelerationUnit unitB, bool expectEqual) { var a = new RotationalAcceleration(valueA, unitA); @@ -638,8 +653,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(firstValue); var otherQuantity = RotationalAcceleration.FromRadiansPerSecondSquared(secondValue); RotationalAcceleration maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, RotationalAcceleration.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -658,7 +673,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -671,6 +686,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(RotationalAcceleration.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(RotationalAcceleration.Info.Units, RotationalAcceleration.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, RotationalAcceleration.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -739,7 +766,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = RotationalAcceleration.FromRadiansPerSecondSquared(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(RotationalAcceleration), quantity.As(RotationalAcceleration.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs index 1bc497f5f2..8913befd78 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalSpeedTestsBase.g.cs @@ -173,6 +173,20 @@ public void RotationalSpeed_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void RotationalSpeedInfo_CreateWithCustomUnitInfos() + { + RotationalSpeedUnit[] expectedUnits = [RotationalSpeedUnit.RadianPerSecond]; + + RotationalSpeed.RotationalSpeedInfo quantityInfo = RotationalSpeed.RotationalSpeedInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("RotationalSpeed", quantityInfo.Name); + Assert.Equal(RotationalSpeed.Zero, quantityInfo.Zero); + Assert.Equal(RotationalSpeed.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void RadianPerSecondToRotationalSpeedUnits() { @@ -378,7 +392,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 рад/с", RotationalSpeedUnit.RadianPerSecond, 4.2)] [InlineData("ru-RU", "4,2 об/мин", RotationalSpeedUnit.RevolutionPerMinute, 4.2)] [InlineData("ru-RU", "4,2 об/с", RotationalSpeedUnit.RevolutionPerSecond, 4.2)] - public void Parse(string culture, string quantityString, RotationalSpeedUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, RotationalSpeedUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = RotationalSpeed.Parse(quantityString); @@ -418,7 +432,7 @@ public void Parse(string culture, string quantityString, RotationalSpeedUnit exp [InlineData("ru-RU", "4,2 рад/с", RotationalSpeedUnit.RadianPerSecond, 4.2)] [InlineData("ru-RU", "4,2 об/мин", RotationalSpeedUnit.RevolutionPerMinute, 4.2)] [InlineData("ru-RU", "4,2 об/с", RotationalSpeedUnit.RevolutionPerSecond, 4.2)] - public void TryParse(string culture, string quantityString, RotationalSpeedUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, RotationalSpeedUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(RotationalSpeed.TryParse(quantityString, out RotationalSpeed parsed)); @@ -767,6 +781,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RotationalSpeedU var quantity = RotationalSpeed.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -790,44 +805,46 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(RotationalSpeedUnit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - RotationalSpeed radianpersecond = RotationalSpeed.FromRadiansPerSecond(1); - AssertEx.EqualTolerance(1, RotationalSpeed.FromCentiradiansPerSecond(radianpersecond.CentiradiansPerSecond).RadiansPerSecond, CentiradiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromDeciradiansPerSecond(radianpersecond.DeciradiansPerSecond).RadiansPerSecond, DeciradiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromDegreesPerMinute(radianpersecond.DegreesPerMinute).RadiansPerSecond, DegreesPerMinuteTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromDegreesPerSecond(radianpersecond.DegreesPerSecond).RadiansPerSecond, DegreesPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromMicrodegreesPerSecond(radianpersecond.MicrodegreesPerSecond).RadiansPerSecond, MicrodegreesPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromMicroradiansPerSecond(radianpersecond.MicroradiansPerSecond).RadiansPerSecond, MicroradiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromMillidegreesPerSecond(radianpersecond.MillidegreesPerSecond).RadiansPerSecond, MillidegreesPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromMilliradiansPerSecond(radianpersecond.MilliradiansPerSecond).RadiansPerSecond, MilliradiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromNanodegreesPerSecond(radianpersecond.NanodegreesPerSecond).RadiansPerSecond, NanodegreesPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromNanoradiansPerSecond(radianpersecond.NanoradiansPerSecond).RadiansPerSecond, NanoradiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromRadiansPerSecond(radianpersecond.RadiansPerSecond).RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromRevolutionsPerMinute(radianpersecond.RevolutionsPerMinute).RadiansPerSecond, RevolutionsPerMinuteTolerance); - AssertEx.EqualTolerance(1, RotationalSpeed.FromRevolutionsPerSecond(radianpersecond.RevolutionsPerSecond).RadiansPerSecond, RevolutionsPerSecondTolerance); + RotationalSpeed radianpersecond = RotationalSpeed.FromRadiansPerSecond(3); + Assert.Equal(3, RotationalSpeed.FromCentiradiansPerSecond(radianpersecond.CentiradiansPerSecond).RadiansPerSecond); + Assert.Equal(3, RotationalSpeed.FromDeciradiansPerSecond(radianpersecond.DeciradiansPerSecond).RadiansPerSecond); + Assert.Equal(3, RotationalSpeed.FromDegreesPerMinute(radianpersecond.DegreesPerMinute).RadiansPerSecond); + Assert.Equal(3, RotationalSpeed.FromDegreesPerSecond(radianpersecond.DegreesPerSecond).RadiansPerSecond); + Assert.Equal(3, RotationalSpeed.FromMicrodegreesPerSecond(radianpersecond.MicrodegreesPerSecond).RadiansPerSecond); + Assert.Equal(3, RotationalSpeed.FromMicroradiansPerSecond(radianpersecond.MicroradiansPerSecond).RadiansPerSecond); + Assert.Equal(3, RotationalSpeed.FromMillidegreesPerSecond(radianpersecond.MillidegreesPerSecond).RadiansPerSecond); + Assert.Equal(3, RotationalSpeed.FromMilliradiansPerSecond(radianpersecond.MilliradiansPerSecond).RadiansPerSecond); + Assert.Equal(3, RotationalSpeed.FromNanodegreesPerSecond(radianpersecond.NanodegreesPerSecond).RadiansPerSecond); + Assert.Equal(3, RotationalSpeed.FromNanoradiansPerSecond(radianpersecond.NanoradiansPerSecond).RadiansPerSecond); + Assert.Equal(3, RotationalSpeed.FromRadiansPerSecond(radianpersecond.RadiansPerSecond).RadiansPerSecond); + Assert.Equal(3, RotationalSpeed.FromRevolutionsPerMinute(radianpersecond.RevolutionsPerMinute).RadiansPerSecond); + Assert.Equal(3, RotationalSpeed.FromRevolutionsPerSecond(radianpersecond.RevolutionsPerSecond).RadiansPerSecond); } [Fact] public void ArithmeticOperators() { RotationalSpeed v = RotationalSpeed.FromRadiansPerSecond(1); - AssertEx.EqualTolerance(-1, -v.RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(2, (RotationalSpeed.FromRadiansPerSecond(3)-v).RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(2, (RotationalSpeed.FromRadiansPerSecond(10)/5).RadiansPerSecond, RadiansPerSecondTolerance); - AssertEx.EqualTolerance(2, RotationalSpeed.FromRadiansPerSecond(10)/RotationalSpeed.FromRadiansPerSecond(5), RadiansPerSecondTolerance); + Assert.Equal(-1, -v.RadiansPerSecond); + Assert.Equal(2, (RotationalSpeed.FromRadiansPerSecond(3) - v).RadiansPerSecond); + Assert.Equal(2, (v + v).RadiansPerSecond); + Assert.Equal(10, (v * 10).RadiansPerSecond); + Assert.Equal(10, (10 * v).RadiansPerSecond); + Assert.Equal(2, (RotationalSpeed.FromRadiansPerSecond(10) / 5).RadiansPerSecond); + Assert.Equal(2, RotationalSpeed.FromRadiansPerSecond(10) / RotationalSpeed.FromRadiansPerSecond(5)); } [Fact] @@ -873,8 +890,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, RotationalSpeedUnit.RadianPerSecond, 1, RotationalSpeedUnit.RadianPerSecond, true)] // Same value and unit. [InlineData(1, RotationalSpeedUnit.RadianPerSecond, 2, RotationalSpeedUnit.RadianPerSecond, false)] // Different value. - [InlineData(2, RotationalSpeedUnit.RadianPerSecond, 1, RotationalSpeedUnit.CentiradianPerSecond, false)] // Different value and unit. - [InlineData(1, RotationalSpeedUnit.RadianPerSecond, 1, RotationalSpeedUnit.CentiradianPerSecond, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, RotationalSpeedUnit unitA, double valueB, RotationalSpeedUnit unitB, bool expectEqual) { var a = new RotationalSpeed(valueA, unitA); @@ -934,8 +949,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = RotationalSpeed.FromRadiansPerSecond(firstValue); var otherQuantity = RotationalSpeed.FromRadiansPerSecond(secondValue); RotationalSpeed maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, RotationalSpeed.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -954,7 +969,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -967,6 +982,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(RotationalSpeed.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(RotationalSpeed.Info.Units, RotationalSpeed.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, RotationalSpeed.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1053,7 +1080,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = RotationalSpeed.FromRadiansPerSecond(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(RotationalSpeed), quantity.As(RotationalSpeed.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs index b6e31ffbf7..baa9ed699e 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessPerLengthTestsBase.g.cs @@ -141,6 +141,20 @@ public void RotationalStiffnessPerLength_QuantityInfo_ReturnsQuantityInfoDescrib Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void RotationalStiffnessPerLengthInfo_CreateWithCustomUnitInfos() + { + RotationalStiffnessPerLengthUnit[] expectedUnits = [RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter]; + + RotationalStiffnessPerLength.RotationalStiffnessPerLengthInfo quantityInfo = RotationalStiffnessPerLength.RotationalStiffnessPerLengthInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("RotationalStiffnessPerLength", quantityInfo.Name); + Assert.Equal(RotationalStiffnessPerLength.Zero, quantityInfo.Zero); + Assert.Equal(RotationalStiffnessPerLength.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void NewtonMeterPerRadianPerMeterToRotationalStiffnessPerLengthUnits() { @@ -312,7 +326,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 N·m/rad/m", RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, 4.2)] [InlineData("en-US", "4.2 Nm/rad/m", RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, 4.2)] [InlineData("en-US", "4.2 lbf·ft/deg/ft", RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, 4.2)] - public void Parse(string culture, string quantityString, RotationalStiffnessPerLengthUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, RotationalStiffnessPerLengthUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = RotationalStiffnessPerLength.Parse(quantityString); @@ -334,7 +348,7 @@ public void Parse(string culture, string quantityString, RotationalStiffnessPerL [InlineData("en-US", "4.2 N·m/rad/m", RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, 4.2)] [InlineData("en-US", "4.2 Nm/rad/m", RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, 4.2)] [InlineData("en-US", "4.2 lbf·ft/deg/ft", RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, 4.2)] - public void TryParse(string culture, string quantityString, RotationalStiffnessPerLengthUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, RotationalStiffnessPerLengthUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(RotationalStiffnessPerLength.TryParse(quantityString, out RotationalStiffnessPerLength parsed)); @@ -567,6 +581,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RotationalStiffn var quantity = RotationalStiffnessPerLength.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -590,36 +605,38 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(RotationalStiffness IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - RotationalStiffnessPerLength newtonmeterperradianpermeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - AssertEx.EqualTolerance(1, RotationalStiffnessPerLength.FromKilonewtonMetersPerRadianPerMeter(newtonmeterperradianpermeter.KilonewtonMetersPerRadianPerMeter).NewtonMetersPerRadianPerMeter, KilonewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(1, RotationalStiffnessPerLength.FromKilopoundForceFeetPerDegreesPerFeet(newtonmeterperradianpermeter.KilopoundForceFeetPerDegreesPerFeet).NewtonMetersPerRadianPerMeter, KilopoundForceFeetPerDegreesPerFeetTolerance); - AssertEx.EqualTolerance(1, RotationalStiffnessPerLength.FromMeganewtonMetersPerRadianPerMeter(newtonmeterperradianpermeter.MeganewtonMetersPerRadianPerMeter).NewtonMetersPerRadianPerMeter, MeganewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(1, RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(newtonmeterperradianpermeter.NewtonMetersPerRadianPerMeter).NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(1, RotationalStiffnessPerLength.FromPoundForceFeetPerDegreesPerFeet(newtonmeterperradianpermeter.PoundForceFeetPerDegreesPerFeet).NewtonMetersPerRadianPerMeter, PoundForceFeetPerDegreesPerFeetTolerance); + RotationalStiffnessPerLength newtonmeterperradianpermeter = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(3); + Assert.Equal(3, RotationalStiffnessPerLength.FromKilonewtonMetersPerRadianPerMeter(newtonmeterperradianpermeter.KilonewtonMetersPerRadianPerMeter).NewtonMetersPerRadianPerMeter); + Assert.Equal(3, RotationalStiffnessPerLength.FromKilopoundForceFeetPerDegreesPerFeet(newtonmeterperradianpermeter.KilopoundForceFeetPerDegreesPerFeet).NewtonMetersPerRadianPerMeter); + Assert.Equal(3, RotationalStiffnessPerLength.FromMeganewtonMetersPerRadianPerMeter(newtonmeterperradianpermeter.MeganewtonMetersPerRadianPerMeter).NewtonMetersPerRadianPerMeter); + Assert.Equal(3, RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(newtonmeterperradianpermeter.NewtonMetersPerRadianPerMeter).NewtonMetersPerRadianPerMeter); + Assert.Equal(3, RotationalStiffnessPerLength.FromPoundForceFeetPerDegreesPerFeet(newtonmeterperradianpermeter.PoundForceFeetPerDegreesPerFeet).NewtonMetersPerRadianPerMeter); } [Fact] public void ArithmeticOperators() { RotationalStiffnessPerLength v = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1); - AssertEx.EqualTolerance(-1, -v.NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(2, (RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(3)-v).NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(2, (RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(10)/5).NewtonMetersPerRadianPerMeter, NewtonMetersPerRadianPerMeterTolerance); - AssertEx.EqualTolerance(2, RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(10)/RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(5), NewtonMetersPerRadianPerMeterTolerance); + Assert.Equal(-1, -v.NewtonMetersPerRadianPerMeter); + Assert.Equal(2, (RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(3) - v).NewtonMetersPerRadianPerMeter); + Assert.Equal(2, (v + v).NewtonMetersPerRadianPerMeter); + Assert.Equal(10, (v * 10).NewtonMetersPerRadianPerMeter); + Assert.Equal(10, (10 * v).NewtonMetersPerRadianPerMeter); + Assert.Equal(2, (RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(10) / 5).NewtonMetersPerRadianPerMeter); + Assert.Equal(2, RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(10) / RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(5)); } [Fact] @@ -665,8 +682,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, 1, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, true)] // Same value and unit. [InlineData(1, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, 2, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, false)] // Different value. - [InlineData(2, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, 1, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, false)] // Different value and unit. - [InlineData(1, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, 1, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, RotationalStiffnessPerLengthUnit unitA, double valueB, RotationalStiffnessPerLengthUnit unitB, bool expectEqual) { var a = new RotationalStiffnessPerLength(valueA, unitA); @@ -726,8 +741,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(firstValue); var otherQuantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(secondValue); RotationalStiffnessPerLength maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, RotationalStiffnessPerLength.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -746,7 +761,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -759,6 +774,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(RotationalStiffnessPerLength.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(RotationalStiffnessPerLength.Info.Units, RotationalStiffnessPerLength.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, RotationalStiffnessPerLength.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -829,7 +856,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = RotationalStiffnessPerLength.FromNewtonMetersPerRadianPerMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(RotationalStiffnessPerLength), quantity.As(RotationalStiffnessPerLength.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs index 0a1a1e7914..8c240a1a91 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/RotationalStiffnessTestsBase.g.cs @@ -253,6 +253,20 @@ public void RotationalStiffness_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void RotationalStiffnessInfo_CreateWithCustomUnitInfos() + { + RotationalStiffnessUnit[] expectedUnits = [RotationalStiffnessUnit.NewtonMeterPerRadian]; + + RotationalStiffness.RotationalStiffnessInfo quantityInfo = RotationalStiffness.RotationalStiffnessInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("RotationalStiffness", quantityInfo.Name); + Assert.Equal(RotationalStiffness.Zero, quantityInfo.Zero); + Assert.Equal(RotationalStiffness.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void NewtonMeterPerRadianToRotationalStiffnessUnits() { @@ -571,7 +585,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 Nmm/rad", RotationalStiffnessUnit.NewtonMillimeterPerRadian, 4.2)] [InlineData("en-US", "4.2 lbf·ft/rad", RotationalStiffnessUnit.PoundForceFeetPerRadian, 4.2)] [InlineData("en-US", "4.2 lbf·ft/deg", RotationalStiffnessUnit.PoundForceFootPerDegrees, 4.2)] - public void Parse(string culture, string quantityString, RotationalStiffnessUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, RotationalStiffnessUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = RotationalStiffness.Parse(quantityString); @@ -684,7 +698,7 @@ public void Parse(string culture, string quantityString, RotationalStiffnessUnit [InlineData("en-US", "4.2 Nmm/rad", RotationalStiffnessUnit.NewtonMillimeterPerRadian, 4.2)] [InlineData("en-US", "4.2 lbf·ft/rad", RotationalStiffnessUnit.PoundForceFeetPerRadian, 4.2)] [InlineData("en-US", "4.2 lbf·ft/deg", RotationalStiffnessUnit.PoundForceFootPerDegrees, 4.2)] - public void TryParse(string culture, string quantityString, RotationalStiffnessUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, RotationalStiffnessUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(RotationalStiffness.TryParse(quantityString, out RotationalStiffness parsed)); @@ -1673,6 +1687,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(RotationalStiffn var quantity = RotationalStiffness.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -1696,64 +1711,66 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(RotationalStiffness IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - RotationalStiffness newtonmeterperradian = RotationalStiffness.FromNewtonMetersPerRadian(1); - AssertEx.EqualTolerance(1, RotationalStiffness.FromCentinewtonMetersPerDegree(newtonmeterperradian.CentinewtonMetersPerDegree).NewtonMetersPerRadian, CentinewtonMetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromCentinewtonMillimetersPerDegree(newtonmeterperradian.CentinewtonMillimetersPerDegree).NewtonMetersPerRadian, CentinewtonMillimetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromCentinewtonMillimetersPerRadian(newtonmeterperradian.CentinewtonMillimetersPerRadian).NewtonMetersPerRadian, CentinewtonMillimetersPerRadianTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromDecanewtonMetersPerDegree(newtonmeterperradian.DecanewtonMetersPerDegree).NewtonMetersPerRadian, DecanewtonMetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromDecanewtonMillimetersPerDegree(newtonmeterperradian.DecanewtonMillimetersPerDegree).NewtonMetersPerRadian, DecanewtonMillimetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromDecanewtonMillimetersPerRadian(newtonmeterperradian.DecanewtonMillimetersPerRadian).NewtonMetersPerRadian, DecanewtonMillimetersPerRadianTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromDecinewtonMetersPerDegree(newtonmeterperradian.DecinewtonMetersPerDegree).NewtonMetersPerRadian, DecinewtonMetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromDecinewtonMillimetersPerDegree(newtonmeterperradian.DecinewtonMillimetersPerDegree).NewtonMetersPerRadian, DecinewtonMillimetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromDecinewtonMillimetersPerRadian(newtonmeterperradian.DecinewtonMillimetersPerRadian).NewtonMetersPerRadian, DecinewtonMillimetersPerRadianTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromKilonewtonMetersPerDegree(newtonmeterperradian.KilonewtonMetersPerDegree).NewtonMetersPerRadian, KilonewtonMetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromKilonewtonMetersPerRadian(newtonmeterperradian.KilonewtonMetersPerRadian).NewtonMetersPerRadian, KilonewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromKilonewtonMillimetersPerDegree(newtonmeterperradian.KilonewtonMillimetersPerDegree).NewtonMetersPerRadian, KilonewtonMillimetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromKilonewtonMillimetersPerRadian(newtonmeterperradian.KilonewtonMillimetersPerRadian).NewtonMetersPerRadian, KilonewtonMillimetersPerRadianTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromKilopoundForceFeetPerDegrees(newtonmeterperradian.KilopoundForceFeetPerDegrees).NewtonMetersPerRadian, KilopoundForceFeetPerDegreesTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromMeganewtonMetersPerDegree(newtonmeterperradian.MeganewtonMetersPerDegree).NewtonMetersPerRadian, MeganewtonMetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromMeganewtonMetersPerRadian(newtonmeterperradian.MeganewtonMetersPerRadian).NewtonMetersPerRadian, MeganewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromMeganewtonMillimetersPerDegree(newtonmeterperradian.MeganewtonMillimetersPerDegree).NewtonMetersPerRadian, MeganewtonMillimetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromMeganewtonMillimetersPerRadian(newtonmeterperradian.MeganewtonMillimetersPerRadian).NewtonMetersPerRadian, MeganewtonMillimetersPerRadianTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromMicronewtonMetersPerDegree(newtonmeterperradian.MicronewtonMetersPerDegree).NewtonMetersPerRadian, MicronewtonMetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromMicronewtonMillimetersPerDegree(newtonmeterperradian.MicronewtonMillimetersPerDegree).NewtonMetersPerRadian, MicronewtonMillimetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromMicronewtonMillimetersPerRadian(newtonmeterperradian.MicronewtonMillimetersPerRadian).NewtonMetersPerRadian, MicronewtonMillimetersPerRadianTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromMillinewtonMetersPerDegree(newtonmeterperradian.MillinewtonMetersPerDegree).NewtonMetersPerRadian, MillinewtonMetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromMillinewtonMillimetersPerDegree(newtonmeterperradian.MillinewtonMillimetersPerDegree).NewtonMetersPerRadian, MillinewtonMillimetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromMillinewtonMillimetersPerRadian(newtonmeterperradian.MillinewtonMillimetersPerRadian).NewtonMetersPerRadian, MillinewtonMillimetersPerRadianTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromNanonewtonMetersPerDegree(newtonmeterperradian.NanonewtonMetersPerDegree).NewtonMetersPerRadian, NanonewtonMetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromNanonewtonMillimetersPerDegree(newtonmeterperradian.NanonewtonMillimetersPerDegree).NewtonMetersPerRadian, NanonewtonMillimetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromNanonewtonMillimetersPerRadian(newtonmeterperradian.NanonewtonMillimetersPerRadian).NewtonMetersPerRadian, NanonewtonMillimetersPerRadianTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromNewtonMetersPerDegree(newtonmeterperradian.NewtonMetersPerDegree).NewtonMetersPerRadian, NewtonMetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromNewtonMetersPerRadian(newtonmeterperradian.NewtonMetersPerRadian).NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromNewtonMillimetersPerDegree(newtonmeterperradian.NewtonMillimetersPerDegree).NewtonMetersPerRadian, NewtonMillimetersPerDegreeTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromNewtonMillimetersPerRadian(newtonmeterperradian.NewtonMillimetersPerRadian).NewtonMetersPerRadian, NewtonMillimetersPerRadianTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromPoundForceFeetPerRadian(newtonmeterperradian.PoundForceFeetPerRadian).NewtonMetersPerRadian, PoundForceFeetPerRadianTolerance); - AssertEx.EqualTolerance(1, RotationalStiffness.FromPoundForceFeetPerDegrees(newtonmeterperradian.PoundForceFeetPerDegrees).NewtonMetersPerRadian, PoundForceFeetPerDegreesTolerance); + RotationalStiffness newtonmeterperradian = RotationalStiffness.FromNewtonMetersPerRadian(3); + Assert.Equal(3, RotationalStiffness.FromCentinewtonMetersPerDegree(newtonmeterperradian.CentinewtonMetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromCentinewtonMillimetersPerDegree(newtonmeterperradian.CentinewtonMillimetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromCentinewtonMillimetersPerRadian(newtonmeterperradian.CentinewtonMillimetersPerRadian).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromDecanewtonMetersPerDegree(newtonmeterperradian.DecanewtonMetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromDecanewtonMillimetersPerDegree(newtonmeterperradian.DecanewtonMillimetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromDecanewtonMillimetersPerRadian(newtonmeterperradian.DecanewtonMillimetersPerRadian).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromDecinewtonMetersPerDegree(newtonmeterperradian.DecinewtonMetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromDecinewtonMillimetersPerDegree(newtonmeterperradian.DecinewtonMillimetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromDecinewtonMillimetersPerRadian(newtonmeterperradian.DecinewtonMillimetersPerRadian).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromKilonewtonMetersPerDegree(newtonmeterperradian.KilonewtonMetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromKilonewtonMetersPerRadian(newtonmeterperradian.KilonewtonMetersPerRadian).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromKilonewtonMillimetersPerDegree(newtonmeterperradian.KilonewtonMillimetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromKilonewtonMillimetersPerRadian(newtonmeterperradian.KilonewtonMillimetersPerRadian).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromKilopoundForceFeetPerDegrees(newtonmeterperradian.KilopoundForceFeetPerDegrees).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromMeganewtonMetersPerDegree(newtonmeterperradian.MeganewtonMetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromMeganewtonMetersPerRadian(newtonmeterperradian.MeganewtonMetersPerRadian).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromMeganewtonMillimetersPerDegree(newtonmeterperradian.MeganewtonMillimetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromMeganewtonMillimetersPerRadian(newtonmeterperradian.MeganewtonMillimetersPerRadian).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromMicronewtonMetersPerDegree(newtonmeterperradian.MicronewtonMetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromMicronewtonMillimetersPerDegree(newtonmeterperradian.MicronewtonMillimetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromMicronewtonMillimetersPerRadian(newtonmeterperradian.MicronewtonMillimetersPerRadian).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromMillinewtonMetersPerDegree(newtonmeterperradian.MillinewtonMetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromMillinewtonMillimetersPerDegree(newtonmeterperradian.MillinewtonMillimetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromMillinewtonMillimetersPerRadian(newtonmeterperradian.MillinewtonMillimetersPerRadian).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromNanonewtonMetersPerDegree(newtonmeterperradian.NanonewtonMetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromNanonewtonMillimetersPerDegree(newtonmeterperradian.NanonewtonMillimetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromNanonewtonMillimetersPerRadian(newtonmeterperradian.NanonewtonMillimetersPerRadian).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromNewtonMetersPerDegree(newtonmeterperradian.NewtonMetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromNewtonMetersPerRadian(newtonmeterperradian.NewtonMetersPerRadian).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromNewtonMillimetersPerDegree(newtonmeterperradian.NewtonMillimetersPerDegree).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromNewtonMillimetersPerRadian(newtonmeterperradian.NewtonMillimetersPerRadian).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromPoundForceFeetPerRadian(newtonmeterperradian.PoundForceFeetPerRadian).NewtonMetersPerRadian); + Assert.Equal(3, RotationalStiffness.FromPoundForceFeetPerDegrees(newtonmeterperradian.PoundForceFeetPerDegrees).NewtonMetersPerRadian); } [Fact] public void ArithmeticOperators() { RotationalStiffness v = RotationalStiffness.FromNewtonMetersPerRadian(1); - AssertEx.EqualTolerance(-1, -v.NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(2, (RotationalStiffness.FromNewtonMetersPerRadian(3)-v).NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(2, (v + v).NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(10, (v*10).NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(10, (10*v).NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(2, (RotationalStiffness.FromNewtonMetersPerRadian(10)/5).NewtonMetersPerRadian, NewtonMetersPerRadianTolerance); - AssertEx.EqualTolerance(2, RotationalStiffness.FromNewtonMetersPerRadian(10)/RotationalStiffness.FromNewtonMetersPerRadian(5), NewtonMetersPerRadianTolerance); + Assert.Equal(-1, -v.NewtonMetersPerRadian); + Assert.Equal(2, (RotationalStiffness.FromNewtonMetersPerRadian(3) - v).NewtonMetersPerRadian); + Assert.Equal(2, (v + v).NewtonMetersPerRadian); + Assert.Equal(10, (v * 10).NewtonMetersPerRadian); + Assert.Equal(10, (10 * v).NewtonMetersPerRadian); + Assert.Equal(2, (RotationalStiffness.FromNewtonMetersPerRadian(10) / 5).NewtonMetersPerRadian); + Assert.Equal(2, RotationalStiffness.FromNewtonMetersPerRadian(10) / RotationalStiffness.FromNewtonMetersPerRadian(5)); } [Fact] @@ -1799,8 +1816,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, RotationalStiffnessUnit.NewtonMeterPerRadian, 1, RotationalStiffnessUnit.NewtonMeterPerRadian, true)] // Same value and unit. [InlineData(1, RotationalStiffnessUnit.NewtonMeterPerRadian, 2, RotationalStiffnessUnit.NewtonMeterPerRadian, false)] // Different value. - [InlineData(2, RotationalStiffnessUnit.NewtonMeterPerRadian, 1, RotationalStiffnessUnit.CentinewtonMeterPerDegree, false)] // Different value and unit. - [InlineData(1, RotationalStiffnessUnit.NewtonMeterPerRadian, 1, RotationalStiffnessUnit.CentinewtonMeterPerDegree, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, RotationalStiffnessUnit unitA, double valueB, RotationalStiffnessUnit unitB, bool expectEqual) { var a = new RotationalStiffness(valueA, unitA); @@ -1860,8 +1875,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = RotationalStiffness.FromNewtonMetersPerRadian(firstValue); var otherQuantity = RotationalStiffness.FromNewtonMetersPerRadian(secondValue); RotationalStiffness maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, RotationalStiffness.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1880,7 +1895,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1893,6 +1908,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(RotationalStiffness.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(RotationalStiffness.Info.Units, RotationalStiffness.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, RotationalStiffness.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -2019,7 +2046,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = RotationalStiffness.FromNewtonMetersPerRadian(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(RotationalStiffness), quantity.As(RotationalStiffness.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs index 7c06184d2f..ed0e955e0f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ScalarTestsBase.g.cs @@ -104,6 +104,20 @@ public void Scalar_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ScalarInfo_CreateWithCustomUnitInfos() + { + ScalarUnit[] expectedUnits = [ScalarUnit.Amount]; + + Scalar.ScalarInfo quantityInfo = Scalar.ScalarInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Scalar", quantityInfo.Name); + Assert.Equal(Scalar.Zero, quantityInfo.Zero); + Assert.Equal(Scalar.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void AmountToScalarUnits() { @@ -216,7 +230,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() [Theory] [InlineData("en-US", "4.2 ", ScalarUnit.Amount, 4.2)] - public void Parse(string culture, string quantityString, ScalarUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ScalarUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Scalar.Parse(quantityString); @@ -226,7 +240,7 @@ public void Parse(string culture, string quantityString, ScalarUnit expectedUnit [Theory] [InlineData("en-US", "4.2 ", ScalarUnit.Amount, 4.2)] - public void TryParse(string culture, string quantityString, ScalarUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ScalarUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Scalar.TryParse(quantityString, out Scalar parsed)); @@ -359,6 +373,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ScalarUnit unit) var quantity = Scalar.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -382,32 +397,34 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ScalarUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Scalar amount = Scalar.FromAmount(1); - AssertEx.EqualTolerance(1, Scalar.FromAmount(amount.Amount).Amount, AmountTolerance); + Scalar amount = Scalar.FromAmount(3); + Assert.Equal(3, Scalar.FromAmount(amount.Amount).Amount); } [Fact] public void ArithmeticOperators() { Scalar v = Scalar.FromAmount(1); - AssertEx.EqualTolerance(-1, -v.Amount, AmountTolerance); - AssertEx.EqualTolerance(2, (Scalar.FromAmount(3)-v).Amount, AmountTolerance); - AssertEx.EqualTolerance(2, (v + v).Amount, AmountTolerance); - AssertEx.EqualTolerance(10, (v*10).Amount, AmountTolerance); - AssertEx.EqualTolerance(10, (10*v).Amount, AmountTolerance); - AssertEx.EqualTolerance(2, (Scalar.FromAmount(10)/5).Amount, AmountTolerance); - AssertEx.EqualTolerance(2, Scalar.FromAmount(10)/Scalar.FromAmount(5), AmountTolerance); + Assert.Equal(-1, -v.Amount); + Assert.Equal(2, (Scalar.FromAmount(3) - v).Amount); + Assert.Equal(2, (v + v).Amount); + Assert.Equal(10, (v * 10).Amount); + Assert.Equal(10, (10 * v).Amount); + Assert.Equal(2, (Scalar.FromAmount(10) / 5).Amount); + Assert.Equal(2, Scalar.FromAmount(10) / Scalar.FromAmount(5)); } [Fact] @@ -453,7 +470,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ScalarUnit.Amount, 1, ScalarUnit.Amount, true)] // Same value and unit. [InlineData(1, ScalarUnit.Amount, 2, ScalarUnit.Amount, false)] // Different value. - [InlineData(2, ScalarUnit.Amount, 1, ScalarUnit.Amount, false)] // Different value and unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ScalarUnit unitA, double valueB, ScalarUnit unitB, bool expectEqual) { var a = new Scalar(valueA, unitA); @@ -513,8 +529,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Scalar.FromAmount(firstValue); var otherQuantity = Scalar.FromAmount(secondValue); Scalar maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Scalar.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -533,7 +549,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -546,6 +562,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Scalar.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Scalar.Info.Units, Scalar.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Scalar.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -608,7 +636,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Scalar.FromAmount(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Scalar), quantity.As(Scalar.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs index fbb666edf0..7746dbde87 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SolidAngleTestsBase.g.cs @@ -104,6 +104,20 @@ public void SolidAngle_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void SolidAngleInfo_CreateWithCustomUnitInfos() + { + SolidAngleUnit[] expectedUnits = [SolidAngleUnit.Steradian]; + + SolidAngle.SolidAngleInfo quantityInfo = SolidAngle.SolidAngleInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("SolidAngle", quantityInfo.Name); + Assert.Equal(SolidAngle.Zero, quantityInfo.Zero); + Assert.Equal(SolidAngle.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void SteradianToSolidAngleUnits() { @@ -216,7 +230,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() [Theory] [InlineData("en-US", "4.2 sr", SolidAngleUnit.Steradian, 4.2)] - public void Parse(string culture, string quantityString, SolidAngleUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, SolidAngleUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = SolidAngle.Parse(quantityString); @@ -226,7 +240,7 @@ public void Parse(string culture, string quantityString, SolidAngleUnit expected [Theory] [InlineData("en-US", "4.2 sr", SolidAngleUnit.Steradian, 4.2)] - public void TryParse(string culture, string quantityString, SolidAngleUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, SolidAngleUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(SolidAngle.TryParse(quantityString, out SolidAngle parsed)); @@ -359,6 +373,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SolidAngleUnit u var quantity = SolidAngle.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -382,32 +397,34 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(SolidAngleUnit unit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - SolidAngle steradian = SolidAngle.FromSteradians(1); - AssertEx.EqualTolerance(1, SolidAngle.FromSteradians(steradian.Steradians).Steradians, SteradiansTolerance); + SolidAngle steradian = SolidAngle.FromSteradians(3); + Assert.Equal(3, SolidAngle.FromSteradians(steradian.Steradians).Steradians); } [Fact] public void ArithmeticOperators() { SolidAngle v = SolidAngle.FromSteradians(1); - AssertEx.EqualTolerance(-1, -v.Steradians, SteradiansTolerance); - AssertEx.EqualTolerance(2, (SolidAngle.FromSteradians(3)-v).Steradians, SteradiansTolerance); - AssertEx.EqualTolerance(2, (v + v).Steradians, SteradiansTolerance); - AssertEx.EqualTolerance(10, (v*10).Steradians, SteradiansTolerance); - AssertEx.EqualTolerance(10, (10*v).Steradians, SteradiansTolerance); - AssertEx.EqualTolerance(2, (SolidAngle.FromSteradians(10)/5).Steradians, SteradiansTolerance); - AssertEx.EqualTolerance(2, SolidAngle.FromSteradians(10)/SolidAngle.FromSteradians(5), SteradiansTolerance); + Assert.Equal(-1, -v.Steradians); + Assert.Equal(2, (SolidAngle.FromSteradians(3) - v).Steradians); + Assert.Equal(2, (v + v).Steradians); + Assert.Equal(10, (v * 10).Steradians); + Assert.Equal(10, (10 * v).Steradians); + Assert.Equal(2, (SolidAngle.FromSteradians(10) / 5).Steradians); + Assert.Equal(2, SolidAngle.FromSteradians(10) / SolidAngle.FromSteradians(5)); } [Fact] @@ -453,7 +470,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, SolidAngleUnit.Steradian, 1, SolidAngleUnit.Steradian, true)] // Same value and unit. [InlineData(1, SolidAngleUnit.Steradian, 2, SolidAngleUnit.Steradian, false)] // Different value. - [InlineData(2, SolidAngleUnit.Steradian, 1, SolidAngleUnit.Steradian, false)] // Different value and unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, SolidAngleUnit unitA, double valueB, SolidAngleUnit unitB, bool expectEqual) { var a = new SolidAngle(valueA, unitA); @@ -513,8 +529,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = SolidAngle.FromSteradians(firstValue); var otherQuantity = SolidAngle.FromSteradians(secondValue); SolidAngle maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, SolidAngle.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -533,7 +549,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -546,6 +562,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(SolidAngle.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(SolidAngle.Info.Units, SolidAngle.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, SolidAngle.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -608,7 +636,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = SolidAngle.FromSteradians(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(SolidAngle), quantity.As(SolidAngle.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs index 814dce6411..bc884b965b 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEnergyTestsBase.g.cs @@ -241,6 +241,20 @@ public void SpecificEnergy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void SpecificEnergyInfo_CreateWithCustomUnitInfos() + { + SpecificEnergyUnit[] expectedUnits = [SpecificEnergyUnit.JoulePerKilogram]; + + SpecificEnergy.SpecificEnergyInfo quantityInfo = SpecificEnergy.SpecificEnergyInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("SpecificEnergy", quantityInfo.Name); + Assert.Equal(SpecificEnergy.Zero, quantityInfo.Zero); + Assert.Equal(SpecificEnergy.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void JoulePerKilogramToSpecificEnergyUnits() { @@ -479,7 +493,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 Wd/t", SpecificEnergyUnit.WattDayPerTonne, 4.2)] [InlineData("en-US", "4.2 Wh/kg", SpecificEnergyUnit.WattHourPerKilogram, 4.2)] [InlineData("en-US", "4.2 Wh/lbs", SpecificEnergyUnit.WattHourPerPound, 4.2)] - public void Parse(string culture, string quantityString, SpecificEnergyUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, SpecificEnergyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = SpecificEnergy.Parse(quantityString); @@ -518,7 +532,7 @@ public void Parse(string culture, string quantityString, SpecificEnergyUnit expe [InlineData("en-US", "4.2 Wd/t", SpecificEnergyUnit.WattDayPerTonne, 4.2)] [InlineData("en-US", "4.2 Wh/kg", SpecificEnergyUnit.WattHourPerKilogram, 4.2)] [InlineData("en-US", "4.2 Wh/lbs", SpecificEnergyUnit.WattHourPerPound, 4.2)] - public void TryParse(string culture, string quantityString, SpecificEnergyUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, SpecificEnergyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(SpecificEnergy.TryParse(quantityString, out SpecificEnergy parsed)); @@ -912,6 +926,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificEnergyUn var quantity = SpecificEnergy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -935,61 +950,63 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(SpecificEnergyUnit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - SpecificEnergy jouleperkilogram = SpecificEnergy.FromJoulesPerKilogram(1); - AssertEx.EqualTolerance(1, SpecificEnergy.FromBtuPerPound(jouleperkilogram.BtuPerPound).JoulesPerKilogram, BtuPerPoundTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromCaloriesPerGram(jouleperkilogram.CaloriesPerGram).JoulesPerKilogram, CaloriesPerGramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromGigawattDaysPerKilogram(jouleperkilogram.GigawattDaysPerKilogram).JoulesPerKilogram, GigawattDaysPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromGigawattDaysPerShortTon(jouleperkilogram.GigawattDaysPerShortTon).JoulesPerKilogram, GigawattDaysPerShortTonTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromGigawattDaysPerTonne(jouleperkilogram.GigawattDaysPerTonne).JoulesPerKilogram, GigawattDaysPerTonneTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromGigawattHoursPerKilogram(jouleperkilogram.GigawattHoursPerKilogram).JoulesPerKilogram, GigawattHoursPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromGigawattHoursPerPound(jouleperkilogram.GigawattHoursPerPound).JoulesPerKilogram, GigawattHoursPerPoundTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromJoulesPerKilogram(jouleperkilogram.JoulesPerKilogram).JoulesPerKilogram, JoulesPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromKilocaloriesPerGram(jouleperkilogram.KilocaloriesPerGram).JoulesPerKilogram, KilocaloriesPerGramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromKilojoulesPerKilogram(jouleperkilogram.KilojoulesPerKilogram).JoulesPerKilogram, KilojoulesPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromKilowattDaysPerKilogram(jouleperkilogram.KilowattDaysPerKilogram).JoulesPerKilogram, KilowattDaysPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromKilowattDaysPerShortTon(jouleperkilogram.KilowattDaysPerShortTon).JoulesPerKilogram, KilowattDaysPerShortTonTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromKilowattDaysPerTonne(jouleperkilogram.KilowattDaysPerTonne).JoulesPerKilogram, KilowattDaysPerTonneTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromKilowattHoursPerKilogram(jouleperkilogram.KilowattHoursPerKilogram).JoulesPerKilogram, KilowattHoursPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromKilowattHoursPerPound(jouleperkilogram.KilowattHoursPerPound).JoulesPerKilogram, KilowattHoursPerPoundTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromMegajoulesPerKilogram(jouleperkilogram.MegajoulesPerKilogram).JoulesPerKilogram, MegajoulesPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromMegaJoulesPerTonne(jouleperkilogram.MegaJoulesPerTonne).JoulesPerKilogram, MegaJoulesPerTonneTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromMegawattDaysPerKilogram(jouleperkilogram.MegawattDaysPerKilogram).JoulesPerKilogram, MegawattDaysPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromMegawattDaysPerShortTon(jouleperkilogram.MegawattDaysPerShortTon).JoulesPerKilogram, MegawattDaysPerShortTonTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromMegawattDaysPerTonne(jouleperkilogram.MegawattDaysPerTonne).JoulesPerKilogram, MegawattDaysPerTonneTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromMegawattHoursPerKilogram(jouleperkilogram.MegawattHoursPerKilogram).JoulesPerKilogram, MegawattHoursPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromMegawattHoursPerPound(jouleperkilogram.MegawattHoursPerPound).JoulesPerKilogram, MegawattHoursPerPoundTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromTerawattDaysPerKilogram(jouleperkilogram.TerawattDaysPerKilogram).JoulesPerKilogram, TerawattDaysPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromTerawattDaysPerShortTon(jouleperkilogram.TerawattDaysPerShortTon).JoulesPerKilogram, TerawattDaysPerShortTonTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromTerawattDaysPerTonne(jouleperkilogram.TerawattDaysPerTonne).JoulesPerKilogram, TerawattDaysPerTonneTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromWattDaysPerKilogram(jouleperkilogram.WattDaysPerKilogram).JoulesPerKilogram, WattDaysPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromWattDaysPerShortTon(jouleperkilogram.WattDaysPerShortTon).JoulesPerKilogram, WattDaysPerShortTonTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromWattDaysPerTonne(jouleperkilogram.WattDaysPerTonne).JoulesPerKilogram, WattDaysPerTonneTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromWattHoursPerKilogram(jouleperkilogram.WattHoursPerKilogram).JoulesPerKilogram, WattHoursPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificEnergy.FromWattHoursPerPound(jouleperkilogram.WattHoursPerPound).JoulesPerKilogram, WattHoursPerPoundTolerance); + SpecificEnergy jouleperkilogram = SpecificEnergy.FromJoulesPerKilogram(3); + Assert.Equal(3, SpecificEnergy.FromBtuPerPound(jouleperkilogram.BtuPerPound).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromCaloriesPerGram(jouleperkilogram.CaloriesPerGram).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromGigawattDaysPerKilogram(jouleperkilogram.GigawattDaysPerKilogram).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromGigawattDaysPerShortTon(jouleperkilogram.GigawattDaysPerShortTon).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromGigawattDaysPerTonne(jouleperkilogram.GigawattDaysPerTonne).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromGigawattHoursPerKilogram(jouleperkilogram.GigawattHoursPerKilogram).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromGigawattHoursPerPound(jouleperkilogram.GigawattHoursPerPound).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromJoulesPerKilogram(jouleperkilogram.JoulesPerKilogram).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromKilocaloriesPerGram(jouleperkilogram.KilocaloriesPerGram).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromKilojoulesPerKilogram(jouleperkilogram.KilojoulesPerKilogram).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromKilowattDaysPerKilogram(jouleperkilogram.KilowattDaysPerKilogram).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromKilowattDaysPerShortTon(jouleperkilogram.KilowattDaysPerShortTon).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromKilowattDaysPerTonne(jouleperkilogram.KilowattDaysPerTonne).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromKilowattHoursPerKilogram(jouleperkilogram.KilowattHoursPerKilogram).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromKilowattHoursPerPound(jouleperkilogram.KilowattHoursPerPound).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromMegajoulesPerKilogram(jouleperkilogram.MegajoulesPerKilogram).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromMegaJoulesPerTonne(jouleperkilogram.MegaJoulesPerTonne).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromMegawattDaysPerKilogram(jouleperkilogram.MegawattDaysPerKilogram).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromMegawattDaysPerShortTon(jouleperkilogram.MegawattDaysPerShortTon).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromMegawattDaysPerTonne(jouleperkilogram.MegawattDaysPerTonne).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromMegawattHoursPerKilogram(jouleperkilogram.MegawattHoursPerKilogram).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromMegawattHoursPerPound(jouleperkilogram.MegawattHoursPerPound).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromTerawattDaysPerKilogram(jouleperkilogram.TerawattDaysPerKilogram).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromTerawattDaysPerShortTon(jouleperkilogram.TerawattDaysPerShortTon).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromTerawattDaysPerTonne(jouleperkilogram.TerawattDaysPerTonne).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromWattDaysPerKilogram(jouleperkilogram.WattDaysPerKilogram).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromWattDaysPerShortTon(jouleperkilogram.WattDaysPerShortTon).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromWattDaysPerTonne(jouleperkilogram.WattDaysPerTonne).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromWattHoursPerKilogram(jouleperkilogram.WattHoursPerKilogram).JoulesPerKilogram); + Assert.Equal(3, SpecificEnergy.FromWattHoursPerPound(jouleperkilogram.WattHoursPerPound).JoulesPerKilogram); } [Fact] public void ArithmeticOperators() { SpecificEnergy v = SpecificEnergy.FromJoulesPerKilogram(1); - AssertEx.EqualTolerance(-1, -v.JoulesPerKilogram, JoulesPerKilogramTolerance); - AssertEx.EqualTolerance(2, (SpecificEnergy.FromJoulesPerKilogram(3)-v).JoulesPerKilogram, JoulesPerKilogramTolerance); - AssertEx.EqualTolerance(2, (v + v).JoulesPerKilogram, JoulesPerKilogramTolerance); - AssertEx.EqualTolerance(10, (v*10).JoulesPerKilogram, JoulesPerKilogramTolerance); - AssertEx.EqualTolerance(10, (10*v).JoulesPerKilogram, JoulesPerKilogramTolerance); - AssertEx.EqualTolerance(2, (SpecificEnergy.FromJoulesPerKilogram(10)/5).JoulesPerKilogram, JoulesPerKilogramTolerance); - AssertEx.EqualTolerance(2, SpecificEnergy.FromJoulesPerKilogram(10)/SpecificEnergy.FromJoulesPerKilogram(5), JoulesPerKilogramTolerance); + Assert.Equal(-1, -v.JoulesPerKilogram); + Assert.Equal(2, (SpecificEnergy.FromJoulesPerKilogram(3) - v).JoulesPerKilogram); + Assert.Equal(2, (v + v).JoulesPerKilogram); + Assert.Equal(10, (v * 10).JoulesPerKilogram); + Assert.Equal(10, (10 * v).JoulesPerKilogram); + Assert.Equal(2, (SpecificEnergy.FromJoulesPerKilogram(10) / 5).JoulesPerKilogram); + Assert.Equal(2, SpecificEnergy.FromJoulesPerKilogram(10) / SpecificEnergy.FromJoulesPerKilogram(5)); } [Fact] @@ -1035,8 +1052,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, SpecificEnergyUnit.JoulePerKilogram, 1, SpecificEnergyUnit.JoulePerKilogram, true)] // Same value and unit. [InlineData(1, SpecificEnergyUnit.JoulePerKilogram, 2, SpecificEnergyUnit.JoulePerKilogram, false)] // Different value. - [InlineData(2, SpecificEnergyUnit.JoulePerKilogram, 1, SpecificEnergyUnit.BtuPerPound, false)] // Different value and unit. - [InlineData(1, SpecificEnergyUnit.JoulePerKilogram, 1, SpecificEnergyUnit.BtuPerPound, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, SpecificEnergyUnit unitA, double valueB, SpecificEnergyUnit unitB, bool expectEqual) { var a = new SpecificEnergy(valueA, unitA); @@ -1096,8 +1111,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = SpecificEnergy.FromJoulesPerKilogram(firstValue); var otherQuantity = SpecificEnergy.FromJoulesPerKilogram(secondValue); SpecificEnergy maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, SpecificEnergy.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1116,7 +1131,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1129,6 +1144,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(SpecificEnergy.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(SpecificEnergy.Info.Units, SpecificEnergy.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, SpecificEnergy.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1249,7 +1276,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = SpecificEnergy.FromJoulesPerKilogram(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(SpecificEnergy), quantity.As(SpecificEnergy.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs index bb181c5b8f..a98935ec59 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificEntropyTestsBase.g.cs @@ -157,6 +157,20 @@ public void SpecificEntropy_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void SpecificEntropyInfo_CreateWithCustomUnitInfos() + { + SpecificEntropyUnit[] expectedUnits = [SpecificEntropyUnit.JoulePerKilogramKelvin]; + + SpecificEntropy.SpecificEntropyInfo quantityInfo = SpecificEntropy.SpecificEntropyInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("SpecificEntropy", quantityInfo.Name); + Assert.Equal(SpecificEntropy.Zero, quantityInfo.Zero); + Assert.Equal(SpecificEntropy.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void JoulePerKilogramKelvinToSpecificEntropyUnits() { @@ -333,7 +347,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 kJ/kg·K", SpecificEntropyUnit.KilojoulePerKilogramKelvin, 4.2)] [InlineData("en-US", "4.2 MJ/kg·°C", SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, 4.2)] [InlineData("en-US", "4.2 MJ/kg·K", SpecificEntropyUnit.MegajoulePerKilogramKelvin, 4.2)] - public void Parse(string culture, string quantityString, SpecificEntropyUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, SpecificEntropyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = SpecificEntropy.Parse(quantityString); @@ -352,7 +366,7 @@ public void Parse(string culture, string quantityString, SpecificEntropyUnit exp [InlineData("en-US", "4.2 kJ/kg·K", SpecificEntropyUnit.KilojoulePerKilogramKelvin, 4.2)] [InlineData("en-US", "4.2 MJ/kg·°C", SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, 4.2)] [InlineData("en-US", "4.2 MJ/kg·K", SpecificEntropyUnit.MegajoulePerKilogramKelvin, 4.2)] - public void TryParse(string culture, string quantityString, SpecificEntropyUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, SpecificEntropyUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(SpecificEntropy.TryParse(quantityString, out SpecificEntropy parsed)); @@ -565,6 +579,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificEntropyU var quantity = SpecificEntropy.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -588,40 +603,42 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(SpecificEntropyUnit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - SpecificEntropy jouleperkilogramkelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - AssertEx.EqualTolerance(1, SpecificEntropy.FromBtusPerPoundFahrenheit(jouleperkilogramkelvin.BtusPerPoundFahrenheit).JoulesPerKilogramKelvin, BtusPerPoundFahrenheitTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.FromCaloriesPerGramKelvin(jouleperkilogramkelvin.CaloriesPerGramKelvin).JoulesPerKilogramKelvin, CaloriesPerGramKelvinTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.FromJoulesPerKilogramDegreeCelsius(jouleperkilogramkelvin.JoulesPerKilogramDegreeCelsius).JoulesPerKilogramKelvin, JoulesPerKilogramDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.FromJoulesPerKilogramKelvin(jouleperkilogramkelvin.JoulesPerKilogramKelvin).JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.FromKilocaloriesPerGramKelvin(jouleperkilogramkelvin.KilocaloriesPerGramKelvin).JoulesPerKilogramKelvin, KilocaloriesPerGramKelvinTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.FromKilojoulesPerKilogramDegreeCelsius(jouleperkilogramkelvin.KilojoulesPerKilogramDegreeCelsius).JoulesPerKilogramKelvin, KilojoulesPerKilogramDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.FromKilojoulesPerKilogramKelvin(jouleperkilogramkelvin.KilojoulesPerKilogramKelvin).JoulesPerKilogramKelvin, KilojoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.FromMegajoulesPerKilogramDegreeCelsius(jouleperkilogramkelvin.MegajoulesPerKilogramDegreeCelsius).JoulesPerKilogramKelvin, MegajoulesPerKilogramDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, SpecificEntropy.FromMegajoulesPerKilogramKelvin(jouleperkilogramkelvin.MegajoulesPerKilogramKelvin).JoulesPerKilogramKelvin, MegajoulesPerKilogramKelvinTolerance); + SpecificEntropy jouleperkilogramkelvin = SpecificEntropy.FromJoulesPerKilogramKelvin(3); + Assert.Equal(3, SpecificEntropy.FromBtusPerPoundFahrenheit(jouleperkilogramkelvin.BtusPerPoundFahrenheit).JoulesPerKilogramKelvin); + Assert.Equal(3, SpecificEntropy.FromCaloriesPerGramKelvin(jouleperkilogramkelvin.CaloriesPerGramKelvin).JoulesPerKilogramKelvin); + Assert.Equal(3, SpecificEntropy.FromJoulesPerKilogramDegreeCelsius(jouleperkilogramkelvin.JoulesPerKilogramDegreeCelsius).JoulesPerKilogramKelvin); + Assert.Equal(3, SpecificEntropy.FromJoulesPerKilogramKelvin(jouleperkilogramkelvin.JoulesPerKilogramKelvin).JoulesPerKilogramKelvin); + Assert.Equal(3, SpecificEntropy.FromKilocaloriesPerGramKelvin(jouleperkilogramkelvin.KilocaloriesPerGramKelvin).JoulesPerKilogramKelvin); + Assert.Equal(3, SpecificEntropy.FromKilojoulesPerKilogramDegreeCelsius(jouleperkilogramkelvin.KilojoulesPerKilogramDegreeCelsius).JoulesPerKilogramKelvin); + Assert.Equal(3, SpecificEntropy.FromKilojoulesPerKilogramKelvin(jouleperkilogramkelvin.KilojoulesPerKilogramKelvin).JoulesPerKilogramKelvin); + Assert.Equal(3, SpecificEntropy.FromMegajoulesPerKilogramDegreeCelsius(jouleperkilogramkelvin.MegajoulesPerKilogramDegreeCelsius).JoulesPerKilogramKelvin); + Assert.Equal(3, SpecificEntropy.FromMegajoulesPerKilogramKelvin(jouleperkilogramkelvin.MegajoulesPerKilogramKelvin).JoulesPerKilogramKelvin); } [Fact] public void ArithmeticOperators() { SpecificEntropy v = SpecificEntropy.FromJoulesPerKilogramKelvin(1); - AssertEx.EqualTolerance(-1, -v.JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(2, (SpecificEntropy.FromJoulesPerKilogramKelvin(3)-v).JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(2, (v + v).JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(10, (v*10).JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(10, (10*v).JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(2, (SpecificEntropy.FromJoulesPerKilogramKelvin(10)/5).JoulesPerKilogramKelvin, JoulesPerKilogramKelvinTolerance); - AssertEx.EqualTolerance(2, SpecificEntropy.FromJoulesPerKilogramKelvin(10)/SpecificEntropy.FromJoulesPerKilogramKelvin(5), JoulesPerKilogramKelvinTolerance); + Assert.Equal(-1, -v.JoulesPerKilogramKelvin); + Assert.Equal(2, (SpecificEntropy.FromJoulesPerKilogramKelvin(3) - v).JoulesPerKilogramKelvin); + Assert.Equal(2, (v + v).JoulesPerKilogramKelvin); + Assert.Equal(10, (v * 10).JoulesPerKilogramKelvin); + Assert.Equal(10, (10 * v).JoulesPerKilogramKelvin); + Assert.Equal(2, (SpecificEntropy.FromJoulesPerKilogramKelvin(10) / 5).JoulesPerKilogramKelvin); + Assert.Equal(2, SpecificEntropy.FromJoulesPerKilogramKelvin(10) / SpecificEntropy.FromJoulesPerKilogramKelvin(5)); } [Fact] @@ -667,8 +684,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, SpecificEntropyUnit.JoulePerKilogramKelvin, 1, SpecificEntropyUnit.JoulePerKilogramKelvin, true)] // Same value and unit. [InlineData(1, SpecificEntropyUnit.JoulePerKilogramKelvin, 2, SpecificEntropyUnit.JoulePerKilogramKelvin, false)] // Different value. - [InlineData(2, SpecificEntropyUnit.JoulePerKilogramKelvin, 1, SpecificEntropyUnit.BtuPerPoundFahrenheit, false)] // Different value and unit. - [InlineData(1, SpecificEntropyUnit.JoulePerKilogramKelvin, 1, SpecificEntropyUnit.BtuPerPoundFahrenheit, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, SpecificEntropyUnit unitA, double valueB, SpecificEntropyUnit unitB, bool expectEqual) { var a = new SpecificEntropy(valueA, unitA); @@ -728,8 +743,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(firstValue); var otherQuantity = SpecificEntropy.FromJoulesPerKilogramKelvin(secondValue); SpecificEntropy maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, SpecificEntropy.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -748,7 +763,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -761,6 +776,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(SpecificEntropy.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(SpecificEntropy.Info.Units, SpecificEntropy.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, SpecificEntropy.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -839,7 +866,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = SpecificEntropy.FromJoulesPerKilogramKelvin(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(SpecificEntropy), quantity.As(SpecificEntropy.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs index 52040a2248..be99c6ddfb 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificFuelConsumptionTestsBase.g.cs @@ -137,6 +137,20 @@ public void SpecificFuelConsumption_QuantityInfo_ReturnsQuantityInfoDescribingQu Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void SpecificFuelConsumptionInfo_CreateWithCustomUnitInfos() + { + SpecificFuelConsumptionUnit[] expectedUnits = [SpecificFuelConsumptionUnit.GramPerKilonewtonSecond]; + + SpecificFuelConsumption.SpecificFuelConsumptionInfo quantityInfo = SpecificFuelConsumption.SpecificFuelConsumptionInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("SpecificFuelConsumption", quantityInfo.Name); + Assert.Equal(SpecificFuelConsumption.Zero, quantityInfo.Zero); + Assert.Equal(SpecificFuelConsumption.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void GramPerKilonewtonSecondToSpecificFuelConsumptionUnits() { @@ -297,7 +311,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 kg/(kgf·h)", SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, 4.2)] [InlineData("en-US", "4.2 kg/(kN·s)", SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond, 4.2)] [InlineData("en-US", "4.2 lb/(lbf·h)", SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, 4.2)] - public void Parse(string culture, string quantityString, SpecificFuelConsumptionUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, SpecificFuelConsumptionUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = SpecificFuelConsumption.Parse(quantityString); @@ -310,7 +324,7 @@ public void Parse(string culture, string quantityString, SpecificFuelConsumption [InlineData("en-US", "4.2 kg/(kgf·h)", SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, 4.2)] [InlineData("en-US", "4.2 kg/(kN·s)", SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond, 4.2)] [InlineData("en-US", "4.2 lb/(lbf·h)", SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, 4.2)] - public void TryParse(string culture, string quantityString, SpecificFuelConsumptionUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, SpecificFuelConsumptionUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(SpecificFuelConsumption.TryParse(quantityString, out SpecificFuelConsumption parsed)); @@ -470,6 +484,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificFuelCons var quantity = SpecificFuelConsumption.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -493,35 +508,37 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(SpecificFuelConsump IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - SpecificFuelConsumption gramperkilonewtonsecond = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1); - AssertEx.EqualTolerance(1, SpecificFuelConsumption.FromGramsPerKilonewtonSecond(gramperkilonewtonsecond.GramsPerKilonewtonSecond).GramsPerKilonewtonSecond, GramsPerKilonewtonSecondTolerance); - AssertEx.EqualTolerance(1, SpecificFuelConsumption.FromKilogramsPerKilogramForceHour(gramperkilonewtonsecond.KilogramsPerKilogramForceHour).GramsPerKilonewtonSecond, KilogramsPerKilogramForceHourTolerance); - AssertEx.EqualTolerance(1, SpecificFuelConsumption.FromKilogramsPerKilonewtonSecond(gramperkilonewtonsecond.KilogramsPerKilonewtonSecond).GramsPerKilonewtonSecond, KilogramsPerKilonewtonSecondTolerance); - AssertEx.EqualTolerance(1, SpecificFuelConsumption.FromPoundsMassPerPoundForceHour(gramperkilonewtonsecond.PoundsMassPerPoundForceHour).GramsPerKilonewtonSecond, PoundsMassPerPoundForceHourTolerance); + SpecificFuelConsumption gramperkilonewtonsecond = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(3); + Assert.Equal(3, SpecificFuelConsumption.FromGramsPerKilonewtonSecond(gramperkilonewtonsecond.GramsPerKilonewtonSecond).GramsPerKilonewtonSecond); + Assert.Equal(3, SpecificFuelConsumption.FromKilogramsPerKilogramForceHour(gramperkilonewtonsecond.KilogramsPerKilogramForceHour).GramsPerKilonewtonSecond); + Assert.Equal(3, SpecificFuelConsumption.FromKilogramsPerKilonewtonSecond(gramperkilonewtonsecond.KilogramsPerKilonewtonSecond).GramsPerKilonewtonSecond); + Assert.Equal(3, SpecificFuelConsumption.FromPoundsMassPerPoundForceHour(gramperkilonewtonsecond.PoundsMassPerPoundForceHour).GramsPerKilonewtonSecond); } [Fact] public void ArithmeticOperators() { SpecificFuelConsumption v = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1); - AssertEx.EqualTolerance(-1, -v.GramsPerKilonewtonSecond, GramsPerKilonewtonSecondTolerance); - AssertEx.EqualTolerance(2, (SpecificFuelConsumption.FromGramsPerKilonewtonSecond(3)-v).GramsPerKilonewtonSecond, GramsPerKilonewtonSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).GramsPerKilonewtonSecond, GramsPerKilonewtonSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).GramsPerKilonewtonSecond, GramsPerKilonewtonSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).GramsPerKilonewtonSecond, GramsPerKilonewtonSecondTolerance); - AssertEx.EqualTolerance(2, (SpecificFuelConsumption.FromGramsPerKilonewtonSecond(10)/5).GramsPerKilonewtonSecond, GramsPerKilonewtonSecondTolerance); - AssertEx.EqualTolerance(2, SpecificFuelConsumption.FromGramsPerKilonewtonSecond(10)/SpecificFuelConsumption.FromGramsPerKilonewtonSecond(5), GramsPerKilonewtonSecondTolerance); + Assert.Equal(-1, -v.GramsPerKilonewtonSecond); + Assert.Equal(2, (SpecificFuelConsumption.FromGramsPerKilonewtonSecond(3) - v).GramsPerKilonewtonSecond); + Assert.Equal(2, (v + v).GramsPerKilonewtonSecond); + Assert.Equal(10, (v * 10).GramsPerKilonewtonSecond); + Assert.Equal(10, (10 * v).GramsPerKilonewtonSecond); + Assert.Equal(2, (SpecificFuelConsumption.FromGramsPerKilonewtonSecond(10) / 5).GramsPerKilonewtonSecond); + Assert.Equal(2, SpecificFuelConsumption.FromGramsPerKilonewtonSecond(10) / SpecificFuelConsumption.FromGramsPerKilonewtonSecond(5)); } [Fact] @@ -567,8 +584,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, 1, SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, true)] // Same value and unit. [InlineData(1, SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, 2, SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, false)] // Different value. - [InlineData(2, SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, 1, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, false)] // Different value and unit. - [InlineData(1, SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, 1, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, SpecificFuelConsumptionUnit unitA, double valueB, SpecificFuelConsumptionUnit unitB, bool expectEqual) { var a = new SpecificFuelConsumption(valueA, unitA); @@ -628,8 +643,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(firstValue); var otherQuantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(secondValue); SpecificFuelConsumption maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, SpecificFuelConsumption.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -648,7 +663,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -661,6 +676,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(SpecificFuelConsumption.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(SpecificFuelConsumption.Info.Units, SpecificFuelConsumption.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, SpecificFuelConsumption.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -729,7 +756,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = SpecificFuelConsumption.FromGramsPerKilonewtonSecond(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(SpecificFuelConsumption), quantity.As(SpecificFuelConsumption.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs index 605ae62907..2474be8985 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificVolumeTestsBase.g.cs @@ -133,6 +133,20 @@ public void SpecificVolume_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void SpecificVolumeInfo_CreateWithCustomUnitInfos() + { + SpecificVolumeUnit[] expectedUnits = [SpecificVolumeUnit.CubicMeterPerKilogram]; + + SpecificVolume.SpecificVolumeInfo quantityInfo = SpecificVolume.SpecificVolumeInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("SpecificVolume", quantityInfo.Name); + Assert.Equal(SpecificVolume.Zero, quantityInfo.Zero); + Assert.Equal(SpecificVolume.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void CubicMeterPerKilogramToSpecificVolumeUnits() { @@ -290,7 +304,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 ft³/lb", SpecificVolumeUnit.CubicFootPerPound, 4.2)] [InlineData("en-US", "4.2 m³/kg", SpecificVolumeUnit.CubicMeterPerKilogram, 4.2)] [InlineData("en-US", "4.2 mm³/kg", SpecificVolumeUnit.MillicubicMeterPerKilogram, 4.2)] - public void Parse(string culture, string quantityString, SpecificVolumeUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, SpecificVolumeUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = SpecificVolume.Parse(quantityString); @@ -302,7 +316,7 @@ public void Parse(string culture, string quantityString, SpecificVolumeUnit expe [InlineData("en-US", "4.2 ft³/lb", SpecificVolumeUnit.CubicFootPerPound, 4.2)] [InlineData("en-US", "4.2 m³/kg", SpecificVolumeUnit.CubicMeterPerKilogram, 4.2)] [InlineData("en-US", "4.2 mm³/kg", SpecificVolumeUnit.MillicubicMeterPerKilogram, 4.2)] - public void TryParse(string culture, string quantityString, SpecificVolumeUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, SpecificVolumeUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(SpecificVolume.TryParse(quantityString, out SpecificVolume parsed)); @@ -453,6 +467,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificVolumeUn var quantity = SpecificVolume.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -476,34 +491,36 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(SpecificVolumeUnit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - SpecificVolume cubicmeterperkilogram = SpecificVolume.FromCubicMetersPerKilogram(1); - AssertEx.EqualTolerance(1, SpecificVolume.FromCubicFeetPerPound(cubicmeterperkilogram.CubicFeetPerPound).CubicMetersPerKilogram, CubicFeetPerPoundTolerance); - AssertEx.EqualTolerance(1, SpecificVolume.FromCubicMetersPerKilogram(cubicmeterperkilogram.CubicMetersPerKilogram).CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - AssertEx.EqualTolerance(1, SpecificVolume.FromMillicubicMetersPerKilogram(cubicmeterperkilogram.MillicubicMetersPerKilogram).CubicMetersPerKilogram, MillicubicMetersPerKilogramTolerance); + SpecificVolume cubicmeterperkilogram = SpecificVolume.FromCubicMetersPerKilogram(3); + Assert.Equal(3, SpecificVolume.FromCubicFeetPerPound(cubicmeterperkilogram.CubicFeetPerPound).CubicMetersPerKilogram); + Assert.Equal(3, SpecificVolume.FromCubicMetersPerKilogram(cubicmeterperkilogram.CubicMetersPerKilogram).CubicMetersPerKilogram); + Assert.Equal(3, SpecificVolume.FromMillicubicMetersPerKilogram(cubicmeterperkilogram.MillicubicMetersPerKilogram).CubicMetersPerKilogram); } [Fact] public void ArithmeticOperators() { SpecificVolume v = SpecificVolume.FromCubicMetersPerKilogram(1); - AssertEx.EqualTolerance(-1, -v.CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - AssertEx.EqualTolerance(2, (SpecificVolume.FromCubicMetersPerKilogram(3)-v).CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - AssertEx.EqualTolerance(2, (v + v).CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - AssertEx.EqualTolerance(10, (v*10).CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - AssertEx.EqualTolerance(10, (10*v).CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - AssertEx.EqualTolerance(2, (SpecificVolume.FromCubicMetersPerKilogram(10)/5).CubicMetersPerKilogram, CubicMetersPerKilogramTolerance); - AssertEx.EqualTolerance(2, SpecificVolume.FromCubicMetersPerKilogram(10)/SpecificVolume.FromCubicMetersPerKilogram(5), CubicMetersPerKilogramTolerance); + Assert.Equal(-1, -v.CubicMetersPerKilogram); + Assert.Equal(2, (SpecificVolume.FromCubicMetersPerKilogram(3) - v).CubicMetersPerKilogram); + Assert.Equal(2, (v + v).CubicMetersPerKilogram); + Assert.Equal(10, (v * 10).CubicMetersPerKilogram); + Assert.Equal(10, (10 * v).CubicMetersPerKilogram); + Assert.Equal(2, (SpecificVolume.FromCubicMetersPerKilogram(10) / 5).CubicMetersPerKilogram); + Assert.Equal(2, SpecificVolume.FromCubicMetersPerKilogram(10) / SpecificVolume.FromCubicMetersPerKilogram(5)); } [Fact] @@ -549,8 +566,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, SpecificVolumeUnit.CubicMeterPerKilogram, 1, SpecificVolumeUnit.CubicMeterPerKilogram, true)] // Same value and unit. [InlineData(1, SpecificVolumeUnit.CubicMeterPerKilogram, 2, SpecificVolumeUnit.CubicMeterPerKilogram, false)] // Different value. - [InlineData(2, SpecificVolumeUnit.CubicMeterPerKilogram, 1, SpecificVolumeUnit.CubicFootPerPound, false)] // Different value and unit. - [InlineData(1, SpecificVolumeUnit.CubicMeterPerKilogram, 1, SpecificVolumeUnit.CubicFootPerPound, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, SpecificVolumeUnit unitA, double valueB, SpecificVolumeUnit unitB, bool expectEqual) { var a = new SpecificVolume(valueA, unitA); @@ -610,8 +625,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = SpecificVolume.FromCubicMetersPerKilogram(firstValue); var otherQuantity = SpecificVolume.FromCubicMetersPerKilogram(secondValue); SpecificVolume maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, SpecificVolume.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -630,7 +645,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -643,6 +658,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(SpecificVolume.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(SpecificVolume.Info.Units, SpecificVolume.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, SpecificVolume.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -709,7 +736,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = SpecificVolume.FromCubicMetersPerKilogram(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(SpecificVolume), quantity.As(SpecificVolume.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs index cc17b14ebd..78a464d313 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpecificWeightTestsBase.g.cs @@ -189,6 +189,20 @@ public void SpecificWeight_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void SpecificWeightInfo_CreateWithCustomUnitInfos() + { + SpecificWeightUnit[] expectedUnits = [SpecificWeightUnit.NewtonPerCubicMeter]; + + SpecificWeight.SpecificWeightInfo quantityInfo = SpecificWeight.SpecificWeightInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("SpecificWeight", quantityInfo.Name); + Assert.Equal(SpecificWeight.Zero, quantityInfo.Zero); + Assert.Equal(SpecificWeight.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void NewtonPerCubicMeterToSpecificWeightUnits() { @@ -388,7 +402,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 tf/cm³", SpecificWeightUnit.TonneForcePerCubicCentimeter, 4.2)] [InlineData("en-US", "4.2 tf/m³", SpecificWeightUnit.TonneForcePerCubicMeter, 4.2)] [InlineData("en-US", "4.2 tf/mm³", SpecificWeightUnit.TonneForcePerCubicMillimeter, 4.2)] - public void Parse(string culture, string quantityString, SpecificWeightUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, SpecificWeightUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = SpecificWeight.Parse(quantityString); @@ -414,7 +428,7 @@ public void Parse(string culture, string quantityString, SpecificWeightUnit expe [InlineData("en-US", "4.2 tf/cm³", SpecificWeightUnit.TonneForcePerCubicCentimeter, 4.2)] [InlineData("en-US", "4.2 tf/m³", SpecificWeightUnit.TonneForcePerCubicMeter, 4.2)] [InlineData("en-US", "4.2 tf/mm³", SpecificWeightUnit.TonneForcePerCubicMillimeter, 4.2)] - public void TryParse(string culture, string quantityString, SpecificWeightUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, SpecificWeightUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(SpecificWeight.TryParse(quantityString, out SpecificWeight parsed)); @@ -691,6 +705,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpecificWeightUn var quantity = SpecificWeight.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -714,48 +729,50 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(SpecificWeightUnit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - SpecificWeight newtonpercubicmeter = SpecificWeight.FromNewtonsPerCubicMeter(1); - AssertEx.EqualTolerance(1, SpecificWeight.FromKilogramsForcePerCubicCentimeter(newtonpercubicmeter.KilogramsForcePerCubicCentimeter).NewtonsPerCubicMeter, KilogramsForcePerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromKilogramsForcePerCubicMeter(newtonpercubicmeter.KilogramsForcePerCubicMeter).NewtonsPerCubicMeter, KilogramsForcePerCubicMeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromKilogramsForcePerCubicMillimeter(newtonpercubicmeter.KilogramsForcePerCubicMillimeter).NewtonsPerCubicMeter, KilogramsForcePerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromKilonewtonsPerCubicCentimeter(newtonpercubicmeter.KilonewtonsPerCubicCentimeter).NewtonsPerCubicMeter, KilonewtonsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromKilonewtonsPerCubicMeter(newtonpercubicmeter.KilonewtonsPerCubicMeter).NewtonsPerCubicMeter, KilonewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromKilonewtonsPerCubicMillimeter(newtonpercubicmeter.KilonewtonsPerCubicMillimeter).NewtonsPerCubicMeter, KilonewtonsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromKilopoundsForcePerCubicFoot(newtonpercubicmeter.KilopoundsForcePerCubicFoot).NewtonsPerCubicMeter, KilopoundsForcePerCubicFootTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromKilopoundsForcePerCubicInch(newtonpercubicmeter.KilopoundsForcePerCubicInch).NewtonsPerCubicMeter, KilopoundsForcePerCubicInchTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromMeganewtonsPerCubicMeter(newtonpercubicmeter.MeganewtonsPerCubicMeter).NewtonsPerCubicMeter, MeganewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromNewtonsPerCubicCentimeter(newtonpercubicmeter.NewtonsPerCubicCentimeter).NewtonsPerCubicMeter, NewtonsPerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromNewtonsPerCubicMeter(newtonpercubicmeter.NewtonsPerCubicMeter).NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromNewtonsPerCubicMillimeter(newtonpercubicmeter.NewtonsPerCubicMillimeter).NewtonsPerCubicMeter, NewtonsPerCubicMillimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromPoundsForcePerCubicFoot(newtonpercubicmeter.PoundsForcePerCubicFoot).NewtonsPerCubicMeter, PoundsForcePerCubicFootTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromPoundsForcePerCubicInch(newtonpercubicmeter.PoundsForcePerCubicInch).NewtonsPerCubicMeter, PoundsForcePerCubicInchTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromTonnesForcePerCubicCentimeter(newtonpercubicmeter.TonnesForcePerCubicCentimeter).NewtonsPerCubicMeter, TonnesForcePerCubicCentimeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromTonnesForcePerCubicMeter(newtonpercubicmeter.TonnesForcePerCubicMeter).NewtonsPerCubicMeter, TonnesForcePerCubicMeterTolerance); - AssertEx.EqualTolerance(1, SpecificWeight.FromTonnesForcePerCubicMillimeter(newtonpercubicmeter.TonnesForcePerCubicMillimeter).NewtonsPerCubicMeter, TonnesForcePerCubicMillimeterTolerance); + SpecificWeight newtonpercubicmeter = SpecificWeight.FromNewtonsPerCubicMeter(3); + Assert.Equal(3, SpecificWeight.FromKilogramsForcePerCubicCentimeter(newtonpercubicmeter.KilogramsForcePerCubicCentimeter).NewtonsPerCubicMeter); + Assert.Equal(3, SpecificWeight.FromKilogramsForcePerCubicMeter(newtonpercubicmeter.KilogramsForcePerCubicMeter).NewtonsPerCubicMeter); + Assert.Equal(3, SpecificWeight.FromKilogramsForcePerCubicMillimeter(newtonpercubicmeter.KilogramsForcePerCubicMillimeter).NewtonsPerCubicMeter); + Assert.Equal(3, SpecificWeight.FromKilonewtonsPerCubicCentimeter(newtonpercubicmeter.KilonewtonsPerCubicCentimeter).NewtonsPerCubicMeter); + Assert.Equal(3, SpecificWeight.FromKilonewtonsPerCubicMeter(newtonpercubicmeter.KilonewtonsPerCubicMeter).NewtonsPerCubicMeter); + Assert.Equal(3, SpecificWeight.FromKilonewtonsPerCubicMillimeter(newtonpercubicmeter.KilonewtonsPerCubicMillimeter).NewtonsPerCubicMeter); + Assert.Equal(3, SpecificWeight.FromKilopoundsForcePerCubicFoot(newtonpercubicmeter.KilopoundsForcePerCubicFoot).NewtonsPerCubicMeter); + Assert.Equal(3, SpecificWeight.FromKilopoundsForcePerCubicInch(newtonpercubicmeter.KilopoundsForcePerCubicInch).NewtonsPerCubicMeter); + Assert.Equal(3, SpecificWeight.FromMeganewtonsPerCubicMeter(newtonpercubicmeter.MeganewtonsPerCubicMeter).NewtonsPerCubicMeter); + Assert.Equal(3, SpecificWeight.FromNewtonsPerCubicCentimeter(newtonpercubicmeter.NewtonsPerCubicCentimeter).NewtonsPerCubicMeter); + Assert.Equal(3, SpecificWeight.FromNewtonsPerCubicMeter(newtonpercubicmeter.NewtonsPerCubicMeter).NewtonsPerCubicMeter); + Assert.Equal(3, SpecificWeight.FromNewtonsPerCubicMillimeter(newtonpercubicmeter.NewtonsPerCubicMillimeter).NewtonsPerCubicMeter); + Assert.Equal(3, SpecificWeight.FromPoundsForcePerCubicFoot(newtonpercubicmeter.PoundsForcePerCubicFoot).NewtonsPerCubicMeter); + Assert.Equal(3, SpecificWeight.FromPoundsForcePerCubicInch(newtonpercubicmeter.PoundsForcePerCubicInch).NewtonsPerCubicMeter); + Assert.Equal(3, SpecificWeight.FromTonnesForcePerCubicCentimeter(newtonpercubicmeter.TonnesForcePerCubicCentimeter).NewtonsPerCubicMeter); + Assert.Equal(3, SpecificWeight.FromTonnesForcePerCubicMeter(newtonpercubicmeter.TonnesForcePerCubicMeter).NewtonsPerCubicMeter); + Assert.Equal(3, SpecificWeight.FromTonnesForcePerCubicMillimeter(newtonpercubicmeter.TonnesForcePerCubicMillimeter).NewtonsPerCubicMeter); } [Fact] public void ArithmeticOperators() { SpecificWeight v = SpecificWeight.FromNewtonsPerCubicMeter(1); - AssertEx.EqualTolerance(-1, -v.NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (SpecificWeight.FromNewtonsPerCubicMeter(3)-v).NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, (SpecificWeight.FromNewtonsPerCubicMeter(10)/5).NewtonsPerCubicMeter, NewtonsPerCubicMeterTolerance); - AssertEx.EqualTolerance(2, SpecificWeight.FromNewtonsPerCubicMeter(10)/SpecificWeight.FromNewtonsPerCubicMeter(5), NewtonsPerCubicMeterTolerance); + Assert.Equal(-1, -v.NewtonsPerCubicMeter); + Assert.Equal(2, (SpecificWeight.FromNewtonsPerCubicMeter(3) - v).NewtonsPerCubicMeter); + Assert.Equal(2, (v + v).NewtonsPerCubicMeter); + Assert.Equal(10, (v * 10).NewtonsPerCubicMeter); + Assert.Equal(10, (10 * v).NewtonsPerCubicMeter); + Assert.Equal(2, (SpecificWeight.FromNewtonsPerCubicMeter(10) / 5).NewtonsPerCubicMeter); + Assert.Equal(2, SpecificWeight.FromNewtonsPerCubicMeter(10) / SpecificWeight.FromNewtonsPerCubicMeter(5)); } [Fact] @@ -801,8 +818,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, SpecificWeightUnit.NewtonPerCubicMeter, 1, SpecificWeightUnit.NewtonPerCubicMeter, true)] // Same value and unit. [InlineData(1, SpecificWeightUnit.NewtonPerCubicMeter, 2, SpecificWeightUnit.NewtonPerCubicMeter, false)] // Different value. - [InlineData(2, SpecificWeightUnit.NewtonPerCubicMeter, 1, SpecificWeightUnit.KilogramForcePerCubicCentimeter, false)] // Different value and unit. - [InlineData(1, SpecificWeightUnit.NewtonPerCubicMeter, 1, SpecificWeightUnit.KilogramForcePerCubicCentimeter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, SpecificWeightUnit unitA, double valueB, SpecificWeightUnit unitB, bool expectEqual) { var a = new SpecificWeight(valueA, unitA); @@ -862,8 +877,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = SpecificWeight.FromNewtonsPerCubicMeter(firstValue); var otherQuantity = SpecificWeight.FromNewtonsPerCubicMeter(secondValue); SpecificWeight maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, SpecificWeight.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -882,7 +897,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -895,6 +910,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(SpecificWeight.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(SpecificWeight.Info.Units, SpecificWeight.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, SpecificWeight.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -989,7 +1016,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = SpecificWeight.FromNewtonsPerCubicMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(SpecificWeight), quantity.As(SpecificWeight.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs index 00b8bdda32..1f405fc37d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/SpeedTestsBase.g.cs @@ -253,6 +253,20 @@ public void Speed_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void SpeedInfo_CreateWithCustomUnitInfos() + { + SpeedUnit[] expectedUnits = [SpeedUnit.MeterPerSecond]; + + Speed.SpeedInfo quantityInfo = Speed.SpeedInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Speed", quantityInfo.Name); + Assert.Equal(Speed.Zero, quantityInfo.Zero); + Assert.Equal(Speed.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void MeterPerSecondToSpeedUnits() { @@ -530,7 +544,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 мм/с", SpeedUnit.MillimeterPerSecond, 4.2)] [InlineData("ru-RU", "4,2 нм/мин", SpeedUnit.NanometerPerMinute, 4.2)] [InlineData("ru-RU", "4,2 нм/с", SpeedUnit.NanometerPerSecond, 4.2)] - public void Parse(string culture, string quantityString, SpeedUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, SpeedUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Speed.Parse(quantityString); @@ -602,7 +616,7 @@ public void Parse(string culture, string quantityString, SpeedUnit expectedUnit, [InlineData("ru-RU", "4,2 мм/с", SpeedUnit.MillimeterPerSecond, 4.2)] [InlineData("ru-RU", "4,2 нм/мин", SpeedUnit.NanometerPerMinute, 4.2)] [InlineData("ru-RU", "4,2 нм/с", SpeedUnit.NanometerPerSecond, 4.2)] - public void TryParse(string culture, string quantityString, SpeedUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, SpeedUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Speed.TryParse(quantityString, out Speed parsed)); @@ -1191,6 +1205,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(SpeedUnit unit) var quantity = Speed.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -1214,64 +1229,66 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(SpeedUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Speed meterpersecond = Speed.FromMetersPerSecond(1); - AssertEx.EqualTolerance(1, Speed.FromCentimetersPerHour(meterpersecond.CentimetersPerHour).MetersPerSecond, CentimetersPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromCentimetersPerMinute(meterpersecond.CentimetersPerMinute).MetersPerSecond, CentimetersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.FromCentimetersPerSecond(meterpersecond.CentimetersPerSecond).MetersPerSecond, CentimetersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromDecimetersPerMinute(meterpersecond.DecimetersPerMinute).MetersPerSecond, DecimetersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.FromDecimetersPerSecond(meterpersecond.DecimetersPerSecond).MetersPerSecond, DecimetersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromFeetPerHour(meterpersecond.FeetPerHour).MetersPerSecond, FeetPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromFeetPerMinute(meterpersecond.FeetPerMinute).MetersPerSecond, FeetPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.FromFeetPerSecond(meterpersecond.FeetPerSecond).MetersPerSecond, FeetPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromInchesPerHour(meterpersecond.InchesPerHour).MetersPerSecond, InchesPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromInchesPerMinute(meterpersecond.InchesPerMinute).MetersPerSecond, InchesPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.FromInchesPerSecond(meterpersecond.InchesPerSecond).MetersPerSecond, InchesPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromKilometersPerHour(meterpersecond.KilometersPerHour).MetersPerSecond, KilometersPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromKilometersPerMinute(meterpersecond.KilometersPerMinute).MetersPerSecond, KilometersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.FromKilometersPerSecond(meterpersecond.KilometersPerSecond).MetersPerSecond, KilometersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromKnots(meterpersecond.Knots).MetersPerSecond, KnotsTolerance); - AssertEx.EqualTolerance(1, Speed.FromMach(meterpersecond.Mach).MetersPerSecond, MachTolerance); - AssertEx.EqualTolerance(1, Speed.FromMetersPerHour(meterpersecond.MetersPerHour).MetersPerSecond, MetersPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromMetersPerMinute(meterpersecond.MetersPerMinute).MetersPerSecond, MetersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.FromMetersPerSecond(meterpersecond.MetersPerSecond).MetersPerSecond, MetersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromMicrometersPerMinute(meterpersecond.MicrometersPerMinute).MetersPerSecond, MicrometersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.FromMicrometersPerSecond(meterpersecond.MicrometersPerSecond).MetersPerSecond, MicrometersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromMilesPerHour(meterpersecond.MilesPerHour).MetersPerSecond, MilesPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromMillimetersPerHour(meterpersecond.MillimetersPerHour).MetersPerSecond, MillimetersPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromMillimetersPerMinute(meterpersecond.MillimetersPerMinute).MetersPerSecond, MillimetersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.FromMillimetersPerSecond(meterpersecond.MillimetersPerSecond).MetersPerSecond, MillimetersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromNanometersPerMinute(meterpersecond.NanometersPerMinute).MetersPerSecond, NanometersPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.FromNanometersPerSecond(meterpersecond.NanometersPerSecond).MetersPerSecond, NanometersPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromUsSurveyFeetPerHour(meterpersecond.UsSurveyFeetPerHour).MetersPerSecond, UsSurveyFeetPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromUsSurveyFeetPerMinute(meterpersecond.UsSurveyFeetPerMinute).MetersPerSecond, UsSurveyFeetPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.FromUsSurveyFeetPerSecond(meterpersecond.UsSurveyFeetPerSecond).MetersPerSecond, UsSurveyFeetPerSecondTolerance); - AssertEx.EqualTolerance(1, Speed.FromYardsPerHour(meterpersecond.YardsPerHour).MetersPerSecond, YardsPerHourTolerance); - AssertEx.EqualTolerance(1, Speed.FromYardsPerMinute(meterpersecond.YardsPerMinute).MetersPerSecond, YardsPerMinuteTolerance); - AssertEx.EqualTolerance(1, Speed.FromYardsPerSecond(meterpersecond.YardsPerSecond).MetersPerSecond, YardsPerSecondTolerance); + Speed meterpersecond = Speed.FromMetersPerSecond(3); + Assert.Equal(3, Speed.FromCentimetersPerHour(meterpersecond.CentimetersPerHour).MetersPerSecond); + Assert.Equal(3, Speed.FromCentimetersPerMinute(meterpersecond.CentimetersPerMinute).MetersPerSecond); + Assert.Equal(3, Speed.FromCentimetersPerSecond(meterpersecond.CentimetersPerSecond).MetersPerSecond); + Assert.Equal(3, Speed.FromDecimetersPerMinute(meterpersecond.DecimetersPerMinute).MetersPerSecond); + Assert.Equal(3, Speed.FromDecimetersPerSecond(meterpersecond.DecimetersPerSecond).MetersPerSecond); + Assert.Equal(3, Speed.FromFeetPerHour(meterpersecond.FeetPerHour).MetersPerSecond); + Assert.Equal(3, Speed.FromFeetPerMinute(meterpersecond.FeetPerMinute).MetersPerSecond); + Assert.Equal(3, Speed.FromFeetPerSecond(meterpersecond.FeetPerSecond).MetersPerSecond); + Assert.Equal(3, Speed.FromInchesPerHour(meterpersecond.InchesPerHour).MetersPerSecond); + Assert.Equal(3, Speed.FromInchesPerMinute(meterpersecond.InchesPerMinute).MetersPerSecond); + Assert.Equal(3, Speed.FromInchesPerSecond(meterpersecond.InchesPerSecond).MetersPerSecond); + Assert.Equal(3, Speed.FromKilometersPerHour(meterpersecond.KilometersPerHour).MetersPerSecond); + Assert.Equal(3, Speed.FromKilometersPerMinute(meterpersecond.KilometersPerMinute).MetersPerSecond); + Assert.Equal(3, Speed.FromKilometersPerSecond(meterpersecond.KilometersPerSecond).MetersPerSecond); + Assert.Equal(3, Speed.FromKnots(meterpersecond.Knots).MetersPerSecond); + Assert.Equal(3, Speed.FromMach(meterpersecond.Mach).MetersPerSecond); + Assert.Equal(3, Speed.FromMetersPerHour(meterpersecond.MetersPerHour).MetersPerSecond); + Assert.Equal(3, Speed.FromMetersPerMinute(meterpersecond.MetersPerMinute).MetersPerSecond); + Assert.Equal(3, Speed.FromMetersPerSecond(meterpersecond.MetersPerSecond).MetersPerSecond); + Assert.Equal(3, Speed.FromMicrometersPerMinute(meterpersecond.MicrometersPerMinute).MetersPerSecond); + Assert.Equal(3, Speed.FromMicrometersPerSecond(meterpersecond.MicrometersPerSecond).MetersPerSecond); + Assert.Equal(3, Speed.FromMilesPerHour(meterpersecond.MilesPerHour).MetersPerSecond); + Assert.Equal(3, Speed.FromMillimetersPerHour(meterpersecond.MillimetersPerHour).MetersPerSecond); + Assert.Equal(3, Speed.FromMillimetersPerMinute(meterpersecond.MillimetersPerMinute).MetersPerSecond); + Assert.Equal(3, Speed.FromMillimetersPerSecond(meterpersecond.MillimetersPerSecond).MetersPerSecond); + Assert.Equal(3, Speed.FromNanometersPerMinute(meterpersecond.NanometersPerMinute).MetersPerSecond); + Assert.Equal(3, Speed.FromNanometersPerSecond(meterpersecond.NanometersPerSecond).MetersPerSecond); + Assert.Equal(3, Speed.FromUsSurveyFeetPerHour(meterpersecond.UsSurveyFeetPerHour).MetersPerSecond); + Assert.Equal(3, Speed.FromUsSurveyFeetPerMinute(meterpersecond.UsSurveyFeetPerMinute).MetersPerSecond); + Assert.Equal(3, Speed.FromUsSurveyFeetPerSecond(meterpersecond.UsSurveyFeetPerSecond).MetersPerSecond); + Assert.Equal(3, Speed.FromYardsPerHour(meterpersecond.YardsPerHour).MetersPerSecond); + Assert.Equal(3, Speed.FromYardsPerMinute(meterpersecond.YardsPerMinute).MetersPerSecond); + Assert.Equal(3, Speed.FromYardsPerSecond(meterpersecond.YardsPerSecond).MetersPerSecond); } [Fact] public void ArithmeticOperators() { Speed v = Speed.FromMetersPerSecond(1); - AssertEx.EqualTolerance(-1, -v.MetersPerSecond, MetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (Speed.FromMetersPerSecond(3)-v).MetersPerSecond, MetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).MetersPerSecond, MetersPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).MetersPerSecond, MetersPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).MetersPerSecond, MetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (Speed.FromMetersPerSecond(10)/5).MetersPerSecond, MetersPerSecondTolerance); - AssertEx.EqualTolerance(2, Speed.FromMetersPerSecond(10)/Speed.FromMetersPerSecond(5), MetersPerSecondTolerance); + Assert.Equal(-1, -v.MetersPerSecond); + Assert.Equal(2, (Speed.FromMetersPerSecond(3) - v).MetersPerSecond); + Assert.Equal(2, (v + v).MetersPerSecond); + Assert.Equal(10, (v * 10).MetersPerSecond); + Assert.Equal(10, (10 * v).MetersPerSecond); + Assert.Equal(2, (Speed.FromMetersPerSecond(10) / 5).MetersPerSecond); + Assert.Equal(2, Speed.FromMetersPerSecond(10) / Speed.FromMetersPerSecond(5)); } [Fact] @@ -1317,8 +1334,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, SpeedUnit.MeterPerSecond, 1, SpeedUnit.MeterPerSecond, true)] // Same value and unit. [InlineData(1, SpeedUnit.MeterPerSecond, 2, SpeedUnit.MeterPerSecond, false)] // Different value. - [InlineData(2, SpeedUnit.MeterPerSecond, 1, SpeedUnit.CentimeterPerHour, false)] // Different value and unit. - [InlineData(1, SpeedUnit.MeterPerSecond, 1, SpeedUnit.CentimeterPerHour, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, SpeedUnit unitA, double valueB, SpeedUnit unitB, bool expectEqual) { var a = new Speed(valueA, unitA); @@ -1378,8 +1393,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Speed.FromMetersPerSecond(firstValue); var otherQuantity = Speed.FromMetersPerSecond(secondValue); Speed maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Speed.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1398,7 +1413,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1411,6 +1426,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Speed.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Speed.Info.Units, Speed.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Speed.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1537,7 +1564,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Speed.FromMetersPerSecond(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Speed), quantity.As(Speed.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs index 1408f7f611..03605ee005 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/StandardVolumeFlowTestsBase.g.cs @@ -157,6 +157,20 @@ public void StandardVolumeFlow_QuantityInfo_ReturnsQuantityInfoDescribingQuantit Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void StandardVolumeFlowInfo_CreateWithCustomUnitInfos() + { + StandardVolumeFlowUnit[] expectedUnits = [StandardVolumeFlowUnit.StandardCubicMeterPerSecond]; + + StandardVolumeFlow.StandardVolumeFlowInfo quantityInfo = StandardVolumeFlow.StandardVolumeFlowInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("StandardVolumeFlow", quantityInfo.Name); + Assert.Equal(StandardVolumeFlow.Zero, quantityInfo.Zero); + Assert.Equal(StandardVolumeFlow.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void StandardCubicMeterPerSecondToStandardVolumeFlowUnits() { @@ -332,7 +346,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 Sm³/min", StandardVolumeFlowUnit.StandardCubicMeterPerMinute, 4.2)] [InlineData("en-US", "4.2 Sm³/s", StandardVolumeFlowUnit.StandardCubicMeterPerSecond, 4.2)] [InlineData("en-US", "4.2 slm", StandardVolumeFlowUnit.StandardLiterPerMinute, 4.2)] - public void Parse(string culture, string quantityString, StandardVolumeFlowUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, StandardVolumeFlowUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = StandardVolumeFlow.Parse(quantityString); @@ -350,7 +364,7 @@ public void Parse(string culture, string quantityString, StandardVolumeFlowUnit [InlineData("en-US", "4.2 Sm³/min", StandardVolumeFlowUnit.StandardCubicMeterPerMinute, 4.2)] [InlineData("en-US", "4.2 Sm³/s", StandardVolumeFlowUnit.StandardCubicMeterPerSecond, 4.2)] [InlineData("en-US", "4.2 slm", StandardVolumeFlowUnit.StandardLiterPerMinute, 4.2)] - public void TryParse(string culture, string quantityString, StandardVolumeFlowUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, StandardVolumeFlowUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(StandardVolumeFlow.TryParse(quantityString, out StandardVolumeFlow parsed)); @@ -555,6 +569,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(StandardVolumeFl var quantity = StandardVolumeFlow.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -578,40 +593,42 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(StandardVolumeFlowU IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - StandardVolumeFlow standardcubicmeterpersecond = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1); - AssertEx.EqualTolerance(1, StandardVolumeFlow.FromStandardCubicCentimetersPerMinute(standardcubicmeterpersecond.StandardCubicCentimetersPerMinute).StandardCubicMetersPerSecond, StandardCubicCentimetersPerMinuteTolerance); - AssertEx.EqualTolerance(1, StandardVolumeFlow.FromStandardCubicFeetPerHour(standardcubicmeterpersecond.StandardCubicFeetPerHour).StandardCubicMetersPerSecond, StandardCubicFeetPerHourTolerance); - AssertEx.EqualTolerance(1, StandardVolumeFlow.FromStandardCubicFeetPerMinute(standardcubicmeterpersecond.StandardCubicFeetPerMinute).StandardCubicMetersPerSecond, StandardCubicFeetPerMinuteTolerance); - AssertEx.EqualTolerance(1, StandardVolumeFlow.FromStandardCubicFeetPerSecond(standardcubicmeterpersecond.StandardCubicFeetPerSecond).StandardCubicMetersPerSecond, StandardCubicFeetPerSecondTolerance); - AssertEx.EqualTolerance(1, StandardVolumeFlow.FromStandardCubicMetersPerDay(standardcubicmeterpersecond.StandardCubicMetersPerDay).StandardCubicMetersPerSecond, StandardCubicMetersPerDayTolerance); - AssertEx.EqualTolerance(1, StandardVolumeFlow.FromStandardCubicMetersPerHour(standardcubicmeterpersecond.StandardCubicMetersPerHour).StandardCubicMetersPerSecond, StandardCubicMetersPerHourTolerance); - AssertEx.EqualTolerance(1, StandardVolumeFlow.FromStandardCubicMetersPerMinute(standardcubicmeterpersecond.StandardCubicMetersPerMinute).StandardCubicMetersPerSecond, StandardCubicMetersPerMinuteTolerance); - AssertEx.EqualTolerance(1, StandardVolumeFlow.FromStandardCubicMetersPerSecond(standardcubicmeterpersecond.StandardCubicMetersPerSecond).StandardCubicMetersPerSecond, StandardCubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(1, StandardVolumeFlow.FromStandardLitersPerMinute(standardcubicmeterpersecond.StandardLitersPerMinute).StandardCubicMetersPerSecond, StandardLitersPerMinuteTolerance); + StandardVolumeFlow standardcubicmeterpersecond = StandardVolumeFlow.FromStandardCubicMetersPerSecond(3); + Assert.Equal(3, StandardVolumeFlow.FromStandardCubicCentimetersPerMinute(standardcubicmeterpersecond.StandardCubicCentimetersPerMinute).StandardCubicMetersPerSecond); + Assert.Equal(3, StandardVolumeFlow.FromStandardCubicFeetPerHour(standardcubicmeterpersecond.StandardCubicFeetPerHour).StandardCubicMetersPerSecond); + Assert.Equal(3, StandardVolumeFlow.FromStandardCubicFeetPerMinute(standardcubicmeterpersecond.StandardCubicFeetPerMinute).StandardCubicMetersPerSecond); + Assert.Equal(3, StandardVolumeFlow.FromStandardCubicFeetPerSecond(standardcubicmeterpersecond.StandardCubicFeetPerSecond).StandardCubicMetersPerSecond); + Assert.Equal(3, StandardVolumeFlow.FromStandardCubicMetersPerDay(standardcubicmeterpersecond.StandardCubicMetersPerDay).StandardCubicMetersPerSecond); + Assert.Equal(3, StandardVolumeFlow.FromStandardCubicMetersPerHour(standardcubicmeterpersecond.StandardCubicMetersPerHour).StandardCubicMetersPerSecond); + Assert.Equal(3, StandardVolumeFlow.FromStandardCubicMetersPerMinute(standardcubicmeterpersecond.StandardCubicMetersPerMinute).StandardCubicMetersPerSecond); + Assert.Equal(3, StandardVolumeFlow.FromStandardCubicMetersPerSecond(standardcubicmeterpersecond.StandardCubicMetersPerSecond).StandardCubicMetersPerSecond); + Assert.Equal(3, StandardVolumeFlow.FromStandardLitersPerMinute(standardcubicmeterpersecond.StandardLitersPerMinute).StandardCubicMetersPerSecond); } [Fact] public void ArithmeticOperators() { StandardVolumeFlow v = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1); - AssertEx.EqualTolerance(-1, -v.StandardCubicMetersPerSecond, StandardCubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (StandardVolumeFlow.FromStandardCubicMetersPerSecond(3)-v).StandardCubicMetersPerSecond, StandardCubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).StandardCubicMetersPerSecond, StandardCubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).StandardCubicMetersPerSecond, StandardCubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).StandardCubicMetersPerSecond, StandardCubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (StandardVolumeFlow.FromStandardCubicMetersPerSecond(10)/5).StandardCubicMetersPerSecond, StandardCubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, StandardVolumeFlow.FromStandardCubicMetersPerSecond(10)/StandardVolumeFlow.FromStandardCubicMetersPerSecond(5), StandardCubicMetersPerSecondTolerance); + Assert.Equal(-1, -v.StandardCubicMetersPerSecond); + Assert.Equal(2, (StandardVolumeFlow.FromStandardCubicMetersPerSecond(3) - v).StandardCubicMetersPerSecond); + Assert.Equal(2, (v + v).StandardCubicMetersPerSecond); + Assert.Equal(10, (v * 10).StandardCubicMetersPerSecond); + Assert.Equal(10, (10 * v).StandardCubicMetersPerSecond); + Assert.Equal(2, (StandardVolumeFlow.FromStandardCubicMetersPerSecond(10) / 5).StandardCubicMetersPerSecond); + Assert.Equal(2, StandardVolumeFlow.FromStandardCubicMetersPerSecond(10) / StandardVolumeFlow.FromStandardCubicMetersPerSecond(5)); } [Fact] @@ -657,8 +674,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, 1, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, true)] // Same value and unit. [InlineData(1, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, 2, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, false)] // Different value. - [InlineData(2, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, 1, StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, false)] // Different value and unit. - [InlineData(1, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, 1, StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, StandardVolumeFlowUnit unitA, double valueB, StandardVolumeFlowUnit unitB, bool expectEqual) { var a = new StandardVolumeFlow(valueA, unitA); @@ -718,8 +733,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(firstValue); var otherQuantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(secondValue); StandardVolumeFlow maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, StandardVolumeFlow.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -738,7 +753,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -751,6 +766,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(StandardVolumeFlow.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(StandardVolumeFlow.Info.Units, StandardVolumeFlow.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, StandardVolumeFlow.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -829,7 +856,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = StandardVolumeFlow.FromStandardCubicMetersPerSecond(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(StandardVolumeFlow), quantity.As(StandardVolumeFlow.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs index bcfbcb8b46..e4cceb19d1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureChangeRateTestsBase.g.cs @@ -189,6 +189,20 @@ public void TemperatureChangeRate_QuantityInfo_ReturnsQuantityInfoDescribingQuan Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void TemperatureChangeRateInfo_CreateWithCustomUnitInfos() + { + TemperatureChangeRateUnit[] expectedUnits = [TemperatureChangeRateUnit.DegreeCelsiusPerSecond]; + + TemperatureChangeRate.TemperatureChangeRateInfo quantityInfo = TemperatureChangeRate.TemperatureChangeRateInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("TemperatureChangeRate", quantityInfo.Name); + Assert.Equal(TemperatureChangeRate.Zero, quantityInfo.Zero); + Assert.Equal(TemperatureChangeRate.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void DegreeCelsiusPerSecondToTemperatureChangeRateUnits() { @@ -388,7 +402,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 µ°C/s", TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, 4.2)] [InlineData("en-US", "4.2 m°C/s", TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, 4.2)] [InlineData("en-US", "4.2 n°C/s", TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, 4.2)] - public void Parse(string culture, string quantityString, TemperatureChangeRateUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, TemperatureChangeRateUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = TemperatureChangeRate.Parse(quantityString); @@ -414,7 +428,7 @@ public void Parse(string culture, string quantityString, TemperatureChangeRateUn [InlineData("en-US", "4.2 µ°C/s", TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, 4.2)] [InlineData("en-US", "4.2 m°C/s", TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, 4.2)] [InlineData("en-US", "4.2 n°C/s", TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, 4.2)] - public void TryParse(string culture, string quantityString, TemperatureChangeRateUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, TemperatureChangeRateUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(TemperatureChangeRate.TryParse(quantityString, out TemperatureChangeRate parsed)); @@ -691,6 +705,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TemperatureChang var quantity = TemperatureChangeRate.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -714,48 +729,50 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(TemperatureChangeRa IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - TemperatureChangeRate degreecelsiuspersecond = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromCentidegreesCelsiusPerSecond(degreecelsiuspersecond.CentidegreesCelsiusPerSecond).DegreesCelsiusPerSecond, CentidegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromDecadegreesCelsiusPerSecond(degreecelsiuspersecond.DecadegreesCelsiusPerSecond).DegreesCelsiusPerSecond, DecadegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromDecidegreesCelsiusPerSecond(degreecelsiuspersecond.DecidegreesCelsiusPerSecond).DegreesCelsiusPerSecond, DecidegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromDegreesCelsiusPerHour(degreecelsiuspersecond.DegreesCelsiusPerHour).DegreesCelsiusPerSecond, DegreesCelsiusPerHourTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromDegreesCelsiusPerMinute(degreecelsiuspersecond.DegreesCelsiusPerMinute).DegreesCelsiusPerSecond, DegreesCelsiusPerMinuteTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromDegreesCelsiusPerSecond(degreecelsiuspersecond.DegreesCelsiusPerSecond).DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromDegreesFahrenheitPerHour(degreecelsiuspersecond.DegreesFahrenheitPerHour).DegreesCelsiusPerSecond, DegreesFahrenheitPerHourTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromDegreesFahrenheitPerMinute(degreecelsiuspersecond.DegreesFahrenheitPerMinute).DegreesCelsiusPerSecond, DegreesFahrenheitPerMinuteTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromDegreesFahrenheitPerSecond(degreecelsiuspersecond.DegreesFahrenheitPerSecond).DegreesCelsiusPerSecond, DegreesFahrenheitPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromDegreesKelvinPerHour(degreecelsiuspersecond.DegreesKelvinPerHour).DegreesCelsiusPerSecond, DegreesKelvinPerHourTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromDegreesKelvinPerMinute(degreecelsiuspersecond.DegreesKelvinPerMinute).DegreesCelsiusPerSecond, DegreesKelvinPerMinuteTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromDegreesKelvinPerSecond(degreecelsiuspersecond.DegreesKelvinPerSecond).DegreesCelsiusPerSecond, DegreesKelvinPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromHectodegreesCelsiusPerSecond(degreecelsiuspersecond.HectodegreesCelsiusPerSecond).DegreesCelsiusPerSecond, HectodegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromKilodegreesCelsiusPerSecond(degreecelsiuspersecond.KilodegreesCelsiusPerSecond).DegreesCelsiusPerSecond, KilodegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromMicrodegreesCelsiusPerSecond(degreecelsiuspersecond.MicrodegreesCelsiusPerSecond).DegreesCelsiusPerSecond, MicrodegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromMillidegreesCelsiusPerSecond(degreecelsiuspersecond.MillidegreesCelsiusPerSecond).DegreesCelsiusPerSecond, MillidegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(1, TemperatureChangeRate.FromNanodegreesCelsiusPerSecond(degreecelsiuspersecond.NanodegreesCelsiusPerSecond).DegreesCelsiusPerSecond, NanodegreesCelsiusPerSecondTolerance); + TemperatureChangeRate degreecelsiuspersecond = TemperatureChangeRate.FromDegreesCelsiusPerSecond(3); + Assert.Equal(3, TemperatureChangeRate.FromCentidegreesCelsiusPerSecond(degreecelsiuspersecond.CentidegreesCelsiusPerSecond).DegreesCelsiusPerSecond); + Assert.Equal(3, TemperatureChangeRate.FromDecadegreesCelsiusPerSecond(degreecelsiuspersecond.DecadegreesCelsiusPerSecond).DegreesCelsiusPerSecond); + Assert.Equal(3, TemperatureChangeRate.FromDecidegreesCelsiusPerSecond(degreecelsiuspersecond.DecidegreesCelsiusPerSecond).DegreesCelsiusPerSecond); + Assert.Equal(3, TemperatureChangeRate.FromDegreesCelsiusPerHour(degreecelsiuspersecond.DegreesCelsiusPerHour).DegreesCelsiusPerSecond); + Assert.Equal(3, TemperatureChangeRate.FromDegreesCelsiusPerMinute(degreecelsiuspersecond.DegreesCelsiusPerMinute).DegreesCelsiusPerSecond); + Assert.Equal(3, TemperatureChangeRate.FromDegreesCelsiusPerSecond(degreecelsiuspersecond.DegreesCelsiusPerSecond).DegreesCelsiusPerSecond); + Assert.Equal(3, TemperatureChangeRate.FromDegreesFahrenheitPerHour(degreecelsiuspersecond.DegreesFahrenheitPerHour).DegreesCelsiusPerSecond); + Assert.Equal(3, TemperatureChangeRate.FromDegreesFahrenheitPerMinute(degreecelsiuspersecond.DegreesFahrenheitPerMinute).DegreesCelsiusPerSecond); + Assert.Equal(3, TemperatureChangeRate.FromDegreesFahrenheitPerSecond(degreecelsiuspersecond.DegreesFahrenheitPerSecond).DegreesCelsiusPerSecond); + Assert.Equal(3, TemperatureChangeRate.FromDegreesKelvinPerHour(degreecelsiuspersecond.DegreesKelvinPerHour).DegreesCelsiusPerSecond); + Assert.Equal(3, TemperatureChangeRate.FromDegreesKelvinPerMinute(degreecelsiuspersecond.DegreesKelvinPerMinute).DegreesCelsiusPerSecond); + Assert.Equal(3, TemperatureChangeRate.FromDegreesKelvinPerSecond(degreecelsiuspersecond.DegreesKelvinPerSecond).DegreesCelsiusPerSecond); + Assert.Equal(3, TemperatureChangeRate.FromHectodegreesCelsiusPerSecond(degreecelsiuspersecond.HectodegreesCelsiusPerSecond).DegreesCelsiusPerSecond); + Assert.Equal(3, TemperatureChangeRate.FromKilodegreesCelsiusPerSecond(degreecelsiuspersecond.KilodegreesCelsiusPerSecond).DegreesCelsiusPerSecond); + Assert.Equal(3, TemperatureChangeRate.FromMicrodegreesCelsiusPerSecond(degreecelsiuspersecond.MicrodegreesCelsiusPerSecond).DegreesCelsiusPerSecond); + Assert.Equal(3, TemperatureChangeRate.FromMillidegreesCelsiusPerSecond(degreecelsiuspersecond.MillidegreesCelsiusPerSecond).DegreesCelsiusPerSecond); + Assert.Equal(3, TemperatureChangeRate.FromNanodegreesCelsiusPerSecond(degreecelsiuspersecond.NanodegreesCelsiusPerSecond).DegreesCelsiusPerSecond); } [Fact] public void ArithmeticOperators() { TemperatureChangeRate v = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1); - AssertEx.EqualTolerance(-1, -v.DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(2, (TemperatureChangeRate.FromDegreesCelsiusPerSecond(3)-v).DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(2, (TemperatureChangeRate.FromDegreesCelsiusPerSecond(10)/5).DegreesCelsiusPerSecond, DegreesCelsiusPerSecondTolerance); - AssertEx.EqualTolerance(2, TemperatureChangeRate.FromDegreesCelsiusPerSecond(10)/TemperatureChangeRate.FromDegreesCelsiusPerSecond(5), DegreesCelsiusPerSecondTolerance); + Assert.Equal(-1, -v.DegreesCelsiusPerSecond); + Assert.Equal(2, (TemperatureChangeRate.FromDegreesCelsiusPerSecond(3) - v).DegreesCelsiusPerSecond); + Assert.Equal(2, (v + v).DegreesCelsiusPerSecond); + Assert.Equal(10, (v * 10).DegreesCelsiusPerSecond); + Assert.Equal(10, (10 * v).DegreesCelsiusPerSecond); + Assert.Equal(2, (TemperatureChangeRate.FromDegreesCelsiusPerSecond(10) / 5).DegreesCelsiusPerSecond); + Assert.Equal(2, TemperatureChangeRate.FromDegreesCelsiusPerSecond(10) / TemperatureChangeRate.FromDegreesCelsiusPerSecond(5)); } [Fact] @@ -801,8 +818,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, 1, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, true)] // Same value and unit. [InlineData(1, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, 2, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, false)] // Different value. - [InlineData(2, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, 1, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, false)] // Different value and unit. - [InlineData(1, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, 1, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, TemperatureChangeRateUnit unitA, double valueB, TemperatureChangeRateUnit unitB, bool expectEqual) { var a = new TemperatureChangeRate(valueA, unitA); @@ -862,8 +877,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(firstValue); var otherQuantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(secondValue); TemperatureChangeRate maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, TemperatureChangeRate.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -882,7 +897,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -895,6 +910,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(TemperatureChangeRate.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(TemperatureChangeRate.Info.Units, TemperatureChangeRate.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, TemperatureChangeRate.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -989,7 +1016,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = TemperatureChangeRate.FromDegreesCelsiusPerSecond(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(TemperatureChangeRate), quantity.As(TemperatureChangeRate.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs index 1aae87ef4f..172a968dc1 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureDeltaTestsBase.g.cs @@ -157,6 +157,20 @@ public void TemperatureDelta_QuantityInfo_ReturnsQuantityInfoDescribingQuantity( Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void TemperatureDeltaInfo_CreateWithCustomUnitInfos() + { + TemperatureDeltaUnit[] expectedUnits = [TemperatureDeltaUnit.Kelvin]; + + TemperatureDelta.TemperatureDeltaInfo quantityInfo = TemperatureDelta.TemperatureDeltaInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("TemperatureDelta", quantityInfo.Name); + Assert.Equal(TemperatureDelta.Zero, quantityInfo.Zero); + Assert.Equal(TemperatureDelta.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void KelvinToTemperatureDeltaUnits() { @@ -332,7 +346,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 ∆°Rø", TemperatureDeltaUnit.DegreeRoemer, 4.2)] [InlineData("en-US", "4.2 ∆K", TemperatureDeltaUnit.Kelvin, 4.2)] [InlineData("en-US", "4.2 ∆m°C", TemperatureDeltaUnit.MillidegreeCelsius, 4.2)] - public void Parse(string culture, string quantityString, TemperatureDeltaUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, TemperatureDeltaUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = TemperatureDelta.Parse(quantityString); @@ -350,7 +364,7 @@ public void Parse(string culture, string quantityString, TemperatureDeltaUnit ex [InlineData("en-US", "4.2 ∆°Rø", TemperatureDeltaUnit.DegreeRoemer, 4.2)] [InlineData("en-US", "4.2 ∆K", TemperatureDeltaUnit.Kelvin, 4.2)] [InlineData("en-US", "4.2 ∆m°C", TemperatureDeltaUnit.MillidegreeCelsius, 4.2)] - public void TryParse(string culture, string quantityString, TemperatureDeltaUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, TemperatureDeltaUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(TemperatureDelta.TryParse(quantityString, out TemperatureDelta parsed)); @@ -555,6 +569,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TemperatureDelta var quantity = TemperatureDelta.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -578,40 +593,42 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(TemperatureDeltaUni IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - TemperatureDelta kelvin = TemperatureDelta.FromKelvins(1); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesCelsius(kelvin.DegreesCelsius).Kelvins, DegreesCelsiusTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesDelisle(kelvin.DegreesDelisle).Kelvins, DegreesDelisleTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesFahrenheit(kelvin.DegreesFahrenheit).Kelvins, DegreesFahrenheitTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesNewton(kelvin.DegreesNewton).Kelvins, DegreesNewtonTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesRankine(kelvin.DegreesRankine).Kelvins, DegreesRankineTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesReaumur(kelvin.DegreesReaumur).Kelvins, DegreesReaumurTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromDegreesRoemer(kelvin.DegreesRoemer).Kelvins, DegreesRoemerTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromKelvins(kelvin.Kelvins).Kelvins, KelvinsTolerance); - AssertEx.EqualTolerance(1, TemperatureDelta.FromMillidegreesCelsius(kelvin.MillidegreesCelsius).Kelvins, MillidegreesCelsiusTolerance); + TemperatureDelta kelvin = TemperatureDelta.FromKelvins(3); + Assert.Equal(3, TemperatureDelta.FromDegreesCelsius(kelvin.DegreesCelsius).Kelvins); + Assert.Equal(3, TemperatureDelta.FromDegreesDelisle(kelvin.DegreesDelisle).Kelvins); + Assert.Equal(3, TemperatureDelta.FromDegreesFahrenheit(kelvin.DegreesFahrenheit).Kelvins); + Assert.Equal(3, TemperatureDelta.FromDegreesNewton(kelvin.DegreesNewton).Kelvins); + Assert.Equal(3, TemperatureDelta.FromDegreesRankine(kelvin.DegreesRankine).Kelvins); + Assert.Equal(3, TemperatureDelta.FromDegreesReaumur(kelvin.DegreesReaumur).Kelvins); + Assert.Equal(3, TemperatureDelta.FromDegreesRoemer(kelvin.DegreesRoemer).Kelvins); + Assert.Equal(3, TemperatureDelta.FromKelvins(kelvin.Kelvins).Kelvins); + Assert.Equal(3, TemperatureDelta.FromMillidegreesCelsius(kelvin.MillidegreesCelsius).Kelvins); } [Fact] public void ArithmeticOperators() { TemperatureDelta v = TemperatureDelta.FromKelvins(1); - AssertEx.EqualTolerance(-1, -v.Kelvins, KelvinsTolerance); - AssertEx.EqualTolerance(2, (TemperatureDelta.FromKelvins(3)-v).Kelvins, KelvinsTolerance); - AssertEx.EqualTolerance(2, (v + v).Kelvins, KelvinsTolerance); - AssertEx.EqualTolerance(10, (v*10).Kelvins, KelvinsTolerance); - AssertEx.EqualTolerance(10, (10*v).Kelvins, KelvinsTolerance); - AssertEx.EqualTolerance(2, (TemperatureDelta.FromKelvins(10)/5).Kelvins, KelvinsTolerance); - AssertEx.EqualTolerance(2, TemperatureDelta.FromKelvins(10)/TemperatureDelta.FromKelvins(5), KelvinsTolerance); + Assert.Equal(-1, -v.Kelvins); + Assert.Equal(2, (TemperatureDelta.FromKelvins(3) - v).Kelvins); + Assert.Equal(2, (v + v).Kelvins); + Assert.Equal(10, (v * 10).Kelvins); + Assert.Equal(10, (10 * v).Kelvins); + Assert.Equal(2, (TemperatureDelta.FromKelvins(10) / 5).Kelvins); + Assert.Equal(2, TemperatureDelta.FromKelvins(10) / TemperatureDelta.FromKelvins(5)); } [Fact] @@ -657,8 +674,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, TemperatureDeltaUnit.Kelvin, 1, TemperatureDeltaUnit.Kelvin, true)] // Same value and unit. [InlineData(1, TemperatureDeltaUnit.Kelvin, 2, TemperatureDeltaUnit.Kelvin, false)] // Different value. - [InlineData(2, TemperatureDeltaUnit.Kelvin, 1, TemperatureDeltaUnit.DegreeCelsius, false)] // Different value and unit. - [InlineData(1, TemperatureDeltaUnit.Kelvin, 1, TemperatureDeltaUnit.DegreeCelsius, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, TemperatureDeltaUnit unitA, double valueB, TemperatureDeltaUnit unitB, bool expectEqual) { var a = new TemperatureDelta(valueA, unitA); @@ -718,8 +733,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = TemperatureDelta.FromKelvins(firstValue); var otherQuantity = TemperatureDelta.FromKelvins(secondValue); TemperatureDelta maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, TemperatureDelta.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -738,7 +753,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -751,6 +766,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(TemperatureDelta.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(TemperatureDelta.Info.Units, TemperatureDelta.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, TemperatureDelta.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -829,7 +856,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = TemperatureDelta.FromKelvins(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(TemperatureDelta), quantity.As(TemperatureDelta.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs index 0a2f9cd54a..b54e435ada 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureGradientTestsBase.g.cs @@ -137,6 +137,20 @@ public void TemperatureGradient_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void TemperatureGradientInfo_CreateWithCustomUnitInfos() + { + TemperatureGradientUnit[] expectedUnits = [TemperatureGradientUnit.KelvinPerMeter]; + + TemperatureGradient.TemperatureGradientInfo quantityInfo = TemperatureGradient.TemperatureGradientInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("TemperatureGradient", quantityInfo.Name); + Assert.Equal(TemperatureGradient.Zero, quantityInfo.Zero); + Assert.Equal(TemperatureGradient.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void KelvinPerMeterToTemperatureGradientUnits() { @@ -297,7 +311,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 ∆°C/m", TemperatureGradientUnit.DegreeCelsiusPerMeter, 4.2)] [InlineData("en-US", "4.2 ∆°F/ft", TemperatureGradientUnit.DegreeFahrenheitPerFoot, 4.2)] [InlineData("en-US", "4.2 ∆°K/m", TemperatureGradientUnit.KelvinPerMeter, 4.2)] - public void Parse(string culture, string quantityString, TemperatureGradientUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, TemperatureGradientUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = TemperatureGradient.Parse(quantityString); @@ -310,7 +324,7 @@ public void Parse(string culture, string quantityString, TemperatureGradientUnit [InlineData("en-US", "4.2 ∆°C/m", TemperatureGradientUnit.DegreeCelsiusPerMeter, 4.2)] [InlineData("en-US", "4.2 ∆°F/ft", TemperatureGradientUnit.DegreeFahrenheitPerFoot, 4.2)] [InlineData("en-US", "4.2 ∆°K/m", TemperatureGradientUnit.KelvinPerMeter, 4.2)] - public void TryParse(string culture, string quantityString, TemperatureGradientUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, TemperatureGradientUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(TemperatureGradient.TryParse(quantityString, out TemperatureGradient parsed)); @@ -470,6 +484,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TemperatureGradi var quantity = TemperatureGradient.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -493,35 +508,37 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(TemperatureGradient IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - TemperatureGradient kelvinpermeter = TemperatureGradient.FromKelvinsPerMeter(1); - AssertEx.EqualTolerance(1, TemperatureGradient.FromDegreesCelsiusPerKilometer(kelvinpermeter.DegreesCelsiusPerKilometer).KelvinsPerMeter, DegreesCelsiusPerKilometerTolerance); - AssertEx.EqualTolerance(1, TemperatureGradient.FromDegreesCelsiusPerMeter(kelvinpermeter.DegreesCelsiusPerMeter).KelvinsPerMeter, DegreesCelsiusPerMeterTolerance); - AssertEx.EqualTolerance(1, TemperatureGradient.FromDegreesFahrenheitPerFoot(kelvinpermeter.DegreesFahrenheitPerFoot).KelvinsPerMeter, DegreesFahrenheitPerFootTolerance); - AssertEx.EqualTolerance(1, TemperatureGradient.FromKelvinsPerMeter(kelvinpermeter.KelvinsPerMeter).KelvinsPerMeter, KelvinsPerMeterTolerance); + TemperatureGradient kelvinpermeter = TemperatureGradient.FromKelvinsPerMeter(3); + Assert.Equal(3, TemperatureGradient.FromDegreesCelsiusPerKilometer(kelvinpermeter.DegreesCelsiusPerKilometer).KelvinsPerMeter); + Assert.Equal(3, TemperatureGradient.FromDegreesCelsiusPerMeter(kelvinpermeter.DegreesCelsiusPerMeter).KelvinsPerMeter); + Assert.Equal(3, TemperatureGradient.FromDegreesFahrenheitPerFoot(kelvinpermeter.DegreesFahrenheitPerFoot).KelvinsPerMeter); + Assert.Equal(3, TemperatureGradient.FromKelvinsPerMeter(kelvinpermeter.KelvinsPerMeter).KelvinsPerMeter); } [Fact] public void ArithmeticOperators() { TemperatureGradient v = TemperatureGradient.FromKelvinsPerMeter(1); - AssertEx.EqualTolerance(-1, -v.KelvinsPerMeter, KelvinsPerMeterTolerance); - AssertEx.EqualTolerance(2, (TemperatureGradient.FromKelvinsPerMeter(3)-v).KelvinsPerMeter, KelvinsPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).KelvinsPerMeter, KelvinsPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).KelvinsPerMeter, KelvinsPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).KelvinsPerMeter, KelvinsPerMeterTolerance); - AssertEx.EqualTolerance(2, (TemperatureGradient.FromKelvinsPerMeter(10)/5).KelvinsPerMeter, KelvinsPerMeterTolerance); - AssertEx.EqualTolerance(2, TemperatureGradient.FromKelvinsPerMeter(10)/TemperatureGradient.FromKelvinsPerMeter(5), KelvinsPerMeterTolerance); + Assert.Equal(-1, -v.KelvinsPerMeter); + Assert.Equal(2, (TemperatureGradient.FromKelvinsPerMeter(3) - v).KelvinsPerMeter); + Assert.Equal(2, (v + v).KelvinsPerMeter); + Assert.Equal(10, (v * 10).KelvinsPerMeter); + Assert.Equal(10, (10 * v).KelvinsPerMeter); + Assert.Equal(2, (TemperatureGradient.FromKelvinsPerMeter(10) / 5).KelvinsPerMeter); + Assert.Equal(2, TemperatureGradient.FromKelvinsPerMeter(10) / TemperatureGradient.FromKelvinsPerMeter(5)); } [Fact] @@ -567,8 +584,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, TemperatureGradientUnit.KelvinPerMeter, 1, TemperatureGradientUnit.KelvinPerMeter, true)] // Same value and unit. [InlineData(1, TemperatureGradientUnit.KelvinPerMeter, 2, TemperatureGradientUnit.KelvinPerMeter, false)] // Different value. - [InlineData(2, TemperatureGradientUnit.KelvinPerMeter, 1, TemperatureGradientUnit.DegreeCelsiusPerKilometer, false)] // Different value and unit. - [InlineData(1, TemperatureGradientUnit.KelvinPerMeter, 1, TemperatureGradientUnit.DegreeCelsiusPerKilometer, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, TemperatureGradientUnit unitA, double valueB, TemperatureGradientUnit unitB, bool expectEqual) { var a = new TemperatureGradient(valueA, unitA); @@ -628,8 +643,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = TemperatureGradient.FromKelvinsPerMeter(firstValue); var otherQuantity = TemperatureGradient.FromKelvinsPerMeter(secondValue); TemperatureGradient maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, TemperatureGradient.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -648,7 +663,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -661,6 +676,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(TemperatureGradient.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(TemperatureGradient.Info.Units, TemperatureGradient.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, TemperatureGradient.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -729,7 +756,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = TemperatureGradient.FromKelvinsPerMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(TemperatureGradient), quantity.As(TemperatureGradient.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs index 6b545e8793..edd8bebe9c 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TemperatureTestsBase.g.cs @@ -161,6 +161,20 @@ public void Temperature_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void TemperatureInfo_CreateWithCustomUnitInfos() + { + TemperatureUnit[] expectedUnits = [TemperatureUnit.Kelvin]; + + Temperature.TemperatureInfo quantityInfo = Temperature.TemperatureInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Temperature", quantityInfo.Name); + Assert.Equal(Temperature.Zero, quantityInfo.Zero); + Assert.Equal(Temperature.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void KelvinToTemperatureUnits() { @@ -339,7 +353,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 K", TemperatureUnit.Kelvin, 4.2)] [InlineData("en-US", "4.2 m°C", TemperatureUnit.MillidegreeCelsius, 4.2)] [InlineData("en-US", "4.2 T⊙", TemperatureUnit.SolarTemperature, 4.2)] - public void Parse(string culture, string quantityString, TemperatureUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, TemperatureUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Temperature.Parse(quantityString); @@ -358,7 +372,7 @@ public void Parse(string culture, string quantityString, TemperatureUnit expecte [InlineData("en-US", "4.2 K", TemperatureUnit.Kelvin, 4.2)] [InlineData("en-US", "4.2 m°C", TemperatureUnit.MillidegreeCelsius, 4.2)] [InlineData("en-US", "4.2 T⊙", TemperatureUnit.SolarTemperature, 4.2)] - public void TryParse(string culture, string quantityString, TemperatureUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, TemperatureUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Temperature.TryParse(quantityString, out Temperature parsed)); @@ -572,6 +586,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TemperatureUnit var quantity = Temperature.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -595,28 +610,30 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(TemperatureUnit uni IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Temperature kelvin = Temperature.FromKelvins(1); - AssertEx.EqualTolerance(1, Temperature.FromDegreesCelsius(kelvin.DegreesCelsius).Kelvins, DegreesCelsiusTolerance); - AssertEx.EqualTolerance(1, Temperature.FromDegreesDelisle(kelvin.DegreesDelisle).Kelvins, DegreesDelisleTolerance); - AssertEx.EqualTolerance(1, Temperature.FromDegreesFahrenheit(kelvin.DegreesFahrenheit).Kelvins, DegreesFahrenheitTolerance); - AssertEx.EqualTolerance(1, Temperature.FromDegreesNewton(kelvin.DegreesNewton).Kelvins, DegreesNewtonTolerance); - AssertEx.EqualTolerance(1, Temperature.FromDegreesRankine(kelvin.DegreesRankine).Kelvins, DegreesRankineTolerance); - AssertEx.EqualTolerance(1, Temperature.FromDegreesReaumur(kelvin.DegreesReaumur).Kelvins, DegreesReaumurTolerance); - AssertEx.EqualTolerance(1, Temperature.FromDegreesRoemer(kelvin.DegreesRoemer).Kelvins, DegreesRoemerTolerance); - AssertEx.EqualTolerance(1, Temperature.FromKelvins(kelvin.Kelvins).Kelvins, KelvinsTolerance); - AssertEx.EqualTolerance(1, Temperature.FromMillidegreesCelsius(kelvin.MillidegreesCelsius).Kelvins, MillidegreesCelsiusTolerance); - AssertEx.EqualTolerance(1, Temperature.FromSolarTemperatures(kelvin.SolarTemperatures).Kelvins, SolarTemperaturesTolerance); + Temperature kelvin = Temperature.FromKelvins(3); + Assert.Equal(3, Temperature.FromDegreesCelsius(kelvin.DegreesCelsius).Kelvins); + Assert.Equal(3, Temperature.FromDegreesDelisle(kelvin.DegreesDelisle).Kelvins); + Assert.Equal(3, Temperature.FromDegreesFahrenheit(kelvin.DegreesFahrenheit).Kelvins); + Assert.Equal(3, Temperature.FromDegreesNewton(kelvin.DegreesNewton).Kelvins); + Assert.Equal(3, Temperature.FromDegreesRankine(kelvin.DegreesRankine).Kelvins); + Assert.Equal(3, Temperature.FromDegreesReaumur(kelvin.DegreesReaumur).Kelvins); + Assert.Equal(3, Temperature.FromDegreesRoemer(kelvin.DegreesRoemer).Kelvins); + Assert.Equal(3, Temperature.FromKelvins(kelvin.Kelvins).Kelvins); + Assert.Equal(3, Temperature.FromMillidegreesCelsius(kelvin.MillidegreesCelsius).Kelvins); + Assert.Equal(3, Temperature.FromSolarTemperatures(kelvin.SolarTemperatures).Kelvins); } @@ -663,8 +680,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, TemperatureUnit.Kelvin, 1, TemperatureUnit.Kelvin, true)] // Same value and unit. [InlineData(1, TemperatureUnit.Kelvin, 2, TemperatureUnit.Kelvin, false)] // Different value. - [InlineData(2, TemperatureUnit.Kelvin, 1, TemperatureUnit.DegreeCelsius, false)] // Different value and unit. - [InlineData(1, TemperatureUnit.Kelvin, 1, TemperatureUnit.DegreeCelsius, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, TemperatureUnit unitA, double valueB, TemperatureUnit unitB, bool expectEqual) { var a = new Temperature(valueA, unitA); @@ -724,8 +739,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Temperature.FromKelvins(firstValue); var otherQuantity = Temperature.FromKelvins(secondValue); TemperatureDelta maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, TemperatureDelta.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -744,7 +759,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -757,6 +772,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Temperature.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Temperature.Info.Units, Temperature.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Temperature.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -837,7 +864,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Temperature.FromKelvins(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Temperature), quantity.As(Temperature.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } } diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs index 1f8bf1aa08..5e796490f7 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalConductivityTestsBase.g.cs @@ -129,6 +129,20 @@ public void ThermalConductivity_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ThermalConductivityInfo_CreateWithCustomUnitInfos() + { + ThermalConductivityUnit[] expectedUnits = [ThermalConductivityUnit.WattPerMeterKelvin]; + + ThermalConductivity.ThermalConductivityInfo quantityInfo = ThermalConductivity.ThermalConductivityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ThermalConductivity", quantityInfo.Name); + Assert.Equal(ThermalConductivity.Zero, quantityInfo.Zero); + Assert.Equal(ThermalConductivity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void WattPerMeterKelvinToThermalConductivityUnits() { @@ -283,7 +297,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Theory] [InlineData("en-US", "4.2 BTU/(h·ft·°F)", ThermalConductivityUnit.BtuPerHourFootFahrenheit, 4.2)] [InlineData("en-US", "4.2 W/(m·K)", ThermalConductivityUnit.WattPerMeterKelvin, 4.2)] - public void Parse(string culture, string quantityString, ThermalConductivityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ThermalConductivityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ThermalConductivity.Parse(quantityString); @@ -294,7 +308,7 @@ public void Parse(string culture, string quantityString, ThermalConductivityUnit [Theory] [InlineData("en-US", "4.2 BTU/(h·ft·°F)", ThermalConductivityUnit.BtuPerHourFootFahrenheit, 4.2)] [InlineData("en-US", "4.2 W/(m·K)", ThermalConductivityUnit.WattPerMeterKelvin, 4.2)] - public void TryParse(string culture, string quantityString, ThermalConductivityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ThermalConductivityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ThermalConductivity.TryParse(quantityString, out ThermalConductivity parsed)); @@ -436,6 +450,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ThermalConductiv var quantity = ThermalConductivity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -459,33 +474,35 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ThermalConductivity IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ThermalConductivity wattpermeterkelvin = ThermalConductivity.FromWattsPerMeterKelvin(1); - AssertEx.EqualTolerance(1, ThermalConductivity.FromBtusPerHourFootFahrenheit(wattpermeterkelvin.BtusPerHourFootFahrenheit).WattsPerMeterKelvin, BtusPerHourFootFahrenheitTolerance); - AssertEx.EqualTolerance(1, ThermalConductivity.FromWattsPerMeterKelvin(wattpermeterkelvin.WattsPerMeterKelvin).WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); + ThermalConductivity wattpermeterkelvin = ThermalConductivity.FromWattsPerMeterKelvin(3); + Assert.Equal(3, ThermalConductivity.FromBtusPerHourFootFahrenheit(wattpermeterkelvin.BtusPerHourFootFahrenheit).WattsPerMeterKelvin); + Assert.Equal(3, ThermalConductivity.FromWattsPerMeterKelvin(wattpermeterkelvin.WattsPerMeterKelvin).WattsPerMeterKelvin); } [Fact] public void ArithmeticOperators() { ThermalConductivity v = ThermalConductivity.FromWattsPerMeterKelvin(1); - AssertEx.EqualTolerance(-1, -v.WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); - AssertEx.EqualTolerance(2, (ThermalConductivity.FromWattsPerMeterKelvin(3)-v).WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); - AssertEx.EqualTolerance(2, (v + v).WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); - AssertEx.EqualTolerance(10, (v*10).WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); - AssertEx.EqualTolerance(10, (10*v).WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); - AssertEx.EqualTolerance(2, (ThermalConductivity.FromWattsPerMeterKelvin(10)/5).WattsPerMeterKelvin, WattsPerMeterKelvinTolerance); - AssertEx.EqualTolerance(2, ThermalConductivity.FromWattsPerMeterKelvin(10)/ThermalConductivity.FromWattsPerMeterKelvin(5), WattsPerMeterKelvinTolerance); + Assert.Equal(-1, -v.WattsPerMeterKelvin); + Assert.Equal(2, (ThermalConductivity.FromWattsPerMeterKelvin(3) - v).WattsPerMeterKelvin); + Assert.Equal(2, (v + v).WattsPerMeterKelvin); + Assert.Equal(10, (v * 10).WattsPerMeterKelvin); + Assert.Equal(10, (10 * v).WattsPerMeterKelvin); + Assert.Equal(2, (ThermalConductivity.FromWattsPerMeterKelvin(10) / 5).WattsPerMeterKelvin); + Assert.Equal(2, ThermalConductivity.FromWattsPerMeterKelvin(10) / ThermalConductivity.FromWattsPerMeterKelvin(5)); } [Fact] @@ -531,8 +548,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ThermalConductivityUnit.WattPerMeterKelvin, 1, ThermalConductivityUnit.WattPerMeterKelvin, true)] // Same value and unit. [InlineData(1, ThermalConductivityUnit.WattPerMeterKelvin, 2, ThermalConductivityUnit.WattPerMeterKelvin, false)] // Different value. - [InlineData(2, ThermalConductivityUnit.WattPerMeterKelvin, 1, ThermalConductivityUnit.BtuPerHourFootFahrenheit, false)] // Different value and unit. - [InlineData(1, ThermalConductivityUnit.WattPerMeterKelvin, 1, ThermalConductivityUnit.BtuPerHourFootFahrenheit, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ThermalConductivityUnit unitA, double valueB, ThermalConductivityUnit unitB, bool expectEqual) { var a = new ThermalConductivity(valueA, unitA); @@ -592,8 +607,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ThermalConductivity.FromWattsPerMeterKelvin(firstValue); var otherQuantity = ThermalConductivity.FromWattsPerMeterKelvin(secondValue); ThermalConductivity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ThermalConductivity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -612,7 +627,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -625,6 +640,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ThermalConductivity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ThermalConductivity.Info.Units, ThermalConductivity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ThermalConductivity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -689,7 +716,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ThermalConductivity.FromWattsPerMeterKelvin(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ThermalConductivity), quantity.As(ThermalConductivity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalInsulanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalInsulanceTestsBase.g.cs index 7861a39a38..9831d47070 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalInsulanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalInsulanceTestsBase.g.cs @@ -149,6 +149,20 @@ public void ThermalInsulance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity( Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ThermalInsulanceInfo_CreateWithCustomUnitInfos() + { + ThermalInsulanceUnit[] expectedUnits = [ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt]; + + ThermalInsulance.ThermalInsulanceInfo quantityInfo = ThermalInsulance.ThermalInsulanceInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ThermalInsulance", quantityInfo.Name); + Assert.Equal(ThermalInsulance.Zero, quantityInfo.Zero); + Assert.Equal(ThermalInsulance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void SquareMeterKelvinPerKilowattToThermalInsulanceUnits() { @@ -318,7 +332,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 m²K/kW", ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, 4.2)] [InlineData("en-US", "4.2 m²K/W", ThermalInsulanceUnit.SquareMeterKelvinPerWatt, 4.2)] [InlineData("en-US", "4.2 mm²K/W", ThermalInsulanceUnit.SquareMillimeterKelvinPerWatt, 4.2)] - public void Parse(string culture, string quantityString, ThermalInsulanceUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ThermalInsulanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ThermalInsulance.Parse(quantityString); @@ -334,7 +348,7 @@ public void Parse(string culture, string quantityString, ThermalInsulanceUnit ex [InlineData("en-US", "4.2 m²K/kW", ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, 4.2)] [InlineData("en-US", "4.2 m²K/W", ThermalInsulanceUnit.SquareMeterKelvinPerWatt, 4.2)] [InlineData("en-US", "4.2 mm²K/W", ThermalInsulanceUnit.SquareMillimeterKelvinPerWatt, 4.2)] - public void TryParse(string culture, string quantityString, ThermalInsulanceUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ThermalInsulanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ThermalInsulance.TryParse(quantityString, out ThermalInsulance parsed)); @@ -521,6 +535,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ThermalInsulance var quantity = ThermalInsulance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -544,38 +559,40 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ThermalInsulanceUni IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ThermalInsulance squaremeterkelvinperkilowatt = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1); - AssertEx.EqualTolerance(1, ThermalInsulance.FromHourSquareFeetDegreesFahrenheitPerBtu(squaremeterkelvinperkilowatt.HourSquareFeetDegreesFahrenheitPerBtu).SquareMeterKelvinsPerKilowatt, HourSquareFeetDegreesFahrenheitPerBtuTolerance); - AssertEx.EqualTolerance(1, ThermalInsulance.FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(squaremeterkelvinperkilowatt.SquareCentimeterHourDegreesCelsiusPerKilocalorie).SquareMeterKelvinsPerKilowatt, SquareCentimeterHourDegreesCelsiusPerKilocalorieTolerance); - AssertEx.EqualTolerance(1, ThermalInsulance.FromSquareCentimeterKelvinsPerWatt(squaremeterkelvinperkilowatt.SquareCentimeterKelvinsPerWatt).SquareMeterKelvinsPerKilowatt, SquareCentimeterKelvinsPerWattTolerance); - AssertEx.EqualTolerance(1, ThermalInsulance.FromSquareMeterDegreesCelsiusPerWatt(squaremeterkelvinperkilowatt.SquareMeterDegreesCelsiusPerWatt).SquareMeterKelvinsPerKilowatt, SquareMeterDegreesCelsiusPerWattTolerance); - AssertEx.EqualTolerance(1, ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(squaremeterkelvinperkilowatt.SquareMeterKelvinsPerKilowatt).SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - AssertEx.EqualTolerance(1, ThermalInsulance.FromSquareMeterKelvinsPerWatt(squaremeterkelvinperkilowatt.SquareMeterKelvinsPerWatt).SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerWattTolerance); - AssertEx.EqualTolerance(1, ThermalInsulance.FromSquareMillimeterKelvinsPerWatt(squaremeterkelvinperkilowatt.SquareMillimeterKelvinsPerWatt).SquareMeterKelvinsPerKilowatt, SquareMillimeterKelvinsPerWattTolerance); + ThermalInsulance squaremeterkelvinperkilowatt = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(3); + Assert.Equal(3, ThermalInsulance.FromHourSquareFeetDegreesFahrenheitPerBtu(squaremeterkelvinperkilowatt.HourSquareFeetDegreesFahrenheitPerBtu).SquareMeterKelvinsPerKilowatt); + Assert.Equal(3, ThermalInsulance.FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(squaremeterkelvinperkilowatt.SquareCentimeterHourDegreesCelsiusPerKilocalorie).SquareMeterKelvinsPerKilowatt); + Assert.Equal(3, ThermalInsulance.FromSquareCentimeterKelvinsPerWatt(squaremeterkelvinperkilowatt.SquareCentimeterKelvinsPerWatt).SquareMeterKelvinsPerKilowatt); + Assert.Equal(3, ThermalInsulance.FromSquareMeterDegreesCelsiusPerWatt(squaremeterkelvinperkilowatt.SquareMeterDegreesCelsiusPerWatt).SquareMeterKelvinsPerKilowatt); + Assert.Equal(3, ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(squaremeterkelvinperkilowatt.SquareMeterKelvinsPerKilowatt).SquareMeterKelvinsPerKilowatt); + Assert.Equal(3, ThermalInsulance.FromSquareMeterKelvinsPerWatt(squaremeterkelvinperkilowatt.SquareMeterKelvinsPerWatt).SquareMeterKelvinsPerKilowatt); + Assert.Equal(3, ThermalInsulance.FromSquareMillimeterKelvinsPerWatt(squaremeterkelvinperkilowatt.SquareMillimeterKelvinsPerWatt).SquareMeterKelvinsPerKilowatt); } [Fact] public void ArithmeticOperators() { ThermalInsulance v = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1); - AssertEx.EqualTolerance(-1, -v.SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - AssertEx.EqualTolerance(2, (ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(3)-v).SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - AssertEx.EqualTolerance(2, (v + v).SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - AssertEx.EqualTolerance(10, (v*10).SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - AssertEx.EqualTolerance(10, (10*v).SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - AssertEx.EqualTolerance(2, (ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(10)/5).SquareMeterKelvinsPerKilowatt, SquareMeterKelvinsPerKilowattTolerance); - AssertEx.EqualTolerance(2, ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(10)/ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(5), SquareMeterKelvinsPerKilowattTolerance); + Assert.Equal(-1, -v.SquareMeterKelvinsPerKilowatt); + Assert.Equal(2, (ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(3) - v).SquareMeterKelvinsPerKilowatt); + Assert.Equal(2, (v + v).SquareMeterKelvinsPerKilowatt); + Assert.Equal(10, (v * 10).SquareMeterKelvinsPerKilowatt); + Assert.Equal(10, (10 * v).SquareMeterKelvinsPerKilowatt); + Assert.Equal(2, (ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(10) / 5).SquareMeterKelvinsPerKilowatt); + Assert.Equal(2, ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(10) / ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(5)); } [Fact] @@ -621,8 +638,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, 1, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, true)] // Same value and unit. [InlineData(1, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, 2, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, false)] // Different value. - [InlineData(2, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, 1, ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, false)] // Different value and unit. - [InlineData(1, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, 1, ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ThermalInsulanceUnit unitA, double valueB, ThermalInsulanceUnit unitB, bool expectEqual) { var a = new ThermalInsulance(valueA, unitA); @@ -682,8 +697,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(firstValue); var otherQuantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(secondValue); ThermalInsulance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ThermalInsulance.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -702,7 +717,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -715,6 +730,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ThermalInsulance.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ThermalInsulance.Info.Units, ThermalInsulance.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ThermalInsulance.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -789,7 +816,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ThermalInsulance.FromSquareMeterKelvinsPerKilowatt(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ThermalInsulance), quantity.As(ThermalInsulance.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalResistanceTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalResistanceTestsBase.g.cs index ce5b48fa83..9defb397f3 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalResistanceTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/ThermalResistanceTestsBase.g.cs @@ -129,6 +129,20 @@ public void ThermalResistance_QuantityInfo_ReturnsQuantityInfoDescribingQuantity Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void ThermalResistanceInfo_CreateWithCustomUnitInfos() + { + ThermalResistanceUnit[] expectedUnits = [ThermalResistanceUnit.KelvinPerWatt]; + + ThermalResistance.ThermalResistanceInfo quantityInfo = ThermalResistance.ThermalResistanceInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("ThermalResistance", quantityInfo.Name); + Assert.Equal(ThermalResistance.Zero, quantityInfo.Zero); + Assert.Equal(ThermalResistance.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void KelvinPerWattToThermalResistanceUnits() { @@ -283,7 +297,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Theory] [InlineData("en-US", "4.2 °C/W", ThermalResistanceUnit.DegreeCelsiusPerWatt, 4.2)] [InlineData("en-US", "4.2 K/W", ThermalResistanceUnit.KelvinPerWatt, 4.2)] - public void Parse(string culture, string quantityString, ThermalResistanceUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, ThermalResistanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = ThermalResistance.Parse(quantityString); @@ -294,7 +308,7 @@ public void Parse(string culture, string quantityString, ThermalResistanceUnit e [Theory] [InlineData("en-US", "4.2 °C/W", ThermalResistanceUnit.DegreeCelsiusPerWatt, 4.2)] [InlineData("en-US", "4.2 K/W", ThermalResistanceUnit.KelvinPerWatt, 4.2)] - public void TryParse(string culture, string quantityString, ThermalResistanceUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, ThermalResistanceUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(ThermalResistance.TryParse(quantityString, out ThermalResistance parsed)); @@ -436,6 +450,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(ThermalResistanc var quantity = ThermalResistance.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -459,33 +474,35 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(ThermalResistanceUn IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - ThermalResistance kelvinperwatt = ThermalResistance.FromKelvinsPerWatt(1); - AssertEx.EqualTolerance(1, ThermalResistance.FromDegreesCelsiusPerWatt(kelvinperwatt.DegreesCelsiusPerWatt).KelvinsPerWatt, DegreesCelsiusPerWattTolerance); - AssertEx.EqualTolerance(1, ThermalResistance.FromKelvinsPerWatt(kelvinperwatt.KelvinsPerWatt).KelvinsPerWatt, KelvinsPerWattTolerance); + ThermalResistance kelvinperwatt = ThermalResistance.FromKelvinsPerWatt(3); + Assert.Equal(3, ThermalResistance.FromDegreesCelsiusPerWatt(kelvinperwatt.DegreesCelsiusPerWatt).KelvinsPerWatt); + Assert.Equal(3, ThermalResistance.FromKelvinsPerWatt(kelvinperwatt.KelvinsPerWatt).KelvinsPerWatt); } [Fact] public void ArithmeticOperators() { ThermalResistance v = ThermalResistance.FromKelvinsPerWatt(1); - AssertEx.EqualTolerance(-1, -v.KelvinsPerWatt, KelvinsPerWattTolerance); - AssertEx.EqualTolerance(2, (ThermalResistance.FromKelvinsPerWatt(3)-v).KelvinsPerWatt, KelvinsPerWattTolerance); - AssertEx.EqualTolerance(2, (v + v).KelvinsPerWatt, KelvinsPerWattTolerance); - AssertEx.EqualTolerance(10, (v*10).KelvinsPerWatt, KelvinsPerWattTolerance); - AssertEx.EqualTolerance(10, (10*v).KelvinsPerWatt, KelvinsPerWattTolerance); - AssertEx.EqualTolerance(2, (ThermalResistance.FromKelvinsPerWatt(10)/5).KelvinsPerWatt, KelvinsPerWattTolerance); - AssertEx.EqualTolerance(2, ThermalResistance.FromKelvinsPerWatt(10)/ThermalResistance.FromKelvinsPerWatt(5), KelvinsPerWattTolerance); + Assert.Equal(-1, -v.KelvinsPerWatt); + Assert.Equal(2, (ThermalResistance.FromKelvinsPerWatt(3) - v).KelvinsPerWatt); + Assert.Equal(2, (v + v).KelvinsPerWatt); + Assert.Equal(10, (v * 10).KelvinsPerWatt); + Assert.Equal(10, (10 * v).KelvinsPerWatt); + Assert.Equal(2, (ThermalResistance.FromKelvinsPerWatt(10) / 5).KelvinsPerWatt); + Assert.Equal(2, ThermalResistance.FromKelvinsPerWatt(10) / ThermalResistance.FromKelvinsPerWatt(5)); } [Fact] @@ -531,8 +548,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, ThermalResistanceUnit.KelvinPerWatt, 1, ThermalResistanceUnit.KelvinPerWatt, true)] // Same value and unit. [InlineData(1, ThermalResistanceUnit.KelvinPerWatt, 2, ThermalResistanceUnit.KelvinPerWatt, false)] // Different value. - [InlineData(2, ThermalResistanceUnit.KelvinPerWatt, 1, ThermalResistanceUnit.DegreeCelsiusPerWatt, false)] // Different value and unit. - [InlineData(1, ThermalResistanceUnit.KelvinPerWatt, 1, ThermalResistanceUnit.DegreeCelsiusPerWatt, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, ThermalResistanceUnit unitA, double valueB, ThermalResistanceUnit unitB, bool expectEqual) { var a = new ThermalResistance(valueA, unitA); @@ -592,8 +607,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = ThermalResistance.FromKelvinsPerWatt(firstValue); var otherQuantity = ThermalResistance.FromKelvinsPerWatt(secondValue); ThermalResistance maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, ThermalResistance.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -612,7 +627,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -625,6 +640,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(ThermalResistance.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(ThermalResistance.Info.Units, ThermalResistance.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, ThermalResistance.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -689,7 +716,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = ThermalResistance.FromKelvinsPerWatt(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(ThermalResistance), quantity.As(ThermalResistance.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs index 3439442851..8753bc6e45 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TorqueTestsBase.g.cs @@ -221,6 +221,20 @@ public void Torque_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void TorqueInfo_CreateWithCustomUnitInfos() + { + TorqueUnit[] expectedUnits = [TorqueUnit.NewtonMeter]; + + Torque.TorqueInfo quantityInfo = Torque.TorqueInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Torque", quantityInfo.Name); + Assert.Equal(Torque.Zero, quantityInfo.Zero); + Assert.Equal(Torque.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void NewtonMeterToTorqueUnits() { @@ -447,7 +461,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 кН·м", TorqueUnit.KilonewtonMeter, 4.2)] [InlineData("ru-RU", "4,2 МН·м", TorqueUnit.MeganewtonMeter, 4.2)] [InlineData("ru-RU", "4,2 Н·м", TorqueUnit.NewtonMeter, 4.2)] - public void Parse(string culture, string quantityString, TorqueUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, TorqueUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Torque.Parse(quantityString); @@ -484,7 +498,7 @@ public void Parse(string culture, string quantityString, TorqueUnit expectedUnit [InlineData("ru-RU", "4,2 кН·м", TorqueUnit.KilonewtonMeter, 4.2)] [InlineData("ru-RU", "4,2 МН·м", TorqueUnit.MeganewtonMeter, 4.2)] [InlineData("ru-RU", "4,2 Н·м", TorqueUnit.NewtonMeter, 4.2)] - public void TryParse(string culture, string quantityString, TorqueUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, TorqueUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Torque.TryParse(quantityString, out Torque parsed)); @@ -848,6 +862,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TorqueUnit unit) var quantity = Torque.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -871,56 +886,58 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(TorqueUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Torque newtonmeter = Torque.FromNewtonMeters(1); - AssertEx.EqualTolerance(1, Torque.FromGramForceCentimeters(newtonmeter.GramForceCentimeters).NewtonMeters, GramForceCentimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromGramForceMeters(newtonmeter.GramForceMeters).NewtonMeters, GramForceMetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromGramForceMillimeters(newtonmeter.GramForceMillimeters).NewtonMeters, GramForceMillimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromKilogramForceCentimeters(newtonmeter.KilogramForceCentimeters).NewtonMeters, KilogramForceCentimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromKilogramForceMeters(newtonmeter.KilogramForceMeters).NewtonMeters, KilogramForceMetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromKilogramForceMillimeters(newtonmeter.KilogramForceMillimeters).NewtonMeters, KilogramForceMillimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromKilonewtonCentimeters(newtonmeter.KilonewtonCentimeters).NewtonMeters, KilonewtonCentimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromKilonewtonMeters(newtonmeter.KilonewtonMeters).NewtonMeters, KilonewtonMetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromKilonewtonMillimeters(newtonmeter.KilonewtonMillimeters).NewtonMeters, KilonewtonMillimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromKilopoundForceFeet(newtonmeter.KilopoundForceFeet).NewtonMeters, KilopoundForceFeetTolerance); - AssertEx.EqualTolerance(1, Torque.FromKilopoundForceInches(newtonmeter.KilopoundForceInches).NewtonMeters, KilopoundForceInchesTolerance); - AssertEx.EqualTolerance(1, Torque.FromMeganewtonCentimeters(newtonmeter.MeganewtonCentimeters).NewtonMeters, MeganewtonCentimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromMeganewtonMeters(newtonmeter.MeganewtonMeters).NewtonMeters, MeganewtonMetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromMeganewtonMillimeters(newtonmeter.MeganewtonMillimeters).NewtonMeters, MeganewtonMillimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromMegapoundForceFeet(newtonmeter.MegapoundForceFeet).NewtonMeters, MegapoundForceFeetTolerance); - AssertEx.EqualTolerance(1, Torque.FromMegapoundForceInches(newtonmeter.MegapoundForceInches).NewtonMeters, MegapoundForceInchesTolerance); - AssertEx.EqualTolerance(1, Torque.FromNewtonCentimeters(newtonmeter.NewtonCentimeters).NewtonMeters, NewtonCentimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromNewtonMeters(newtonmeter.NewtonMeters).NewtonMeters, NewtonMetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromNewtonMillimeters(newtonmeter.NewtonMillimeters).NewtonMeters, NewtonMillimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromPoundalFeet(newtonmeter.PoundalFeet).NewtonMeters, PoundalFeetTolerance); - AssertEx.EqualTolerance(1, Torque.FromPoundForceFeet(newtonmeter.PoundForceFeet).NewtonMeters, PoundForceFeetTolerance); - AssertEx.EqualTolerance(1, Torque.FromPoundForceInches(newtonmeter.PoundForceInches).NewtonMeters, PoundForceInchesTolerance); - AssertEx.EqualTolerance(1, Torque.FromTonneForceCentimeters(newtonmeter.TonneForceCentimeters).NewtonMeters, TonneForceCentimetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromTonneForceMeters(newtonmeter.TonneForceMeters).NewtonMeters, TonneForceMetersTolerance); - AssertEx.EqualTolerance(1, Torque.FromTonneForceMillimeters(newtonmeter.TonneForceMillimeters).NewtonMeters, TonneForceMillimetersTolerance); + Torque newtonmeter = Torque.FromNewtonMeters(3); + Assert.Equal(3, Torque.FromGramForceCentimeters(newtonmeter.GramForceCentimeters).NewtonMeters); + Assert.Equal(3, Torque.FromGramForceMeters(newtonmeter.GramForceMeters).NewtonMeters); + Assert.Equal(3, Torque.FromGramForceMillimeters(newtonmeter.GramForceMillimeters).NewtonMeters); + Assert.Equal(3, Torque.FromKilogramForceCentimeters(newtonmeter.KilogramForceCentimeters).NewtonMeters); + Assert.Equal(3, Torque.FromKilogramForceMeters(newtonmeter.KilogramForceMeters).NewtonMeters); + Assert.Equal(3, Torque.FromKilogramForceMillimeters(newtonmeter.KilogramForceMillimeters).NewtonMeters); + Assert.Equal(3, Torque.FromKilonewtonCentimeters(newtonmeter.KilonewtonCentimeters).NewtonMeters); + Assert.Equal(3, Torque.FromKilonewtonMeters(newtonmeter.KilonewtonMeters).NewtonMeters); + Assert.Equal(3, Torque.FromKilonewtonMillimeters(newtonmeter.KilonewtonMillimeters).NewtonMeters); + Assert.Equal(3, Torque.FromKilopoundForceFeet(newtonmeter.KilopoundForceFeet).NewtonMeters); + Assert.Equal(3, Torque.FromKilopoundForceInches(newtonmeter.KilopoundForceInches).NewtonMeters); + Assert.Equal(3, Torque.FromMeganewtonCentimeters(newtonmeter.MeganewtonCentimeters).NewtonMeters); + Assert.Equal(3, Torque.FromMeganewtonMeters(newtonmeter.MeganewtonMeters).NewtonMeters); + Assert.Equal(3, Torque.FromMeganewtonMillimeters(newtonmeter.MeganewtonMillimeters).NewtonMeters); + Assert.Equal(3, Torque.FromMegapoundForceFeet(newtonmeter.MegapoundForceFeet).NewtonMeters); + Assert.Equal(3, Torque.FromMegapoundForceInches(newtonmeter.MegapoundForceInches).NewtonMeters); + Assert.Equal(3, Torque.FromNewtonCentimeters(newtonmeter.NewtonCentimeters).NewtonMeters); + Assert.Equal(3, Torque.FromNewtonMeters(newtonmeter.NewtonMeters).NewtonMeters); + Assert.Equal(3, Torque.FromNewtonMillimeters(newtonmeter.NewtonMillimeters).NewtonMeters); + Assert.Equal(3, Torque.FromPoundalFeet(newtonmeter.PoundalFeet).NewtonMeters); + Assert.Equal(3, Torque.FromPoundForceFeet(newtonmeter.PoundForceFeet).NewtonMeters); + Assert.Equal(3, Torque.FromPoundForceInches(newtonmeter.PoundForceInches).NewtonMeters); + Assert.Equal(3, Torque.FromTonneForceCentimeters(newtonmeter.TonneForceCentimeters).NewtonMeters); + Assert.Equal(3, Torque.FromTonneForceMeters(newtonmeter.TonneForceMeters).NewtonMeters); + Assert.Equal(3, Torque.FromTonneForceMillimeters(newtonmeter.TonneForceMillimeters).NewtonMeters); } [Fact] public void ArithmeticOperators() { Torque v = Torque.FromNewtonMeters(1); - AssertEx.EqualTolerance(-1, -v.NewtonMeters, NewtonMetersTolerance); - AssertEx.EqualTolerance(2, (Torque.FromNewtonMeters(3)-v).NewtonMeters, NewtonMetersTolerance); - AssertEx.EqualTolerance(2, (v + v).NewtonMeters, NewtonMetersTolerance); - AssertEx.EqualTolerance(10, (v*10).NewtonMeters, NewtonMetersTolerance); - AssertEx.EqualTolerance(10, (10*v).NewtonMeters, NewtonMetersTolerance); - AssertEx.EqualTolerance(2, (Torque.FromNewtonMeters(10)/5).NewtonMeters, NewtonMetersTolerance); - AssertEx.EqualTolerance(2, Torque.FromNewtonMeters(10)/Torque.FromNewtonMeters(5), NewtonMetersTolerance); + Assert.Equal(-1, -v.NewtonMeters); + Assert.Equal(2, (Torque.FromNewtonMeters(3) - v).NewtonMeters); + Assert.Equal(2, (v + v).NewtonMeters); + Assert.Equal(10, (v * 10).NewtonMeters); + Assert.Equal(10, (10 * v).NewtonMeters); + Assert.Equal(2, (Torque.FromNewtonMeters(10) / 5).NewtonMeters); + Assert.Equal(2, Torque.FromNewtonMeters(10) / Torque.FromNewtonMeters(5)); } [Fact] @@ -966,8 +983,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, TorqueUnit.NewtonMeter, 1, TorqueUnit.NewtonMeter, true)] // Same value and unit. [InlineData(1, TorqueUnit.NewtonMeter, 2, TorqueUnit.NewtonMeter, false)] // Different value. - [InlineData(2, TorqueUnit.NewtonMeter, 1, TorqueUnit.GramForceCentimeter, false)] // Different value and unit. - [InlineData(1, TorqueUnit.NewtonMeter, 1, TorqueUnit.GramForceCentimeter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, TorqueUnit unitA, double valueB, TorqueUnit unitB, bool expectEqual) { var a = new Torque(valueA, unitA); @@ -1027,8 +1042,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Torque.FromNewtonMeters(firstValue); var otherQuantity = Torque.FromNewtonMeters(secondValue); Torque maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Torque.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1047,7 +1062,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1060,6 +1075,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Torque.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Torque.Info.Units, Torque.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Torque.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -1170,7 +1197,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Torque.FromNewtonMeters(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Torque), quantity.As(Torque.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs index 4b2dff426d..d7ae25cbfd 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/TurbidityTestsBase.g.cs @@ -104,6 +104,20 @@ public void Turbidity_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void TurbidityInfo_CreateWithCustomUnitInfos() + { + TurbidityUnit[] expectedUnits = [TurbidityUnit.NTU]; + + Turbidity.TurbidityInfo quantityInfo = Turbidity.TurbidityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Turbidity", quantityInfo.Name); + Assert.Equal(Turbidity.Zero, quantityInfo.Zero); + Assert.Equal(Turbidity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void NTUToTurbidityUnits() { @@ -216,7 +230,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() [Theory] [InlineData("en-US", "4.2 NTU", TurbidityUnit.NTU, 4.2)] - public void Parse(string culture, string quantityString, TurbidityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, TurbidityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Turbidity.Parse(quantityString); @@ -226,7 +240,7 @@ public void Parse(string culture, string quantityString, TurbidityUnit expectedU [Theory] [InlineData("en-US", "4.2 NTU", TurbidityUnit.NTU, 4.2)] - public void TryParse(string culture, string quantityString, TurbidityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, TurbidityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Turbidity.TryParse(quantityString, out Turbidity parsed)); @@ -359,6 +373,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(TurbidityUnit un var quantity = Turbidity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -382,32 +397,34 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(TurbidityUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Turbidity ntu = Turbidity.FromNTU(1); - AssertEx.EqualTolerance(1, Turbidity.FromNTU(ntu.NTU).NTU, NTUTolerance); + Turbidity ntu = Turbidity.FromNTU(3); + Assert.Equal(3, Turbidity.FromNTU(ntu.NTU).NTU); } [Fact] public void ArithmeticOperators() { Turbidity v = Turbidity.FromNTU(1); - AssertEx.EqualTolerance(-1, -v.NTU, NTUTolerance); - AssertEx.EqualTolerance(2, (Turbidity.FromNTU(3)-v).NTU, NTUTolerance); - AssertEx.EqualTolerance(2, (v + v).NTU, NTUTolerance); - AssertEx.EqualTolerance(10, (v*10).NTU, NTUTolerance); - AssertEx.EqualTolerance(10, (10*v).NTU, NTUTolerance); - AssertEx.EqualTolerance(2, (Turbidity.FromNTU(10)/5).NTU, NTUTolerance); - AssertEx.EqualTolerance(2, Turbidity.FromNTU(10)/Turbidity.FromNTU(5), NTUTolerance); + Assert.Equal(-1, -v.NTU); + Assert.Equal(2, (Turbidity.FromNTU(3) - v).NTU); + Assert.Equal(2, (v + v).NTU); + Assert.Equal(10, (v * 10).NTU); + Assert.Equal(10, (10 * v).NTU); + Assert.Equal(2, (Turbidity.FromNTU(10) / 5).NTU); + Assert.Equal(2, Turbidity.FromNTU(10) / Turbidity.FromNTU(5)); } [Fact] @@ -453,7 +470,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, TurbidityUnit.NTU, 1, TurbidityUnit.NTU, true)] // Same value and unit. [InlineData(1, TurbidityUnit.NTU, 2, TurbidityUnit.NTU, false)] // Different value. - [InlineData(2, TurbidityUnit.NTU, 1, TurbidityUnit.NTU, false)] // Different value and unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, TurbidityUnit unitA, double valueB, TurbidityUnit unitB, bool expectEqual) { var a = new Turbidity(valueA, unitA); @@ -513,8 +529,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Turbidity.FromNTU(firstValue); var otherQuantity = Turbidity.FromNTU(secondValue); Turbidity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Turbidity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -533,7 +549,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -546,6 +562,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Turbidity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Turbidity.Info.Units, Turbidity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Turbidity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -608,7 +636,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Turbidity.FromNTU(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Turbidity), quantity.As(Turbidity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs index c828b4ca4e..c21a08c1cd 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VitaminATestsBase.g.cs @@ -104,6 +104,20 @@ public void VitaminA_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void VitaminAInfo_CreateWithCustomUnitInfos() + { + VitaminAUnit[] expectedUnits = [VitaminAUnit.InternationalUnit]; + + VitaminA.VitaminAInfo quantityInfo = VitaminA.VitaminAInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("VitaminA", quantityInfo.Name); + Assert.Equal(VitaminA.Zero, quantityInfo.Zero); + Assert.Equal(VitaminA.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void InternationalUnitToVitaminAUnits() { @@ -216,7 +230,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() [Theory] [InlineData("en-US", "4.2 IU", VitaminAUnit.InternationalUnit, 4.2)] - public void Parse(string culture, string quantityString, VitaminAUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, VitaminAUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = VitaminA.Parse(quantityString); @@ -226,7 +240,7 @@ public void Parse(string culture, string quantityString, VitaminAUnit expectedUn [Theory] [InlineData("en-US", "4.2 IU", VitaminAUnit.InternationalUnit, 4.2)] - public void TryParse(string culture, string quantityString, VitaminAUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, VitaminAUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(VitaminA.TryParse(quantityString, out VitaminA parsed)); @@ -359,6 +373,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VitaminAUnit uni var quantity = VitaminA.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -382,32 +397,34 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(VitaminAUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - VitaminA internationalunit = VitaminA.FromInternationalUnits(1); - AssertEx.EqualTolerance(1, VitaminA.FromInternationalUnits(internationalunit.InternationalUnits).InternationalUnits, InternationalUnitsTolerance); + VitaminA internationalunit = VitaminA.FromInternationalUnits(3); + Assert.Equal(3, VitaminA.FromInternationalUnits(internationalunit.InternationalUnits).InternationalUnits); } [Fact] public void ArithmeticOperators() { VitaminA v = VitaminA.FromInternationalUnits(1); - AssertEx.EqualTolerance(-1, -v.InternationalUnits, InternationalUnitsTolerance); - AssertEx.EqualTolerance(2, (VitaminA.FromInternationalUnits(3)-v).InternationalUnits, InternationalUnitsTolerance); - AssertEx.EqualTolerance(2, (v + v).InternationalUnits, InternationalUnitsTolerance); - AssertEx.EqualTolerance(10, (v*10).InternationalUnits, InternationalUnitsTolerance); - AssertEx.EqualTolerance(10, (10*v).InternationalUnits, InternationalUnitsTolerance); - AssertEx.EqualTolerance(2, (VitaminA.FromInternationalUnits(10)/5).InternationalUnits, InternationalUnitsTolerance); - AssertEx.EqualTolerance(2, VitaminA.FromInternationalUnits(10)/VitaminA.FromInternationalUnits(5), InternationalUnitsTolerance); + Assert.Equal(-1, -v.InternationalUnits); + Assert.Equal(2, (VitaminA.FromInternationalUnits(3) - v).InternationalUnits); + Assert.Equal(2, (v + v).InternationalUnits); + Assert.Equal(10, (v * 10).InternationalUnits); + Assert.Equal(10, (10 * v).InternationalUnits); + Assert.Equal(2, (VitaminA.FromInternationalUnits(10) / 5).InternationalUnits); + Assert.Equal(2, VitaminA.FromInternationalUnits(10) / VitaminA.FromInternationalUnits(5)); } [Fact] @@ -453,7 +470,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, VitaminAUnit.InternationalUnit, 1, VitaminAUnit.InternationalUnit, true)] // Same value and unit. [InlineData(1, VitaminAUnit.InternationalUnit, 2, VitaminAUnit.InternationalUnit, false)] // Different value. - [InlineData(2, VitaminAUnit.InternationalUnit, 1, VitaminAUnit.InternationalUnit, false)] // Different value and unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, VitaminAUnit unitA, double valueB, VitaminAUnit unitB, bool expectEqual) { var a = new VitaminA(valueA, unitA); @@ -513,8 +529,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = VitaminA.FromInternationalUnits(firstValue); var otherQuantity = VitaminA.FromInternationalUnits(secondValue); VitaminA maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, VitaminA.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -533,7 +549,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -546,6 +562,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(VitaminA.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(VitaminA.Info.Units, VitaminA.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, VitaminA.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -608,7 +636,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = VitaminA.FromInternationalUnits(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(VitaminA), quantity.As(VitaminA.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs index ed2149ad5a..e375191ac0 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeConcentrationTestsBase.g.cs @@ -180,6 +180,20 @@ public void VolumeConcentration_QuantityInfo_ReturnsQuantityInfoDescribingQuanti Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void VolumeConcentrationInfo_CreateWithCustomUnitInfos() + { + VolumeConcentrationUnit[] expectedUnits = [VolumeConcentrationUnit.DecimalFraction]; + + VolumeConcentration.VolumeConcentrationInfo quantityInfo = VolumeConcentration.VolumeConcentrationInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("VolumeConcentration", quantityInfo.Name); + Assert.Equal(VolumeConcentration.Zero, quantityInfo.Zero); + Assert.Equal(VolumeConcentration.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void DecimalFractionToVolumeConcentrationUnits() { @@ -350,7 +364,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentNullExceptionIfNull() [InlineData("en-US", "4.2 % (v/v)", VolumeConcentrationUnit.Percent, 4.2)] [InlineData("en-US", "4.2 pl/l", VolumeConcentrationUnit.PicoliterPerLiter, 4.2)] [InlineData("en-US", "4.2 pl/ml", VolumeConcentrationUnit.PicoliterPerMilliliter, 4.2)] - public void Parse(string culture, string quantityString, VolumeConcentrationUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, VolumeConcentrationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = VolumeConcentration.Parse(quantityString); @@ -380,7 +394,7 @@ public void Parse(string culture, string quantityString, VolumeConcentrationUnit [InlineData("en-US", "4.2 % (v/v)", VolumeConcentrationUnit.Percent, 4.2)] [InlineData("en-US", "4.2 pl/l", VolumeConcentrationUnit.PicoliterPerLiter, 4.2)] [InlineData("en-US", "4.2 pl/ml", VolumeConcentrationUnit.PicoliterPerMilliliter, 4.2)] - public void TryParse(string culture, string quantityString, VolumeConcentrationUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, VolumeConcentrationUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(VolumeConcentration.TryParse(quantityString, out VolumeConcentration parsed)); @@ -692,6 +706,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumeConcentrat var quantity = VolumeConcentration.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -715,51 +730,53 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(VolumeConcentration IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - VolumeConcentration decimalfraction = VolumeConcentration.FromDecimalFractions(1); - AssertEx.EqualTolerance(1, VolumeConcentration.FromCentilitersPerLiter(decimalfraction.CentilitersPerLiter).DecimalFractions, CentilitersPerLiterTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromCentilitersPerMilliliter(decimalfraction.CentilitersPerMilliliter).DecimalFractions, CentilitersPerMilliliterTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromDecilitersPerLiter(decimalfraction.DecilitersPerLiter).DecimalFractions, DecilitersPerLiterTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromDecilitersPerMilliliter(decimalfraction.DecilitersPerMilliliter).DecimalFractions, DecilitersPerMilliliterTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromDecimalFractions(decimalfraction.DecimalFractions).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromLitersPerLiter(decimalfraction.LitersPerLiter).DecimalFractions, LitersPerLiterTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromLitersPerMilliliter(decimalfraction.LitersPerMilliliter).DecimalFractions, LitersPerMilliliterTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromMicrolitersPerLiter(decimalfraction.MicrolitersPerLiter).DecimalFractions, MicrolitersPerLiterTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromMicrolitersPerMilliliter(decimalfraction.MicrolitersPerMilliliter).DecimalFractions, MicrolitersPerMilliliterTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromMillilitersPerLiter(decimalfraction.MillilitersPerLiter).DecimalFractions, MillilitersPerLiterTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromMillilitersPerMilliliter(decimalfraction.MillilitersPerMilliliter).DecimalFractions, MillilitersPerMilliliterTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromNanolitersPerLiter(decimalfraction.NanolitersPerLiter).DecimalFractions, NanolitersPerLiterTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromNanolitersPerMilliliter(decimalfraction.NanolitersPerMilliliter).DecimalFractions, NanolitersPerMilliliterTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromPartsPerBillion(decimalfraction.PartsPerBillion).DecimalFractions, PartsPerBillionTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromPartsPerMillion(decimalfraction.PartsPerMillion).DecimalFractions, PartsPerMillionTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromPartsPerThousand(decimalfraction.PartsPerThousand).DecimalFractions, PartsPerThousandTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromPartsPerTrillion(decimalfraction.PartsPerTrillion).DecimalFractions, PartsPerTrillionTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromPercent(decimalfraction.Percent).DecimalFractions, PercentTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromPicolitersPerLiter(decimalfraction.PicolitersPerLiter).DecimalFractions, PicolitersPerLiterTolerance); - AssertEx.EqualTolerance(1, VolumeConcentration.FromPicolitersPerMilliliter(decimalfraction.PicolitersPerMilliliter).DecimalFractions, PicolitersPerMilliliterTolerance); + VolumeConcentration decimalfraction = VolumeConcentration.FromDecimalFractions(3); + Assert.Equal(3, VolumeConcentration.FromCentilitersPerLiter(decimalfraction.CentilitersPerLiter).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromCentilitersPerMilliliter(decimalfraction.CentilitersPerMilliliter).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromDecilitersPerLiter(decimalfraction.DecilitersPerLiter).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromDecilitersPerMilliliter(decimalfraction.DecilitersPerMilliliter).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromDecimalFractions(decimalfraction.DecimalFractions).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromLitersPerLiter(decimalfraction.LitersPerLiter).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromLitersPerMilliliter(decimalfraction.LitersPerMilliliter).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromMicrolitersPerLiter(decimalfraction.MicrolitersPerLiter).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromMicrolitersPerMilliliter(decimalfraction.MicrolitersPerMilliliter).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromMillilitersPerLiter(decimalfraction.MillilitersPerLiter).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromMillilitersPerMilliliter(decimalfraction.MillilitersPerMilliliter).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromNanolitersPerLiter(decimalfraction.NanolitersPerLiter).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromNanolitersPerMilliliter(decimalfraction.NanolitersPerMilliliter).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromPartsPerBillion(decimalfraction.PartsPerBillion).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromPartsPerMillion(decimalfraction.PartsPerMillion).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromPartsPerThousand(decimalfraction.PartsPerThousand).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromPartsPerTrillion(decimalfraction.PartsPerTrillion).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromPercent(decimalfraction.Percent).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromPicolitersPerLiter(decimalfraction.PicolitersPerLiter).DecimalFractions); + Assert.Equal(3, VolumeConcentration.FromPicolitersPerMilliliter(decimalfraction.PicolitersPerMilliliter).DecimalFractions); } [Fact] public void ArithmeticOperators() { VolumeConcentration v = VolumeConcentration.FromDecimalFractions(1); - AssertEx.EqualTolerance(-1, -v.DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(2, (VolumeConcentration.FromDecimalFractions(3)-v).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(2, (v + v).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(10, (v*10).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(10, (10*v).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(2, (VolumeConcentration.FromDecimalFractions(10)/5).DecimalFractions, DecimalFractionsTolerance); - AssertEx.EqualTolerance(2, VolumeConcentration.FromDecimalFractions(10)/VolumeConcentration.FromDecimalFractions(5), DecimalFractionsTolerance); + Assert.Equal(-1, -v.DecimalFractions); + Assert.Equal(2, (VolumeConcentration.FromDecimalFractions(3) - v).DecimalFractions); + Assert.Equal(2, (v + v).DecimalFractions); + Assert.Equal(10, (v * 10).DecimalFractions); + Assert.Equal(10, (10 * v).DecimalFractions); + Assert.Equal(2, (VolumeConcentration.FromDecimalFractions(10) / 5).DecimalFractions); + Assert.Equal(2, VolumeConcentration.FromDecimalFractions(10) / VolumeConcentration.FromDecimalFractions(5)); } [Fact] @@ -805,8 +822,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, VolumeConcentrationUnit.DecimalFraction, 1, VolumeConcentrationUnit.DecimalFraction, true)] // Same value and unit. [InlineData(1, VolumeConcentrationUnit.DecimalFraction, 2, VolumeConcentrationUnit.DecimalFraction, false)] // Different value. - [InlineData(2, VolumeConcentrationUnit.DecimalFraction, 1, VolumeConcentrationUnit.CentiliterPerLiter, false)] // Different value and unit. - [InlineData(1, VolumeConcentrationUnit.DecimalFraction, 1, VolumeConcentrationUnit.CentiliterPerLiter, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, VolumeConcentrationUnit unitA, double valueB, VolumeConcentrationUnit unitB, bool expectEqual) { var a = new VolumeConcentration(valueA, unitA); @@ -866,8 +881,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = VolumeConcentration.FromDecimalFractions(firstValue); var otherQuantity = VolumeConcentration.FromDecimalFractions(secondValue); VolumeConcentration maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, VolumeConcentration.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -886,7 +901,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -899,6 +914,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(VolumeConcentration.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(VolumeConcentration.Info.Units, VolumeConcentration.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, VolumeConcentration.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -999,7 +1026,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = VolumeConcentration.FromDecimalFractions(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(VolumeConcentration), quantity.As(VolumeConcentration.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs index 3fb320fae5..68b8ee895f 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowPerAreaTestsBase.g.cs @@ -129,6 +129,20 @@ public void VolumeFlowPerArea_QuantityInfo_ReturnsQuantityInfoDescribingQuantity Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void VolumeFlowPerAreaInfo_CreateWithCustomUnitInfos() + { + VolumeFlowPerAreaUnit[] expectedUnits = [VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter]; + + VolumeFlowPerArea.VolumeFlowPerAreaInfo quantityInfo = VolumeFlowPerArea.VolumeFlowPerAreaInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("VolumeFlowPerArea", quantityInfo.Name); + Assert.Equal(VolumeFlowPerArea.Zero, quantityInfo.Zero); + Assert.Equal(VolumeFlowPerArea.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void CubicMeterPerSecondPerSquareMeterToVolumeFlowPerAreaUnits() { @@ -283,7 +297,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [Theory] [InlineData("en-US", "4.2 CFM/ft²", VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, 4.2)] [InlineData("en-US", "4.2 m³/(s·m²)", VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, 4.2)] - public void Parse(string culture, string quantityString, VolumeFlowPerAreaUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, VolumeFlowPerAreaUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = VolumeFlowPerArea.Parse(quantityString); @@ -294,7 +308,7 @@ public void Parse(string culture, string quantityString, VolumeFlowPerAreaUnit e [Theory] [InlineData("en-US", "4.2 CFM/ft²", VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, 4.2)] [InlineData("en-US", "4.2 m³/(s·m²)", VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, 4.2)] - public void TryParse(string culture, string quantityString, VolumeFlowPerAreaUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, VolumeFlowPerAreaUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(VolumeFlowPerArea.TryParse(quantityString, out VolumeFlowPerArea parsed)); @@ -436,6 +450,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumeFlowPerAre var quantity = VolumeFlowPerArea.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -459,33 +474,35 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(VolumeFlowPerAreaUn IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - VolumeFlowPerArea cubicmeterpersecondpersquaremeter = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1); - AssertEx.EqualTolerance(1, VolumeFlowPerArea.FromCubicFeetPerMinutePerSquareFoot(cubicmeterpersecondpersquaremeter.CubicFeetPerMinutePerSquareFoot).CubicMetersPerSecondPerSquareMeter, CubicFeetPerMinutePerSquareFootTolerance); - AssertEx.EqualTolerance(1, VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(cubicmeterpersecondpersquaremeter.CubicMetersPerSecondPerSquareMeter).CubicMetersPerSecondPerSquareMeter, CubicMetersPerSecondPerSquareMeterTolerance); + VolumeFlowPerArea cubicmeterpersecondpersquaremeter = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(3); + Assert.Equal(3, VolumeFlowPerArea.FromCubicFeetPerMinutePerSquareFoot(cubicmeterpersecondpersquaremeter.CubicFeetPerMinutePerSquareFoot).CubicMetersPerSecondPerSquareMeter); + Assert.Equal(3, VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(cubicmeterpersecondpersquaremeter.CubicMetersPerSecondPerSquareMeter).CubicMetersPerSecondPerSquareMeter); } [Fact] public void ArithmeticOperators() { VolumeFlowPerArea v = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1); - AssertEx.EqualTolerance(-1, -v.CubicMetersPerSecondPerSquareMeter, CubicMetersPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(3)-v).CubicMetersPerSecondPerSquareMeter, CubicMetersPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).CubicMetersPerSecondPerSquareMeter, CubicMetersPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).CubicMetersPerSecondPerSquareMeter, CubicMetersPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).CubicMetersPerSecondPerSquareMeter, CubicMetersPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, (VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(10)/5).CubicMetersPerSecondPerSquareMeter, CubicMetersPerSecondPerSquareMeterTolerance); - AssertEx.EqualTolerance(2, VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(10)/VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(5), CubicMetersPerSecondPerSquareMeterTolerance); + Assert.Equal(-1, -v.CubicMetersPerSecondPerSquareMeter); + Assert.Equal(2, (VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(3) - v).CubicMetersPerSecondPerSquareMeter); + Assert.Equal(2, (v + v).CubicMetersPerSecondPerSquareMeter); + Assert.Equal(10, (v * 10).CubicMetersPerSecondPerSquareMeter); + Assert.Equal(10, (10 * v).CubicMetersPerSecondPerSquareMeter); + Assert.Equal(2, (VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(10) / 5).CubicMetersPerSecondPerSquareMeter); + Assert.Equal(2, VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(10) / VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(5)); } [Fact] @@ -531,8 +548,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, 1, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, true)] // Same value and unit. [InlineData(1, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, 2, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, false)] // Different value. - [InlineData(2, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, 1, VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, false)] // Different value and unit. - [InlineData(1, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, 1, VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, VolumeFlowPerAreaUnit unitA, double valueB, VolumeFlowPerAreaUnit unitB, bool expectEqual) { var a = new VolumeFlowPerArea(valueA, unitA); @@ -592,8 +607,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(firstValue); var otherQuantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(secondValue); VolumeFlowPerArea maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, VolumeFlowPerArea.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -612,7 +627,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -625,6 +640,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(VolumeFlowPerArea.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(VolumeFlowPerArea.Info.Units, VolumeFlowPerArea.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, VolumeFlowPerArea.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -689,7 +716,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = VolumeFlowPerArea.FromCubicMetersPerSecondPerSquareMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(VolumeFlowPerArea), quantity.As(VolumeFlowPerArea.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs index e3817d335e..3917f6da2d 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeFlowTestsBase.g.cs @@ -421,6 +421,20 @@ public void VolumeFlow_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void VolumeFlowInfo_CreateWithCustomUnitInfos() + { + VolumeFlowUnit[] expectedUnits = [VolumeFlowUnit.CubicMeterPerSecond]; + + VolumeFlow.VolumeFlowInfo quantityInfo = VolumeFlow.VolumeFlowInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("VolumeFlow", quantityInfo.Name); + Assert.Equal(VolumeFlow.Zero, quantityInfo.Zero); + Assert.Equal(VolumeFlow.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void CubicMeterPerSecondToVolumeFlowUnits() { @@ -889,7 +903,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 нл/ч", VolumeFlowUnit.NanoliterPerHour, 4.2)] [InlineData("ru-RU", "4,2 нл/мин", VolumeFlowUnit.NanoliterPerMinute, 4.2)] [InlineData("ru-RU", "4,2 нл/c", VolumeFlowUnit.NanoliterPerSecond, 4.2)] - public void Parse(string culture, string quantityString, VolumeFlowUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, VolumeFlowUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = VolumeFlow.Parse(quantityString); @@ -1068,7 +1082,7 @@ public void Parse(string culture, string quantityString, VolumeFlowUnit expected [InlineData("ru-RU", "4,2 нл/ч", VolumeFlowUnit.NanoliterPerHour, 4.2)] [InlineData("ru-RU", "4,2 нл/мин", VolumeFlowUnit.NanoliterPerMinute, 4.2)] [InlineData("ru-RU", "4,2 нл/c", VolumeFlowUnit.NanoliterPerSecond, 4.2)] - public void TryParse(string culture, string quantityString, VolumeFlowUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, VolumeFlowUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(VolumeFlow.TryParse(quantityString, out VolumeFlow parsed)); @@ -2519,6 +2533,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumeFlowUnit u var quantity = VolumeFlow.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -2542,106 +2557,108 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(VolumeFlowUnit unit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - VolumeFlow cubicmeterpersecond = VolumeFlow.FromCubicMetersPerSecond(1); - AssertEx.EqualTolerance(1, VolumeFlow.FromAcreFeetPerDay(cubicmeterpersecond.AcreFeetPerDay).CubicMetersPerSecond, AcreFeetPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromAcreFeetPerHour(cubicmeterpersecond.AcreFeetPerHour).CubicMetersPerSecond, AcreFeetPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromAcreFeetPerMinute(cubicmeterpersecond.AcreFeetPerMinute).CubicMetersPerSecond, AcreFeetPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromAcreFeetPerSecond(cubicmeterpersecond.AcreFeetPerSecond).CubicMetersPerSecond, AcreFeetPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCentilitersPerDay(cubicmeterpersecond.CentilitersPerDay).CubicMetersPerSecond, CentilitersPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCentilitersPerHour(cubicmeterpersecond.CentilitersPerHour).CubicMetersPerSecond, CentilitersPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCentilitersPerMinute(cubicmeterpersecond.CentilitersPerMinute).CubicMetersPerSecond, CentilitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCentilitersPerSecond(cubicmeterpersecond.CentilitersPerSecond).CubicMetersPerSecond, CentilitersPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCubicCentimetersPerMinute(cubicmeterpersecond.CubicCentimetersPerMinute).CubicMetersPerSecond, CubicCentimetersPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCubicDecimetersPerMinute(cubicmeterpersecond.CubicDecimetersPerMinute).CubicMetersPerSecond, CubicDecimetersPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCubicFeetPerHour(cubicmeterpersecond.CubicFeetPerHour).CubicMetersPerSecond, CubicFeetPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCubicFeetPerMinute(cubicmeterpersecond.CubicFeetPerMinute).CubicMetersPerSecond, CubicFeetPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCubicFeetPerSecond(cubicmeterpersecond.CubicFeetPerSecond).CubicMetersPerSecond, CubicFeetPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCubicMetersPerDay(cubicmeterpersecond.CubicMetersPerDay).CubicMetersPerSecond, CubicMetersPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCubicMetersPerHour(cubicmeterpersecond.CubicMetersPerHour).CubicMetersPerSecond, CubicMetersPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCubicMetersPerMinute(cubicmeterpersecond.CubicMetersPerMinute).CubicMetersPerSecond, CubicMetersPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCubicMetersPerSecond(cubicmeterpersecond.CubicMetersPerSecond).CubicMetersPerSecond, CubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCubicMillimetersPerSecond(cubicmeterpersecond.CubicMillimetersPerSecond).CubicMetersPerSecond, CubicMillimetersPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCubicYardsPerDay(cubicmeterpersecond.CubicYardsPerDay).CubicMetersPerSecond, CubicYardsPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCubicYardsPerHour(cubicmeterpersecond.CubicYardsPerHour).CubicMetersPerSecond, CubicYardsPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCubicYardsPerMinute(cubicmeterpersecond.CubicYardsPerMinute).CubicMetersPerSecond, CubicYardsPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromCubicYardsPerSecond(cubicmeterpersecond.CubicYardsPerSecond).CubicMetersPerSecond, CubicYardsPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromDecalitersPerDay(cubicmeterpersecond.DecalitersPerDay).CubicMetersPerSecond, DecalitersPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromDecalitersPerHour(cubicmeterpersecond.DecalitersPerHour).CubicMetersPerSecond, DecalitersPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromDecalitersPerMinute(cubicmeterpersecond.DecalitersPerMinute).CubicMetersPerSecond, DecalitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromDecalitersPerSecond(cubicmeterpersecond.DecalitersPerSecond).CubicMetersPerSecond, DecalitersPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromDecilitersPerDay(cubicmeterpersecond.DecilitersPerDay).CubicMetersPerSecond, DecilitersPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromDecilitersPerHour(cubicmeterpersecond.DecilitersPerHour).CubicMetersPerSecond, DecilitersPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromDecilitersPerMinute(cubicmeterpersecond.DecilitersPerMinute).CubicMetersPerSecond, DecilitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromDecilitersPerSecond(cubicmeterpersecond.DecilitersPerSecond).CubicMetersPerSecond, DecilitersPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromHectolitersPerDay(cubicmeterpersecond.HectolitersPerDay).CubicMetersPerSecond, HectolitersPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromHectolitersPerHour(cubicmeterpersecond.HectolitersPerHour).CubicMetersPerSecond, HectolitersPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromHectolitersPerMinute(cubicmeterpersecond.HectolitersPerMinute).CubicMetersPerSecond, HectolitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromHectolitersPerSecond(cubicmeterpersecond.HectolitersPerSecond).CubicMetersPerSecond, HectolitersPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromKilolitersPerDay(cubicmeterpersecond.KilolitersPerDay).CubicMetersPerSecond, KilolitersPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromKilolitersPerHour(cubicmeterpersecond.KilolitersPerHour).CubicMetersPerSecond, KilolitersPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromKilolitersPerMinute(cubicmeterpersecond.KilolitersPerMinute).CubicMetersPerSecond, KilolitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromKilolitersPerSecond(cubicmeterpersecond.KilolitersPerSecond).CubicMetersPerSecond, KilolitersPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromKilousGallonsPerMinute(cubicmeterpersecond.KilousGallonsPerMinute).CubicMetersPerSecond, KilousGallonsPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromLitersPerDay(cubicmeterpersecond.LitersPerDay).CubicMetersPerSecond, LitersPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromLitersPerHour(cubicmeterpersecond.LitersPerHour).CubicMetersPerSecond, LitersPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromLitersPerMinute(cubicmeterpersecond.LitersPerMinute).CubicMetersPerSecond, LitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromLitersPerSecond(cubicmeterpersecond.LitersPerSecond).CubicMetersPerSecond, LitersPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromMegalitersPerDay(cubicmeterpersecond.MegalitersPerDay).CubicMetersPerSecond, MegalitersPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromMegalitersPerHour(cubicmeterpersecond.MegalitersPerHour).CubicMetersPerSecond, MegalitersPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromMegalitersPerMinute(cubicmeterpersecond.MegalitersPerMinute).CubicMetersPerSecond, MegalitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromMegalitersPerSecond(cubicmeterpersecond.MegalitersPerSecond).CubicMetersPerSecond, MegalitersPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromMegaukGallonsPerDay(cubicmeterpersecond.MegaukGallonsPerDay).CubicMetersPerSecond, MegaukGallonsPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromMegaukGallonsPerSecond(cubicmeterpersecond.MegaukGallonsPerSecond).CubicMetersPerSecond, MegaukGallonsPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromMegausGallonsPerDay(cubicmeterpersecond.MegausGallonsPerDay).CubicMetersPerSecond, MegausGallonsPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromMicrolitersPerDay(cubicmeterpersecond.MicrolitersPerDay).CubicMetersPerSecond, MicrolitersPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromMicrolitersPerHour(cubicmeterpersecond.MicrolitersPerHour).CubicMetersPerSecond, MicrolitersPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromMicrolitersPerMinute(cubicmeterpersecond.MicrolitersPerMinute).CubicMetersPerSecond, MicrolitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromMicrolitersPerSecond(cubicmeterpersecond.MicrolitersPerSecond).CubicMetersPerSecond, MicrolitersPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromMillilitersPerDay(cubicmeterpersecond.MillilitersPerDay).CubicMetersPerSecond, MillilitersPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromMillilitersPerHour(cubicmeterpersecond.MillilitersPerHour).CubicMetersPerSecond, MillilitersPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromMillilitersPerMinute(cubicmeterpersecond.MillilitersPerMinute).CubicMetersPerSecond, MillilitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromMillilitersPerSecond(cubicmeterpersecond.MillilitersPerSecond).CubicMetersPerSecond, MillilitersPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromMillionUsGallonsPerDay(cubicmeterpersecond.MillionUsGallonsPerDay).CubicMetersPerSecond, MillionUsGallonsPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromNanolitersPerDay(cubicmeterpersecond.NanolitersPerDay).CubicMetersPerSecond, NanolitersPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromNanolitersPerHour(cubicmeterpersecond.NanolitersPerHour).CubicMetersPerSecond, NanolitersPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromNanolitersPerMinute(cubicmeterpersecond.NanolitersPerMinute).CubicMetersPerSecond, NanolitersPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromNanolitersPerSecond(cubicmeterpersecond.NanolitersPerSecond).CubicMetersPerSecond, NanolitersPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromOilBarrelsPerDay(cubicmeterpersecond.OilBarrelsPerDay).CubicMetersPerSecond, OilBarrelsPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromOilBarrelsPerHour(cubicmeterpersecond.OilBarrelsPerHour).CubicMetersPerSecond, OilBarrelsPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromOilBarrelsPerMinute(cubicmeterpersecond.OilBarrelsPerMinute).CubicMetersPerSecond, OilBarrelsPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromOilBarrelsPerSecond(cubicmeterpersecond.OilBarrelsPerSecond).CubicMetersPerSecond, OilBarrelsPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromUkGallonsPerDay(cubicmeterpersecond.UkGallonsPerDay).CubicMetersPerSecond, UkGallonsPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromUkGallonsPerHour(cubicmeterpersecond.UkGallonsPerHour).CubicMetersPerSecond, UkGallonsPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromUkGallonsPerMinute(cubicmeterpersecond.UkGallonsPerMinute).CubicMetersPerSecond, UkGallonsPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromUkGallonsPerSecond(cubicmeterpersecond.UkGallonsPerSecond).CubicMetersPerSecond, UkGallonsPerSecondTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromUsGallonsPerDay(cubicmeterpersecond.UsGallonsPerDay).CubicMetersPerSecond, UsGallonsPerDayTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromUsGallonsPerHour(cubicmeterpersecond.UsGallonsPerHour).CubicMetersPerSecond, UsGallonsPerHourTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromUsGallonsPerMinute(cubicmeterpersecond.UsGallonsPerMinute).CubicMetersPerSecond, UsGallonsPerMinuteTolerance); - AssertEx.EqualTolerance(1, VolumeFlow.FromUsGallonsPerSecond(cubicmeterpersecond.UsGallonsPerSecond).CubicMetersPerSecond, UsGallonsPerSecondTolerance); + VolumeFlow cubicmeterpersecond = VolumeFlow.FromCubicMetersPerSecond(3); + Assert.Equal(3, VolumeFlow.FromAcreFeetPerDay(cubicmeterpersecond.AcreFeetPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromAcreFeetPerHour(cubicmeterpersecond.AcreFeetPerHour).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromAcreFeetPerMinute(cubicmeterpersecond.AcreFeetPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromAcreFeetPerSecond(cubicmeterpersecond.AcreFeetPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCentilitersPerDay(cubicmeterpersecond.CentilitersPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCentilitersPerHour(cubicmeterpersecond.CentilitersPerHour).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCentilitersPerMinute(cubicmeterpersecond.CentilitersPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCentilitersPerSecond(cubicmeterpersecond.CentilitersPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCubicCentimetersPerMinute(cubicmeterpersecond.CubicCentimetersPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCubicDecimetersPerMinute(cubicmeterpersecond.CubicDecimetersPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCubicFeetPerHour(cubicmeterpersecond.CubicFeetPerHour).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCubicFeetPerMinute(cubicmeterpersecond.CubicFeetPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCubicFeetPerSecond(cubicmeterpersecond.CubicFeetPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCubicMetersPerDay(cubicmeterpersecond.CubicMetersPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCubicMetersPerHour(cubicmeterpersecond.CubicMetersPerHour).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCubicMetersPerMinute(cubicmeterpersecond.CubicMetersPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCubicMetersPerSecond(cubicmeterpersecond.CubicMetersPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCubicMillimetersPerSecond(cubicmeterpersecond.CubicMillimetersPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCubicYardsPerDay(cubicmeterpersecond.CubicYardsPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCubicYardsPerHour(cubicmeterpersecond.CubicYardsPerHour).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCubicYardsPerMinute(cubicmeterpersecond.CubicYardsPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromCubicYardsPerSecond(cubicmeterpersecond.CubicYardsPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromDecalitersPerDay(cubicmeterpersecond.DecalitersPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromDecalitersPerHour(cubicmeterpersecond.DecalitersPerHour).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromDecalitersPerMinute(cubicmeterpersecond.DecalitersPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromDecalitersPerSecond(cubicmeterpersecond.DecalitersPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromDecilitersPerDay(cubicmeterpersecond.DecilitersPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromDecilitersPerHour(cubicmeterpersecond.DecilitersPerHour).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromDecilitersPerMinute(cubicmeterpersecond.DecilitersPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromDecilitersPerSecond(cubicmeterpersecond.DecilitersPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromHectolitersPerDay(cubicmeterpersecond.HectolitersPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromHectolitersPerHour(cubicmeterpersecond.HectolitersPerHour).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromHectolitersPerMinute(cubicmeterpersecond.HectolitersPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromHectolitersPerSecond(cubicmeterpersecond.HectolitersPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromKilolitersPerDay(cubicmeterpersecond.KilolitersPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromKilolitersPerHour(cubicmeterpersecond.KilolitersPerHour).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromKilolitersPerMinute(cubicmeterpersecond.KilolitersPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromKilolitersPerSecond(cubicmeterpersecond.KilolitersPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromKilousGallonsPerMinute(cubicmeterpersecond.KilousGallonsPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromLitersPerDay(cubicmeterpersecond.LitersPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromLitersPerHour(cubicmeterpersecond.LitersPerHour).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromLitersPerMinute(cubicmeterpersecond.LitersPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromLitersPerSecond(cubicmeterpersecond.LitersPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromMegalitersPerDay(cubicmeterpersecond.MegalitersPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromMegalitersPerHour(cubicmeterpersecond.MegalitersPerHour).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromMegalitersPerMinute(cubicmeterpersecond.MegalitersPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromMegalitersPerSecond(cubicmeterpersecond.MegalitersPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromMegaukGallonsPerDay(cubicmeterpersecond.MegaukGallonsPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromMegaukGallonsPerSecond(cubicmeterpersecond.MegaukGallonsPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromMegausGallonsPerDay(cubicmeterpersecond.MegausGallonsPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromMicrolitersPerDay(cubicmeterpersecond.MicrolitersPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromMicrolitersPerHour(cubicmeterpersecond.MicrolitersPerHour).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromMicrolitersPerMinute(cubicmeterpersecond.MicrolitersPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromMicrolitersPerSecond(cubicmeterpersecond.MicrolitersPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromMillilitersPerDay(cubicmeterpersecond.MillilitersPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromMillilitersPerHour(cubicmeterpersecond.MillilitersPerHour).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromMillilitersPerMinute(cubicmeterpersecond.MillilitersPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromMillilitersPerSecond(cubicmeterpersecond.MillilitersPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromMillionUsGallonsPerDay(cubicmeterpersecond.MillionUsGallonsPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromNanolitersPerDay(cubicmeterpersecond.NanolitersPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromNanolitersPerHour(cubicmeterpersecond.NanolitersPerHour).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromNanolitersPerMinute(cubicmeterpersecond.NanolitersPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromNanolitersPerSecond(cubicmeterpersecond.NanolitersPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromOilBarrelsPerDay(cubicmeterpersecond.OilBarrelsPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromOilBarrelsPerHour(cubicmeterpersecond.OilBarrelsPerHour).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromOilBarrelsPerMinute(cubicmeterpersecond.OilBarrelsPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromOilBarrelsPerSecond(cubicmeterpersecond.OilBarrelsPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromUkGallonsPerDay(cubicmeterpersecond.UkGallonsPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromUkGallonsPerHour(cubicmeterpersecond.UkGallonsPerHour).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromUkGallonsPerMinute(cubicmeterpersecond.UkGallonsPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromUkGallonsPerSecond(cubicmeterpersecond.UkGallonsPerSecond).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromUsGallonsPerDay(cubicmeterpersecond.UsGallonsPerDay).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromUsGallonsPerHour(cubicmeterpersecond.UsGallonsPerHour).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromUsGallonsPerMinute(cubicmeterpersecond.UsGallonsPerMinute).CubicMetersPerSecond); + Assert.Equal(3, VolumeFlow.FromUsGallonsPerSecond(cubicmeterpersecond.UsGallonsPerSecond).CubicMetersPerSecond); } [Fact] public void ArithmeticOperators() { VolumeFlow v = VolumeFlow.FromCubicMetersPerSecond(1); - AssertEx.EqualTolerance(-1, -v.CubicMetersPerSecond, CubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (VolumeFlow.FromCubicMetersPerSecond(3)-v).CubicMetersPerSecond, CubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (v + v).CubicMetersPerSecond, CubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(10, (v*10).CubicMetersPerSecond, CubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(10, (10*v).CubicMetersPerSecond, CubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, (VolumeFlow.FromCubicMetersPerSecond(10)/5).CubicMetersPerSecond, CubicMetersPerSecondTolerance); - AssertEx.EqualTolerance(2, VolumeFlow.FromCubicMetersPerSecond(10)/VolumeFlow.FromCubicMetersPerSecond(5), CubicMetersPerSecondTolerance); + Assert.Equal(-1, -v.CubicMetersPerSecond); + Assert.Equal(2, (VolumeFlow.FromCubicMetersPerSecond(3) - v).CubicMetersPerSecond); + Assert.Equal(2, (v + v).CubicMetersPerSecond); + Assert.Equal(10, (v * 10).CubicMetersPerSecond); + Assert.Equal(10, (10 * v).CubicMetersPerSecond); + Assert.Equal(2, (VolumeFlow.FromCubicMetersPerSecond(10) / 5).CubicMetersPerSecond); + Assert.Equal(2, VolumeFlow.FromCubicMetersPerSecond(10) / VolumeFlow.FromCubicMetersPerSecond(5)); } [Fact] @@ -2687,8 +2704,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, VolumeFlowUnit.CubicMeterPerSecond, 1, VolumeFlowUnit.CubicMeterPerSecond, true)] // Same value and unit. [InlineData(1, VolumeFlowUnit.CubicMeterPerSecond, 2, VolumeFlowUnit.CubicMeterPerSecond, false)] // Different value. - [InlineData(2, VolumeFlowUnit.CubicMeterPerSecond, 1, VolumeFlowUnit.AcreFootPerDay, false)] // Different value and unit. - [InlineData(1, VolumeFlowUnit.CubicMeterPerSecond, 1, VolumeFlowUnit.AcreFootPerDay, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, VolumeFlowUnit unitA, double valueB, VolumeFlowUnit unitB, bool expectEqual) { var a = new VolumeFlow(valueA, unitA); @@ -2748,8 +2763,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = VolumeFlow.FromCubicMetersPerSecond(firstValue); var otherQuantity = VolumeFlow.FromCubicMetersPerSecond(secondValue); VolumeFlow maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, VolumeFlow.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -2768,7 +2783,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -2781,6 +2796,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(VolumeFlow.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(VolumeFlow.Info.Units, VolumeFlow.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, VolumeFlow.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -2991,7 +3018,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = VolumeFlow.FromCubicMetersPerSecond(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(VolumeFlow), quantity.As(VolumeFlow.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs index 45261aeb84..2d803c40f3 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumePerLengthTestsBase.g.cs @@ -157,6 +157,20 @@ public void VolumePerLength_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void VolumePerLengthInfo_CreateWithCustomUnitInfos() + { + VolumePerLengthUnit[] expectedUnits = [VolumePerLengthUnit.CubicMeterPerMeter]; + + VolumePerLength.VolumePerLengthInfo quantityInfo = VolumePerLength.VolumePerLengthInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("VolumePerLength", quantityInfo.Name); + Assert.Equal(VolumePerLength.Zero, quantityInfo.Zero); + Assert.Equal(VolumePerLength.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void CubicMeterPerMeterToVolumePerLengthUnits() { @@ -332,7 +346,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 l/mm", VolumePerLengthUnit.LiterPerMillimeter, 4.2)] [InlineData("en-US", "4.2 bbl/ft", VolumePerLengthUnit.OilBarrelPerFoot, 4.2)] [InlineData("en-US", "4.2 gal (U.S.)/mi", VolumePerLengthUnit.UsGallonPerMile, 4.2)] - public void Parse(string culture, string quantityString, VolumePerLengthUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, VolumePerLengthUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = VolumePerLength.Parse(quantityString); @@ -350,7 +364,7 @@ public void Parse(string culture, string quantityString, VolumePerLengthUnit exp [InlineData("en-US", "4.2 l/mm", VolumePerLengthUnit.LiterPerMillimeter, 4.2)] [InlineData("en-US", "4.2 bbl/ft", VolumePerLengthUnit.OilBarrelPerFoot, 4.2)] [InlineData("en-US", "4.2 gal (U.S.)/mi", VolumePerLengthUnit.UsGallonPerMile, 4.2)] - public void TryParse(string culture, string quantityString, VolumePerLengthUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, VolumePerLengthUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(VolumePerLength.TryParse(quantityString, out VolumePerLength parsed)); @@ -555,6 +569,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumePerLengthU var quantity = VolumePerLength.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -578,40 +593,42 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(VolumePerLengthUnit IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - VolumePerLength cubicmeterpermeter = VolumePerLength.FromCubicMetersPerMeter(1); - AssertEx.EqualTolerance(1, VolumePerLength.FromCubicMetersPerMeter(cubicmeterpermeter.CubicMetersPerMeter).CubicMetersPerMeter, CubicMetersPerMeterTolerance); - AssertEx.EqualTolerance(1, VolumePerLength.FromCubicYardsPerFoot(cubicmeterpermeter.CubicYardsPerFoot).CubicMetersPerMeter, CubicYardsPerFootTolerance); - AssertEx.EqualTolerance(1, VolumePerLength.FromCubicYardsPerUsSurveyFoot(cubicmeterpermeter.CubicYardsPerUsSurveyFoot).CubicMetersPerMeter, CubicYardsPerUsSurveyFootTolerance); - AssertEx.EqualTolerance(1, VolumePerLength.FromImperialGallonsPerMile(cubicmeterpermeter.ImperialGallonsPerMile).CubicMetersPerMeter, ImperialGallonsPerMileTolerance); - AssertEx.EqualTolerance(1, VolumePerLength.FromLitersPerKilometer(cubicmeterpermeter.LitersPerKilometer).CubicMetersPerMeter, LitersPerKilometerTolerance); - AssertEx.EqualTolerance(1, VolumePerLength.FromLitersPerMeter(cubicmeterpermeter.LitersPerMeter).CubicMetersPerMeter, LitersPerMeterTolerance); - AssertEx.EqualTolerance(1, VolumePerLength.FromLitersPerMillimeter(cubicmeterpermeter.LitersPerMillimeter).CubicMetersPerMeter, LitersPerMillimeterTolerance); - AssertEx.EqualTolerance(1, VolumePerLength.FromOilBarrelsPerFoot(cubicmeterpermeter.OilBarrelsPerFoot).CubicMetersPerMeter, OilBarrelsPerFootTolerance); - AssertEx.EqualTolerance(1, VolumePerLength.FromUsGallonsPerMile(cubicmeterpermeter.UsGallonsPerMile).CubicMetersPerMeter, UsGallonsPerMileTolerance); + VolumePerLength cubicmeterpermeter = VolumePerLength.FromCubicMetersPerMeter(3); + Assert.Equal(3, VolumePerLength.FromCubicMetersPerMeter(cubicmeterpermeter.CubicMetersPerMeter).CubicMetersPerMeter); + Assert.Equal(3, VolumePerLength.FromCubicYardsPerFoot(cubicmeterpermeter.CubicYardsPerFoot).CubicMetersPerMeter); + Assert.Equal(3, VolumePerLength.FromCubicYardsPerUsSurveyFoot(cubicmeterpermeter.CubicYardsPerUsSurveyFoot).CubicMetersPerMeter); + Assert.Equal(3, VolumePerLength.FromImperialGallonsPerMile(cubicmeterpermeter.ImperialGallonsPerMile).CubicMetersPerMeter); + Assert.Equal(3, VolumePerLength.FromLitersPerKilometer(cubicmeterpermeter.LitersPerKilometer).CubicMetersPerMeter); + Assert.Equal(3, VolumePerLength.FromLitersPerMeter(cubicmeterpermeter.LitersPerMeter).CubicMetersPerMeter); + Assert.Equal(3, VolumePerLength.FromLitersPerMillimeter(cubicmeterpermeter.LitersPerMillimeter).CubicMetersPerMeter); + Assert.Equal(3, VolumePerLength.FromOilBarrelsPerFoot(cubicmeterpermeter.OilBarrelsPerFoot).CubicMetersPerMeter); + Assert.Equal(3, VolumePerLength.FromUsGallonsPerMile(cubicmeterpermeter.UsGallonsPerMile).CubicMetersPerMeter); } [Fact] public void ArithmeticOperators() { VolumePerLength v = VolumePerLength.FromCubicMetersPerMeter(1); - AssertEx.EqualTolerance(-1, -v.CubicMetersPerMeter, CubicMetersPerMeterTolerance); - AssertEx.EqualTolerance(2, (VolumePerLength.FromCubicMetersPerMeter(3)-v).CubicMetersPerMeter, CubicMetersPerMeterTolerance); - AssertEx.EqualTolerance(2, (v + v).CubicMetersPerMeter, CubicMetersPerMeterTolerance); - AssertEx.EqualTolerance(10, (v*10).CubicMetersPerMeter, CubicMetersPerMeterTolerance); - AssertEx.EqualTolerance(10, (10*v).CubicMetersPerMeter, CubicMetersPerMeterTolerance); - AssertEx.EqualTolerance(2, (VolumePerLength.FromCubicMetersPerMeter(10)/5).CubicMetersPerMeter, CubicMetersPerMeterTolerance); - AssertEx.EqualTolerance(2, VolumePerLength.FromCubicMetersPerMeter(10)/VolumePerLength.FromCubicMetersPerMeter(5), CubicMetersPerMeterTolerance); + Assert.Equal(-1, -v.CubicMetersPerMeter); + Assert.Equal(2, (VolumePerLength.FromCubicMetersPerMeter(3) - v).CubicMetersPerMeter); + Assert.Equal(2, (v + v).CubicMetersPerMeter); + Assert.Equal(10, (v * 10).CubicMetersPerMeter); + Assert.Equal(10, (10 * v).CubicMetersPerMeter); + Assert.Equal(2, (VolumePerLength.FromCubicMetersPerMeter(10) / 5).CubicMetersPerMeter); + Assert.Equal(2, VolumePerLength.FromCubicMetersPerMeter(10) / VolumePerLength.FromCubicMetersPerMeter(5)); } [Fact] @@ -657,8 +674,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, VolumePerLengthUnit.CubicMeterPerMeter, 1, VolumePerLengthUnit.CubicMeterPerMeter, true)] // Same value and unit. [InlineData(1, VolumePerLengthUnit.CubicMeterPerMeter, 2, VolumePerLengthUnit.CubicMeterPerMeter, false)] // Different value. - [InlineData(2, VolumePerLengthUnit.CubicMeterPerMeter, 1, VolumePerLengthUnit.CubicYardPerFoot, false)] // Different value and unit. - [InlineData(1, VolumePerLengthUnit.CubicMeterPerMeter, 1, VolumePerLengthUnit.CubicYardPerFoot, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, VolumePerLengthUnit unitA, double valueB, VolumePerLengthUnit unitB, bool expectEqual) { var a = new VolumePerLength(valueA, unitA); @@ -718,8 +733,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = VolumePerLength.FromCubicMetersPerMeter(firstValue); var otherQuantity = VolumePerLength.FromCubicMetersPerMeter(secondValue); VolumePerLength maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, VolumePerLength.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -738,7 +753,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -751,6 +766,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(VolumePerLength.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(VolumePerLength.Info.Units, VolumePerLength.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, VolumePerLength.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -829,7 +856,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = VolumePerLength.FromCubicMetersPerMeter(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(VolumePerLength), quantity.As(VolumePerLength.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs index 4058db5b30..91feb6c70a 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumeTestsBase.g.cs @@ -337,6 +337,20 @@ public void Volume_QuantityInfo_ReturnsQuantityInfoDescribingQuantity() Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void VolumeInfo_CreateWithCustomUnitInfos() + { + VolumeUnit[] expectedUnits = [VolumeUnit.CubicMeter]; + + Volume.VolumeInfo quantityInfo = Volume.VolumeInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("Volume", quantityInfo.Name); + Assert.Equal(Volume.Zero, quantityInfo.Zero); + Assert.Equal(Volume.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void CubicMeterToVolumeUnits() { @@ -694,7 +708,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("ru-RU", "4,2 нл", VolumeUnit.Nanoliter, 4.2)] [InlineData("ru-RU", "4,2 Американский галлон", VolumeUnit.UsGallon, 4.2)] [InlineData("ru-RU", "4,2 Американская унция", VolumeUnit.UsOunce, 4.2)] - public void Parse(string culture, string quantityString, VolumeUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, VolumeUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = Volume.Parse(quantityString); @@ -814,7 +828,7 @@ public void ParseWithAmbiguousAbbreviation(string culture, string quantityString [InlineData("ru-RU", "4,2 нл", VolumeUnit.Nanoliter, 4.2)] [InlineData("ru-RU", "4,2 Американский галлон", VolumeUnit.UsGallon, 4.2)] [InlineData("ru-RU", "4,2 Американская унция", VolumeUnit.UsOunce, 4.2)] - public void TryParse(string culture, string quantityString, VolumeUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, VolumeUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(Volume.TryParse(quantityString, out Volume parsed)); @@ -1724,6 +1738,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumeUnit unit) var quantity = Volume.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -1747,85 +1762,87 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(VolumeUnit unit) IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - Volume cubicmeter = Volume.FromCubicMeters(1); - AssertEx.EqualTolerance(1, Volume.FromAcreFeet(cubicmeter.AcreFeet).CubicMeters, AcreFeetTolerance); - AssertEx.EqualTolerance(1, Volume.FromAuTablespoons(cubicmeter.AuTablespoons).CubicMeters, AuTablespoonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromBoardFeet(cubicmeter.BoardFeet).CubicMeters, BoardFeetTolerance); - AssertEx.EqualTolerance(1, Volume.FromCentiliters(cubicmeter.Centiliters).CubicMeters, CentilitersTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicCentimeters(cubicmeter.CubicCentimeters).CubicMeters, CubicCentimetersTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicDecimeters(cubicmeter.CubicDecimeters).CubicMeters, CubicDecimetersTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicFeet(cubicmeter.CubicFeet).CubicMeters, CubicFeetTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicHectometers(cubicmeter.CubicHectometers).CubicMeters, CubicHectometersTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicInches(cubicmeter.CubicInches).CubicMeters, CubicInchesTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicKilometers(cubicmeter.CubicKilometers).CubicMeters, CubicKilometersTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicMeters(cubicmeter.CubicMeters).CubicMeters, CubicMetersTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicMicrometers(cubicmeter.CubicMicrometers).CubicMeters, CubicMicrometersTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicMiles(cubicmeter.CubicMiles).CubicMeters, CubicMilesTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicMillimeters(cubicmeter.CubicMillimeters).CubicMeters, CubicMillimetersTolerance); - AssertEx.EqualTolerance(1, Volume.FromCubicYards(cubicmeter.CubicYards).CubicMeters, CubicYardsTolerance); - AssertEx.EqualTolerance(1, Volume.FromDecaliters(cubicmeter.Decaliters).CubicMeters, DecalitersTolerance); - AssertEx.EqualTolerance(1, Volume.FromDecausGallons(cubicmeter.DecausGallons).CubicMeters, DecausGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromDeciliters(cubicmeter.Deciliters).CubicMeters, DecilitersTolerance); - AssertEx.EqualTolerance(1, Volume.FromDeciusGallons(cubicmeter.DeciusGallons).CubicMeters, DeciusGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromHectocubicFeet(cubicmeter.HectocubicFeet).CubicMeters, HectocubicFeetTolerance); - AssertEx.EqualTolerance(1, Volume.FromHectocubicMeters(cubicmeter.HectocubicMeters).CubicMeters, HectocubicMetersTolerance); - AssertEx.EqualTolerance(1, Volume.FromHectoliters(cubicmeter.Hectoliters).CubicMeters, HectolitersTolerance); - AssertEx.EqualTolerance(1, Volume.FromHectousGallons(cubicmeter.HectousGallons).CubicMeters, HectousGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromImperialBeerBarrels(cubicmeter.ImperialBeerBarrels).CubicMeters, ImperialBeerBarrelsTolerance); - AssertEx.EqualTolerance(1, Volume.FromImperialGallons(cubicmeter.ImperialGallons).CubicMeters, ImperialGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromImperialOunces(cubicmeter.ImperialOunces).CubicMeters, ImperialOuncesTolerance); - AssertEx.EqualTolerance(1, Volume.FromImperialPints(cubicmeter.ImperialPints).CubicMeters, ImperialPintsTolerance); - AssertEx.EqualTolerance(1, Volume.FromImperialQuarts(cubicmeter.ImperialQuarts).CubicMeters, ImperialQuartsTolerance); - AssertEx.EqualTolerance(1, Volume.FromKilocubicFeet(cubicmeter.KilocubicFeet).CubicMeters, KilocubicFeetTolerance); - AssertEx.EqualTolerance(1, Volume.FromKilocubicMeters(cubicmeter.KilocubicMeters).CubicMeters, KilocubicMetersTolerance); - AssertEx.EqualTolerance(1, Volume.FromKiloimperialGallons(cubicmeter.KiloimperialGallons).CubicMeters, KiloimperialGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromKiloliters(cubicmeter.Kiloliters).CubicMeters, KilolitersTolerance); - AssertEx.EqualTolerance(1, Volume.FromKilousGallons(cubicmeter.KilousGallons).CubicMeters, KilousGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromLiters(cubicmeter.Liters).CubicMeters, LitersTolerance); - AssertEx.EqualTolerance(1, Volume.FromMegacubicFeet(cubicmeter.MegacubicFeet).CubicMeters, MegacubicFeetTolerance); - AssertEx.EqualTolerance(1, Volume.FromMegaimperialGallons(cubicmeter.MegaimperialGallons).CubicMeters, MegaimperialGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromMegaliters(cubicmeter.Megaliters).CubicMeters, MegalitersTolerance); - AssertEx.EqualTolerance(1, Volume.FromMegausGallons(cubicmeter.MegausGallons).CubicMeters, MegausGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromMetricCups(cubicmeter.MetricCups).CubicMeters, MetricCupsTolerance); - AssertEx.EqualTolerance(1, Volume.FromMetricTeaspoons(cubicmeter.MetricTeaspoons).CubicMeters, MetricTeaspoonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromMicroliters(cubicmeter.Microliters).CubicMeters, MicrolitersTolerance); - AssertEx.EqualTolerance(1, Volume.FromMilliliters(cubicmeter.Milliliters).CubicMeters, MillilitersTolerance); - AssertEx.EqualTolerance(1, Volume.FromNanoliters(cubicmeter.Nanoliters).CubicMeters, NanolitersTolerance); - AssertEx.EqualTolerance(1, Volume.FromOilBarrels(cubicmeter.OilBarrels).CubicMeters, OilBarrelsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUkTablespoons(cubicmeter.UkTablespoons).CubicMeters, UkTablespoonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsBeerBarrels(cubicmeter.UsBeerBarrels).CubicMeters, UsBeerBarrelsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsCustomaryCups(cubicmeter.UsCustomaryCups).CubicMeters, UsCustomaryCupsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsGallons(cubicmeter.UsGallons).CubicMeters, UsGallonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsLegalCups(cubicmeter.UsLegalCups).CubicMeters, UsLegalCupsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsOunces(cubicmeter.UsOunces).CubicMeters, UsOuncesTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsPints(cubicmeter.UsPints).CubicMeters, UsPintsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsQuarts(cubicmeter.UsQuarts).CubicMeters, UsQuartsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsTablespoons(cubicmeter.UsTablespoons).CubicMeters, UsTablespoonsTolerance); - AssertEx.EqualTolerance(1, Volume.FromUsTeaspoons(cubicmeter.UsTeaspoons).CubicMeters, UsTeaspoonsTolerance); + Volume cubicmeter = Volume.FromCubicMeters(3); + Assert.Equal(3, Volume.FromAcreFeet(cubicmeter.AcreFeet).CubicMeters); + Assert.Equal(3, Volume.FromAuTablespoons(cubicmeter.AuTablespoons).CubicMeters); + Assert.Equal(3, Volume.FromBoardFeet(cubicmeter.BoardFeet).CubicMeters); + Assert.Equal(3, Volume.FromCentiliters(cubicmeter.Centiliters).CubicMeters); + Assert.Equal(3, Volume.FromCubicCentimeters(cubicmeter.CubicCentimeters).CubicMeters); + Assert.Equal(3, Volume.FromCubicDecimeters(cubicmeter.CubicDecimeters).CubicMeters); + Assert.Equal(3, Volume.FromCubicFeet(cubicmeter.CubicFeet).CubicMeters); + Assert.Equal(3, Volume.FromCubicHectometers(cubicmeter.CubicHectometers).CubicMeters); + Assert.Equal(3, Volume.FromCubicInches(cubicmeter.CubicInches).CubicMeters); + Assert.Equal(3, Volume.FromCubicKilometers(cubicmeter.CubicKilometers).CubicMeters); + Assert.Equal(3, Volume.FromCubicMeters(cubicmeter.CubicMeters).CubicMeters); + Assert.Equal(3, Volume.FromCubicMicrometers(cubicmeter.CubicMicrometers).CubicMeters); + Assert.Equal(3, Volume.FromCubicMiles(cubicmeter.CubicMiles).CubicMeters); + Assert.Equal(3, Volume.FromCubicMillimeters(cubicmeter.CubicMillimeters).CubicMeters); + Assert.Equal(3, Volume.FromCubicYards(cubicmeter.CubicYards).CubicMeters); + Assert.Equal(3, Volume.FromDecaliters(cubicmeter.Decaliters).CubicMeters); + Assert.Equal(3, Volume.FromDecausGallons(cubicmeter.DecausGallons).CubicMeters); + Assert.Equal(3, Volume.FromDeciliters(cubicmeter.Deciliters).CubicMeters); + Assert.Equal(3, Volume.FromDeciusGallons(cubicmeter.DeciusGallons).CubicMeters); + Assert.Equal(3, Volume.FromHectocubicFeet(cubicmeter.HectocubicFeet).CubicMeters); + Assert.Equal(3, Volume.FromHectocubicMeters(cubicmeter.HectocubicMeters).CubicMeters); + Assert.Equal(3, Volume.FromHectoliters(cubicmeter.Hectoliters).CubicMeters); + Assert.Equal(3, Volume.FromHectousGallons(cubicmeter.HectousGallons).CubicMeters); + Assert.Equal(3, Volume.FromImperialBeerBarrels(cubicmeter.ImperialBeerBarrels).CubicMeters); + Assert.Equal(3, Volume.FromImperialGallons(cubicmeter.ImperialGallons).CubicMeters); + Assert.Equal(3, Volume.FromImperialOunces(cubicmeter.ImperialOunces).CubicMeters); + Assert.Equal(3, Volume.FromImperialPints(cubicmeter.ImperialPints).CubicMeters); + Assert.Equal(3, Volume.FromImperialQuarts(cubicmeter.ImperialQuarts).CubicMeters); + Assert.Equal(3, Volume.FromKilocubicFeet(cubicmeter.KilocubicFeet).CubicMeters); + Assert.Equal(3, Volume.FromKilocubicMeters(cubicmeter.KilocubicMeters).CubicMeters); + Assert.Equal(3, Volume.FromKiloimperialGallons(cubicmeter.KiloimperialGallons).CubicMeters); + Assert.Equal(3, Volume.FromKiloliters(cubicmeter.Kiloliters).CubicMeters); + Assert.Equal(3, Volume.FromKilousGallons(cubicmeter.KilousGallons).CubicMeters); + Assert.Equal(3, Volume.FromLiters(cubicmeter.Liters).CubicMeters); + Assert.Equal(3, Volume.FromMegacubicFeet(cubicmeter.MegacubicFeet).CubicMeters); + Assert.Equal(3, Volume.FromMegaimperialGallons(cubicmeter.MegaimperialGallons).CubicMeters); + Assert.Equal(3, Volume.FromMegaliters(cubicmeter.Megaliters).CubicMeters); + Assert.Equal(3, Volume.FromMegausGallons(cubicmeter.MegausGallons).CubicMeters); + Assert.Equal(3, Volume.FromMetricCups(cubicmeter.MetricCups).CubicMeters); + Assert.Equal(3, Volume.FromMetricTeaspoons(cubicmeter.MetricTeaspoons).CubicMeters); + Assert.Equal(3, Volume.FromMicroliters(cubicmeter.Microliters).CubicMeters); + Assert.Equal(3, Volume.FromMilliliters(cubicmeter.Milliliters).CubicMeters); + Assert.Equal(3, Volume.FromNanoliters(cubicmeter.Nanoliters).CubicMeters); + Assert.Equal(3, Volume.FromOilBarrels(cubicmeter.OilBarrels).CubicMeters); + Assert.Equal(3, Volume.FromUkTablespoons(cubicmeter.UkTablespoons).CubicMeters); + Assert.Equal(3, Volume.FromUsBeerBarrels(cubicmeter.UsBeerBarrels).CubicMeters); + Assert.Equal(3, Volume.FromUsCustomaryCups(cubicmeter.UsCustomaryCups).CubicMeters); + Assert.Equal(3, Volume.FromUsGallons(cubicmeter.UsGallons).CubicMeters); + Assert.Equal(3, Volume.FromUsLegalCups(cubicmeter.UsLegalCups).CubicMeters); + Assert.Equal(3, Volume.FromUsOunces(cubicmeter.UsOunces).CubicMeters); + Assert.Equal(3, Volume.FromUsPints(cubicmeter.UsPints).CubicMeters); + Assert.Equal(3, Volume.FromUsQuarts(cubicmeter.UsQuarts).CubicMeters); + Assert.Equal(3, Volume.FromUsTablespoons(cubicmeter.UsTablespoons).CubicMeters); + Assert.Equal(3, Volume.FromUsTeaspoons(cubicmeter.UsTeaspoons).CubicMeters); } [Fact] public void ArithmeticOperators() { Volume v = Volume.FromCubicMeters(1); - AssertEx.EqualTolerance(-1, -v.CubicMeters, CubicMetersTolerance); - AssertEx.EqualTolerance(2, (Volume.FromCubicMeters(3)-v).CubicMeters, CubicMetersTolerance); - AssertEx.EqualTolerance(2, (v + v).CubicMeters, CubicMetersTolerance); - AssertEx.EqualTolerance(10, (v*10).CubicMeters, CubicMetersTolerance); - AssertEx.EqualTolerance(10, (10*v).CubicMeters, CubicMetersTolerance); - AssertEx.EqualTolerance(2, (Volume.FromCubicMeters(10)/5).CubicMeters, CubicMetersTolerance); - AssertEx.EqualTolerance(2, Volume.FromCubicMeters(10)/Volume.FromCubicMeters(5), CubicMetersTolerance); + Assert.Equal(-1, -v.CubicMeters); + Assert.Equal(2, (Volume.FromCubicMeters(3) - v).CubicMeters); + Assert.Equal(2, (v + v).CubicMeters); + Assert.Equal(10, (v * 10).CubicMeters); + Assert.Equal(10, (10 * v).CubicMeters); + Assert.Equal(2, (Volume.FromCubicMeters(10) / 5).CubicMeters); + Assert.Equal(2, Volume.FromCubicMeters(10) / Volume.FromCubicMeters(5)); } [Fact] @@ -1871,8 +1888,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, VolumeUnit.CubicMeter, 1, VolumeUnit.CubicMeter, true)] // Same value and unit. [InlineData(1, VolumeUnit.CubicMeter, 2, VolumeUnit.CubicMeter, false)] // Different value. - [InlineData(2, VolumeUnit.CubicMeter, 1, VolumeUnit.AcreFoot, false)] // Different value and unit. - [InlineData(1, VolumeUnit.CubicMeter, 1, VolumeUnit.AcreFoot, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, VolumeUnit unitA, double valueB, VolumeUnit unitB, bool expectEqual) { var a = new Volume(valueA, unitA); @@ -1932,8 +1947,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = Volume.FromCubicMeters(firstValue); var otherQuantity = Volume.FromCubicMeters(secondValue); Volume maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, Volume.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -1952,7 +1967,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -1965,6 +1980,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(Volume.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(Volume.Info.Units, Volume.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, Volume.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -2133,7 +2160,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = Volume.FromCubicMeters(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(Volume), quantity.As(Volume.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs index 90506fe37b..27866ed430 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/VolumetricHeatCapacityTestsBase.g.cs @@ -157,6 +157,20 @@ public void VolumetricHeatCapacity_QuantityInfo_ReturnsQuantityInfoDescribingQua Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void VolumetricHeatCapacityInfo_CreateWithCustomUnitInfos() + { + VolumetricHeatCapacityUnit[] expectedUnits = [VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin]; + + VolumetricHeatCapacity.VolumetricHeatCapacityInfo quantityInfo = VolumetricHeatCapacity.VolumetricHeatCapacityInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("VolumetricHeatCapacity", quantityInfo.Name); + Assert.Equal(VolumetricHeatCapacity.Zero, quantityInfo.Zero); + Assert.Equal(VolumetricHeatCapacity.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void JoulePerCubicMeterKelvinToVolumetricHeatCapacityUnits() { @@ -332,7 +346,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 kJ/(m³·K)", VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, 4.2)] [InlineData("en-US", "4.2 MJ/(m³·°C)", VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, 4.2)] [InlineData("en-US", "4.2 MJ/(m³·K)", VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, 4.2)] - public void Parse(string culture, string quantityString, VolumetricHeatCapacityUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, VolumetricHeatCapacityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = VolumetricHeatCapacity.Parse(quantityString); @@ -350,7 +364,7 @@ public void Parse(string culture, string quantityString, VolumetricHeatCapacityU [InlineData("en-US", "4.2 kJ/(m³·K)", VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, 4.2)] [InlineData("en-US", "4.2 MJ/(m³·°C)", VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, 4.2)] [InlineData("en-US", "4.2 MJ/(m³·K)", VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, 4.2)] - public void TryParse(string culture, string quantityString, VolumetricHeatCapacityUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, VolumetricHeatCapacityUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(VolumetricHeatCapacity.TryParse(quantityString, out VolumetricHeatCapacity parsed)); @@ -555,6 +569,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(VolumetricHeatCa var quantity = VolumetricHeatCapacity.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -578,40 +593,42 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(VolumetricHeatCapac IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - VolumetricHeatCapacity joulepercubicmeterkelvin = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1); - AssertEx.EqualTolerance(1, VolumetricHeatCapacity.FromBtusPerCubicFootDegreeFahrenheit(joulepercubicmeterkelvin.BtusPerCubicFootDegreeFahrenheit).JoulesPerCubicMeterKelvin, BtusPerCubicFootDegreeFahrenheitTolerance); - AssertEx.EqualTolerance(1, VolumetricHeatCapacity.FromCaloriesPerCubicCentimeterDegreeCelsius(joulepercubicmeterkelvin.CaloriesPerCubicCentimeterDegreeCelsius).JoulesPerCubicMeterKelvin, CaloriesPerCubicCentimeterDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, VolumetricHeatCapacity.FromJoulesPerCubicMeterDegreeCelsius(joulepercubicmeterkelvin.JoulesPerCubicMeterDegreeCelsius).JoulesPerCubicMeterKelvin, JoulesPerCubicMeterDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(joulepercubicmeterkelvin.JoulesPerCubicMeterKelvin).JoulesPerCubicMeterKelvin, JoulesPerCubicMeterKelvinTolerance); - AssertEx.EqualTolerance(1, VolumetricHeatCapacity.FromKilocaloriesPerCubicCentimeterDegreeCelsius(joulepercubicmeterkelvin.KilocaloriesPerCubicCentimeterDegreeCelsius).JoulesPerCubicMeterKelvin, KilocaloriesPerCubicCentimeterDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, VolumetricHeatCapacity.FromKilojoulesPerCubicMeterDegreeCelsius(joulepercubicmeterkelvin.KilojoulesPerCubicMeterDegreeCelsius).JoulesPerCubicMeterKelvin, KilojoulesPerCubicMeterDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, VolumetricHeatCapacity.FromKilojoulesPerCubicMeterKelvin(joulepercubicmeterkelvin.KilojoulesPerCubicMeterKelvin).JoulesPerCubicMeterKelvin, KilojoulesPerCubicMeterKelvinTolerance); - AssertEx.EqualTolerance(1, VolumetricHeatCapacity.FromMegajoulesPerCubicMeterDegreeCelsius(joulepercubicmeterkelvin.MegajoulesPerCubicMeterDegreeCelsius).JoulesPerCubicMeterKelvin, MegajoulesPerCubicMeterDegreeCelsiusTolerance); - AssertEx.EqualTolerance(1, VolumetricHeatCapacity.FromMegajoulesPerCubicMeterKelvin(joulepercubicmeterkelvin.MegajoulesPerCubicMeterKelvin).JoulesPerCubicMeterKelvin, MegajoulesPerCubicMeterKelvinTolerance); + VolumetricHeatCapacity joulepercubicmeterkelvin = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(3); + Assert.Equal(3, VolumetricHeatCapacity.FromBtusPerCubicFootDegreeFahrenheit(joulepercubicmeterkelvin.BtusPerCubicFootDegreeFahrenheit).JoulesPerCubicMeterKelvin); + Assert.Equal(3, VolumetricHeatCapacity.FromCaloriesPerCubicCentimeterDegreeCelsius(joulepercubicmeterkelvin.CaloriesPerCubicCentimeterDegreeCelsius).JoulesPerCubicMeterKelvin); + Assert.Equal(3, VolumetricHeatCapacity.FromJoulesPerCubicMeterDegreeCelsius(joulepercubicmeterkelvin.JoulesPerCubicMeterDegreeCelsius).JoulesPerCubicMeterKelvin); + Assert.Equal(3, VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(joulepercubicmeterkelvin.JoulesPerCubicMeterKelvin).JoulesPerCubicMeterKelvin); + Assert.Equal(3, VolumetricHeatCapacity.FromKilocaloriesPerCubicCentimeterDegreeCelsius(joulepercubicmeterkelvin.KilocaloriesPerCubicCentimeterDegreeCelsius).JoulesPerCubicMeterKelvin); + Assert.Equal(3, VolumetricHeatCapacity.FromKilojoulesPerCubicMeterDegreeCelsius(joulepercubicmeterkelvin.KilojoulesPerCubicMeterDegreeCelsius).JoulesPerCubicMeterKelvin); + Assert.Equal(3, VolumetricHeatCapacity.FromKilojoulesPerCubicMeterKelvin(joulepercubicmeterkelvin.KilojoulesPerCubicMeterKelvin).JoulesPerCubicMeterKelvin); + Assert.Equal(3, VolumetricHeatCapacity.FromMegajoulesPerCubicMeterDegreeCelsius(joulepercubicmeterkelvin.MegajoulesPerCubicMeterDegreeCelsius).JoulesPerCubicMeterKelvin); + Assert.Equal(3, VolumetricHeatCapacity.FromMegajoulesPerCubicMeterKelvin(joulepercubicmeterkelvin.MegajoulesPerCubicMeterKelvin).JoulesPerCubicMeterKelvin); } [Fact] public void ArithmeticOperators() { VolumetricHeatCapacity v = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1); - AssertEx.EqualTolerance(-1, -v.JoulesPerCubicMeterKelvin, JoulesPerCubicMeterKelvinTolerance); - AssertEx.EqualTolerance(2, (VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(3)-v).JoulesPerCubicMeterKelvin, JoulesPerCubicMeterKelvinTolerance); - AssertEx.EqualTolerance(2, (v + v).JoulesPerCubicMeterKelvin, JoulesPerCubicMeterKelvinTolerance); - AssertEx.EqualTolerance(10, (v*10).JoulesPerCubicMeterKelvin, JoulesPerCubicMeterKelvinTolerance); - AssertEx.EqualTolerance(10, (10*v).JoulesPerCubicMeterKelvin, JoulesPerCubicMeterKelvinTolerance); - AssertEx.EqualTolerance(2, (VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(10)/5).JoulesPerCubicMeterKelvin, JoulesPerCubicMeterKelvinTolerance); - AssertEx.EqualTolerance(2, VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(10)/VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(5), JoulesPerCubicMeterKelvinTolerance); + Assert.Equal(-1, -v.JoulesPerCubicMeterKelvin); + Assert.Equal(2, (VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(3) - v).JoulesPerCubicMeterKelvin); + Assert.Equal(2, (v + v).JoulesPerCubicMeterKelvin); + Assert.Equal(10, (v * 10).JoulesPerCubicMeterKelvin); + Assert.Equal(10, (10 * v).JoulesPerCubicMeterKelvin); + Assert.Equal(2, (VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(10) / 5).JoulesPerCubicMeterKelvin); + Assert.Equal(2, VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(10) / VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(5)); } [Fact] @@ -657,8 +674,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, 1, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, true)] // Same value and unit. [InlineData(1, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, 2, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, false)] // Different value. - [InlineData(2, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, 1, VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, false)] // Different value and unit. - [InlineData(1, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, 1, VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, VolumetricHeatCapacityUnit unitA, double valueB, VolumetricHeatCapacityUnit unitB, bool expectEqual) { var a = new VolumetricHeatCapacity(valueA, unitA); @@ -718,8 +733,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(firstValue); var otherQuantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(secondValue); VolumetricHeatCapacity maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, VolumetricHeatCapacity.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -738,7 +753,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -751,6 +766,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(VolumetricHeatCapacity.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(VolumetricHeatCapacity.Info.Units, VolumetricHeatCapacity.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, VolumetricHeatCapacity.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -829,7 +856,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = VolumetricHeatCapacity.FromJoulesPerCubicMeterKelvin(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(VolumetricHeatCapacity), quantity.As(VolumetricHeatCapacity.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs b/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs index caf640fa9a..9b5076c769 100644 --- a/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs +++ b/UnitsNet.Tests/GeneratedCode/TestsBase/WarpingMomentOfInertiaTestsBase.g.cs @@ -145,6 +145,20 @@ public void WarpingMomentOfInertia_QuantityInfo_ReturnsQuantityInfoDescribingQua Assert.Equal(quantityInfo, ((IQuantity)quantity).QuantityInfo); } + [Fact] + public void WarpingMomentOfInertiaInfo_CreateWithCustomUnitInfos() + { + WarpingMomentOfInertiaUnit[] expectedUnits = [WarpingMomentOfInertiaUnit.MeterToTheSixth]; + + WarpingMomentOfInertia.WarpingMomentOfInertiaInfo quantityInfo = WarpingMomentOfInertia.WarpingMomentOfInertiaInfo.CreateDefault(mappings => mappings.SelectUnits(expectedUnits)); + + Assert.Equal("WarpingMomentOfInertia", quantityInfo.Name); + Assert.Equal(WarpingMomentOfInertia.Zero, quantityInfo.Zero); + Assert.Equal(WarpingMomentOfInertia.BaseUnit, quantityInfo.BaseUnitInfo.Value); + Assert.Equal(expectedUnits, quantityInfo.Units); + Assert.Equal(expectedUnits, quantityInfo.UnitInfos.Select(x => x.Value)); + } + [Fact] public void MeterToTheSixthToWarpingMomentOfInertiaUnits() { @@ -311,7 +325,7 @@ public void ToUnit_UnitSystem_ThrowsArgumentExceptionIfNotSupported() [InlineData("en-US", "4.2 in⁶", WarpingMomentOfInertiaUnit.InchToTheSixth, 4.2)] [InlineData("en-US", "4.2 m⁶", WarpingMomentOfInertiaUnit.MeterToTheSixth, 4.2)] [InlineData("en-US", "4.2 mm⁶", WarpingMomentOfInertiaUnit.MillimeterToTheSixth, 4.2)] - public void Parse(string culture, string quantityString, WarpingMomentOfInertiaUnit expectedUnit, double expectedValue) + public void Parse(string culture, string quantityString, WarpingMomentOfInertiaUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); var parsed = WarpingMomentOfInertia.Parse(quantityString); @@ -326,7 +340,7 @@ public void Parse(string culture, string quantityString, WarpingMomentOfInertiaU [InlineData("en-US", "4.2 in⁶", WarpingMomentOfInertiaUnit.InchToTheSixth, 4.2)] [InlineData("en-US", "4.2 m⁶", WarpingMomentOfInertiaUnit.MeterToTheSixth, 4.2)] [InlineData("en-US", "4.2 mm⁶", WarpingMomentOfInertiaUnit.MillimeterToTheSixth, 4.2)] - public void TryParse(string culture, string quantityString, WarpingMomentOfInertiaUnit expectedUnit, double expectedValue) + public void TryParse(string culture, string quantityString, WarpingMomentOfInertiaUnit expectedUnit, decimal expectedValue) { using var _ = new CultureScope(culture); Assert.True(WarpingMomentOfInertia.TryParse(quantityString, out WarpingMomentOfInertia parsed)); @@ -504,6 +518,7 @@ public void ToUnit_FromNonBaseUnit_ReturnsQuantityWithGivenUnit(WarpingMomentOfI var quantity = WarpingMomentOfInertia.From(3.0, fromUnit); var converted = quantity.ToUnit(unit); Assert.Equal(converted.Unit, unit); + Assert.Equal(quantity, converted); }); } @@ -527,37 +542,39 @@ public void ToUnit_FromIQuantity_ReturnsTheExpectedIQuantity(WarpingMomentOfIner IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }, () => { IQuantity quantityToConvert = quantity; IQuantity convertedQuantity = quantityToConvert.ToUnit(unit); Assert.Equal(unit, convertedQuantity.Unit); + Assert.Equal(expectedQuantity, convertedQuantity); }); } [Fact] public void ConversionRoundTrip() { - WarpingMomentOfInertia metertothesixth = WarpingMomentOfInertia.FromMetersToTheSixth(1); - AssertEx.EqualTolerance(1, WarpingMomentOfInertia.FromCentimetersToTheSixth(metertothesixth.CentimetersToTheSixth).MetersToTheSixth, CentimetersToTheSixthTolerance); - AssertEx.EqualTolerance(1, WarpingMomentOfInertia.FromDecimetersToTheSixth(metertothesixth.DecimetersToTheSixth).MetersToTheSixth, DecimetersToTheSixthTolerance); - AssertEx.EqualTolerance(1, WarpingMomentOfInertia.FromFeetToTheSixth(metertothesixth.FeetToTheSixth).MetersToTheSixth, FeetToTheSixthTolerance); - AssertEx.EqualTolerance(1, WarpingMomentOfInertia.FromInchesToTheSixth(metertothesixth.InchesToTheSixth).MetersToTheSixth, InchesToTheSixthTolerance); - AssertEx.EqualTolerance(1, WarpingMomentOfInertia.FromMetersToTheSixth(metertothesixth.MetersToTheSixth).MetersToTheSixth, MetersToTheSixthTolerance); - AssertEx.EqualTolerance(1, WarpingMomentOfInertia.FromMillimetersToTheSixth(metertothesixth.MillimetersToTheSixth).MetersToTheSixth, MillimetersToTheSixthTolerance); + WarpingMomentOfInertia metertothesixth = WarpingMomentOfInertia.FromMetersToTheSixth(3); + Assert.Equal(3, WarpingMomentOfInertia.FromCentimetersToTheSixth(metertothesixth.CentimetersToTheSixth).MetersToTheSixth); + Assert.Equal(3, WarpingMomentOfInertia.FromDecimetersToTheSixth(metertothesixth.DecimetersToTheSixth).MetersToTheSixth); + Assert.Equal(3, WarpingMomentOfInertia.FromFeetToTheSixth(metertothesixth.FeetToTheSixth).MetersToTheSixth); + Assert.Equal(3, WarpingMomentOfInertia.FromInchesToTheSixth(metertothesixth.InchesToTheSixth).MetersToTheSixth); + Assert.Equal(3, WarpingMomentOfInertia.FromMetersToTheSixth(metertothesixth.MetersToTheSixth).MetersToTheSixth); + Assert.Equal(3, WarpingMomentOfInertia.FromMillimetersToTheSixth(metertothesixth.MillimetersToTheSixth).MetersToTheSixth); } [Fact] public void ArithmeticOperators() { WarpingMomentOfInertia v = WarpingMomentOfInertia.FromMetersToTheSixth(1); - AssertEx.EqualTolerance(-1, -v.MetersToTheSixth, MetersToTheSixthTolerance); - AssertEx.EqualTolerance(2, (WarpingMomentOfInertia.FromMetersToTheSixth(3)-v).MetersToTheSixth, MetersToTheSixthTolerance); - AssertEx.EqualTolerance(2, (v + v).MetersToTheSixth, MetersToTheSixthTolerance); - AssertEx.EqualTolerance(10, (v*10).MetersToTheSixth, MetersToTheSixthTolerance); - AssertEx.EqualTolerance(10, (10*v).MetersToTheSixth, MetersToTheSixthTolerance); - AssertEx.EqualTolerance(2, (WarpingMomentOfInertia.FromMetersToTheSixth(10)/5).MetersToTheSixth, MetersToTheSixthTolerance); - AssertEx.EqualTolerance(2, WarpingMomentOfInertia.FromMetersToTheSixth(10)/WarpingMomentOfInertia.FromMetersToTheSixth(5), MetersToTheSixthTolerance); + Assert.Equal(-1, -v.MetersToTheSixth); + Assert.Equal(2, (WarpingMomentOfInertia.FromMetersToTheSixth(3) - v).MetersToTheSixth); + Assert.Equal(2, (v + v).MetersToTheSixth); + Assert.Equal(10, (v * 10).MetersToTheSixth); + Assert.Equal(10, (10 * v).MetersToTheSixth); + Assert.Equal(2, (WarpingMomentOfInertia.FromMetersToTheSixth(10) / 5).MetersToTheSixth); + Assert.Equal(2, WarpingMomentOfInertia.FromMetersToTheSixth(10) / WarpingMomentOfInertia.FromMetersToTheSixth(5)); } [Fact] @@ -603,8 +620,6 @@ public void CompareToThrowsOnNull() [Theory] [InlineData(1, WarpingMomentOfInertiaUnit.MeterToTheSixth, 1, WarpingMomentOfInertiaUnit.MeterToTheSixth, true)] // Same value and unit. [InlineData(1, WarpingMomentOfInertiaUnit.MeterToTheSixth, 2, WarpingMomentOfInertiaUnit.MeterToTheSixth, false)] // Different value. - [InlineData(2, WarpingMomentOfInertiaUnit.MeterToTheSixth, 1, WarpingMomentOfInertiaUnit.CentimeterToTheSixth, false)] // Different value and unit. - [InlineData(1, WarpingMomentOfInertiaUnit.MeterToTheSixth, 1, WarpingMomentOfInertiaUnit.CentimeterToTheSixth, false)] // Different unit. public void Equals_ReturnsTrue_IfValueAndUnitAreEqual(double valueA, WarpingMomentOfInertiaUnit unitA, double valueB, WarpingMomentOfInertiaUnit unitB, bool expectEqual) { var a = new WarpingMomentOfInertia(valueA, unitA); @@ -664,8 +679,8 @@ public void Equals_WithTolerance(double firstValue, double secondValue) var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(firstValue); var otherQuantity = WarpingMomentOfInertia.FromMetersToTheSixth(secondValue); WarpingMomentOfInertia maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - var largerTolerance = maxTolerance * 1.1; - var smallerTolerance = maxTolerance / 1.1; + var largerTolerance = maxTolerance * 1.1m; + var smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, WarpingMomentOfInertia.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, maxTolerance)); @@ -684,7 +699,7 @@ public void Equals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() [Fact] public void HasAtLeastOneAbbreviationSpecified() { - var units = Enum.GetValues(); + var units = EnumHelper.GetValues(); foreach (var unit in units) { var defaultAbbreviation = UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(unit); @@ -697,6 +712,18 @@ public void BaseDimensionsShouldNeverBeNull() Assert.False(WarpingMomentOfInertia.BaseDimensions is null); } + [Fact] + public void Units_ReturnsTheQuantityInfoUnits() + { + Assert.Equal(WarpingMomentOfInertia.Info.Units, WarpingMomentOfInertia.Units); + } + + [Fact] + public void DefaultConversionFunctions_ReturnsTheDefaultUnitConverter() + { + Assert.Equal(UnitConverter.Default, WarpingMomentOfInertia.DefaultConversionFunctions); + } + [Fact] public void ToString_ReturnsValueAndUnitAbbreviationInCurrentCulture() { @@ -769,7 +796,8 @@ public void ToString_NullProvider_EqualsCurrentCulture(string format) public void GetHashCode_Equals() { var quantity = WarpingMomentOfInertia.FromMetersToTheSixth(1.0); - Assert.Equal(Comparison.GetHashCode(quantity.Unit, quantity.Value), quantity.GetHashCode()); + var expected = Comparison.GetHashCode(typeof(WarpingMomentOfInertia), quantity.As(WarpingMomentOfInertia.BaseUnit)); + Assert.Equal(expected, quantity.GetHashCode()); } [Theory] diff --git a/UnitsNet.Tests/GeneratedQuantityCodeTests.cs b/UnitsNet.Tests/GeneratedQuantityCodeTests.cs index 19b0af3ebe..92571ec336 100644 --- a/UnitsNet.Tests/GeneratedQuantityCodeTests.cs +++ b/UnitsNet.Tests/GeneratedQuantityCodeTests.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Reflection; using Xunit; namespace UnitsNet.Tests @@ -13,20 +14,88 @@ namespace UnitsNet.Tests public class GeneratedQuantityCodeTests { /// - /// Types with as internal representation. This is the majority of units, such as - /// . + /// Types with as internal representation. /// - public class QuantitiesWithDouble + public class QuantitiesWithFractions { [Fact] public void LengthEquals_GivenMaxError_ReturnsTrueIfWithinError() { Assert.True(Length.FromMeters(1).Equals(Length.FromMeters(1), Length.Zero), "Equal values have zero difference."); - Assert.True(Length.FromMeters(1).Equals(Length.FromMeters(1), Length.FromMillimeters(1e-5)), "Using a max difference value should not change that fact."); + Assert.True(Length.FromMeters(1).Equals(Length.FromMeters(1), Length.FromMillimeters(1e-5m)), "Using a max difference value should not change that fact."); - Assert.False(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39), Length.Zero), - "Example of floating precision arithmetic that produces slightly different results."); - Assert.True(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39), Length.FromMillimeters(1e-5)), "But the difference is very small"); + Assert.True(Length.FromMeters(1 + 0.39).Equals(Length.FromMeters(1.39)), + "Example of floating precision arithmetic that would originally produces slightly different results is now correct:" + + "this is due to the implicit rounding (15 significant digits) that is applied when constructing from double."); + + Assert.True(Length.FromMeters((1 + 0.39) / double.MaxValue).Equals(Length.FromMeters(1.39 / double.MaxValue)), + "This is also true for very small values as they would be rounded the same way."); + + Assert.False((1.39 / double.MaxValue).Equals(Length.FromMeters(1.39 / double.MaxValue).Value.ToDouble()), + "The conversion back to double is not guaranteed to round-trip"); + } + + [Fact] + public void QuantityValueComparisonEqualsAbsolute_ReturnsTrueIfWithinError() + { + Assert.True(Comparison.EqualsAbsolute(1, 1, 0)); + Assert.True(Comparison.EqualsAbsolute(1, 1, 0.001m)); + Assert.True(Comparison.EqualsAbsolute(1, 0.9999m, 0.001m)); + Assert.False(Comparison.EqualsAbsolute(1, 0.99m, 0.001m)); + Assert.False(Comparison.EqualsAbsolute(1, 0, 0.001m)); + } + + [Fact] + public void QuantityValueComparisonEqualsAbsolute_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + Assert.Throws(() => Comparison.EqualsAbsolute(1, 1, -1)); + } + + [Fact] + public void QuantityValueComparisonEquals_GivenAbsoluteTolerance_ReturnsTrueIfWithinError() + { + Assert.True(Comparison.Equals(1, 1, 0, ComparisonType.Absolute)); + Assert.True(Comparison.Equals(1, 1, 0.001m, ComparisonType.Absolute)); + Assert.True(Comparison.Equals(1, 0.9999m, 0.001m, ComparisonType.Absolute)); + Assert.False(Comparison.Equals(1, 0.99m, 0.001m, ComparisonType.Absolute)); + Assert.False(Comparison.Equals(1, 0, 0.001m, ComparisonType.Absolute)); + } + + [Fact] + public void QuantityValueComparisonEquals_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + Assert.Throws(() => Comparison.Equals(1, 1, -1, ComparisonType.Absolute)); + Assert.Throws(() => Comparison.Equals(1, 1, -1, ComparisonType.Relative)); + } + + [Fact] + public void QuantityValueComparisonEquals_WithInvalidComparisonType_ThrowsArgumentOutOfRangeException() + { + Assert.Throws(() => Comparison.Equals(1, 1, 1, (ComparisonType)(-1))); + } + + [Fact] + public void QuantityValueComparisonEqualsRelative_ReturnsTrueIfWithinError() + { + Assert.True(Comparison.EqualsRelative(1, 1, 1e-5m)); + Assert.False(Comparison.EqualsRelative(1, 0, 1e-5m)); + Assert.True(Comparison.EqualsRelative(100, 120, 0.3m)); + Assert.False(Comparison.EqualsRelative(100, 120, 0.1m)); + } + + [Fact] + public void QuantityValueComparisonEqualsRelative_WithNegativeTolerance_ThrowsArgumentOutOfRangeException() + { + Assert.Throws(() => Comparison.EqualsRelative(1, 1, -1)); + } + + [Fact] + public void QuantityValueComparisonEquals_GivenRelativeTolerance_ReturnsTrueIfWithinError() + { + Assert.True(Comparison.Equals(1, 1, 1e-5m, ComparisonType.Relative)); + Assert.False(Comparison.Equals(1, 0, 1e-5m, ComparisonType.Relative)); + Assert.True(Comparison.Equals(100, 120, 0.3m, ComparisonType.Relative)); + Assert.False(Comparison.Equals(100, 120, 0.1m, ComparisonType.Relative)); } [Fact] @@ -64,16 +133,16 @@ public void HasMultiplicationOperator_GivenTwoQuantities_ReturnsTrueIfDimensions { foreach (var firstQuantity in Quantity.Infos) { - foreach (var divisor in GetMultipliers(firstQuantity.ValueType)) + foreach (var divisor in GetMultipliers(firstQuantity.QuantityType)) { - var secondQuantity = Quantity.Infos.FirstOrDefault(x => x.ValueType == divisor); + var secondQuantity = Quantity.Infos.FirstOrDefault(x => x.QuantityType == divisor); if (secondQuantity == null) { continue; // scalers } var resultDimensions = firstQuantity.BaseDimensions * secondQuantity.BaseDimensions; - var resultingType = GetMultiplicationResult(firstQuantity.ValueType, secondQuantity.ValueType); - var resultQuantity = Quantity.Infos.FirstOrDefault(x => x.ValueType == resultingType); + var resultingType = GetMultiplicationResult(firstQuantity.QuantityType, secondQuantity.QuantityType); + var resultQuantity = Quantity.Infos.FirstOrDefault(x => x.QuantityType == resultingType); if (resultQuantity == null) { continue; // scalers @@ -96,8 +165,8 @@ public void HasDivisionOperator_GivenTwoQuantities_ReturnsTrueIfDimensionsDivisi continue; // scalers } var resultDimensions = firstQuantity.BaseDimensions / secondQuantity.BaseDimensions; - var resultingType = GetDivisionResult(firstQuantity.ValueType, secondQuantity.ValueType); - var resultQuantity = Quantity.Infos.FirstOrDefault(x => x.ValueType == resultingType); + var resultingType = GetDivisionResult(firstQuantity.QuantityType, secondQuantity.QuantityType); + var resultQuantity = Quantity.Infos.FirstOrDefault(x => x.QuantityType == resultingType); if (resultQuantity == null) { continue; // scalers @@ -107,6 +176,33 @@ public void HasDivisionOperator_GivenTwoQuantities_ReturnsTrueIfDimensionsDivisi } } + public static IEnumerable QuantitiesToMultiply { get; } = Quantity.Infos.SelectMany(s => GetMultipliers(s.QuantityType) + .Where(multiplier=> + { + if (!Quantity.ByName.ContainsKey(multiplier.Name)) return false; + Type? multiplicationResult = GetMultiplicationResult(s.QuantityType, multiplier); + return multiplicationResult != null && Quantity.ByName.ContainsKey(multiplicationResult.Name); + }).Select(type => type.Name).Select(typeName => new[] { s.Name, typeName })).ToArray(); + + [Theory(Skip = "Currently failing due to ElectricCurrent, MolarFlow, TemperatureGradient and FuelEfficiency")] + [MemberData(nameof(QuantitiesToMultiply))] + public void MultiplyingTwoQuantities_ReturnsQuantityInSIUnits(string leftName, string rightName) + { + var firstQuantity = Quantity.ByName[leftName]; + var secondQuantity = Quantity.ByName[rightName]; + + IQuantity result = Multiply(firstQuantity.BaseUnitInfo.From(1), secondQuantity.BaseUnitInfo.From(1)); + if (result.QuantityInfo.BaseDimensions.IsDimensionless()) + { + Assert.Equal(result.QuantityInfo.BaseUnitInfo.Value, result.Unit); + } + // excluding results that don't have a valid base unit such as FuelEfficiency + else if(result.QuantityInfo.UnitInfos.Any(unit => unit.BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits))) + { + Assert.True(result.QuantityInfo[result.Unit].BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)); + } + } + private static bool HasMultiplicationOperator(Type t, Type operandType) { var operation = t.GetMethod("op_Multiply", new[] { t, operandType }); @@ -142,6 +238,23 @@ private static IEnumerable GetDivisors(Type t) return t.GetMethods().Where(x => x.IsSpecialName && x.Name == "op_Division" && x.CustomAttributes.All(a => a.AttributeType != typeof(ObsoleteAttribute))) .SelectMany(x => x.GetParameters().Skip(1).Select(p => p.ParameterType)); } + + private static IQuantity Multiply(IQuantity left, IQuantity right) + { + var leftType = left.GetType(); + var rightType = right.GetType(); + var multiplyMethod = GetMultiplyMethod(leftType, rightType); + return (IQuantity)multiplyMethod.Invoke(null, new object[] { left, right })!; + } + private static MethodInfo GetMultiplyMethod(Type selfType, Type otherType) + { + return selfType.GetMethods(BindingFlags.Static | BindingFlags.Public) + .FirstOrDefault(m => m.Name == "op_Multiply" && + m.GetParameters().Length == 2 && + m.GetParameters()[0].ParameterType == selfType && + m.GetParameters()[1].ParameterType == otherType)!; + } + } } } diff --git a/UnitsNet.Tests/LinearQuantityExtensionsTest.cs b/UnitsNet.Tests/LinearQuantityExtensionsTest.cs index 0f24f1b316..072740cca4 100644 --- a/UnitsNet.Tests/LinearQuantityExtensionsTest.cs +++ b/UnitsNet.Tests/LinearQuantityExtensionsTest.cs @@ -7,8 +7,7 @@ public class LinearQuantityExtensionsTest { [Theory] [InlineData(2.0, 2.0, 0.1, true)] - // [InlineData(2.0, 2.1, 0.1, true)] // should be equal but fails due to rounding - [InlineData(2.0, 2.1, 0.10001, true)] + [InlineData(2.0, 2.1, 0.1, true)] [InlineData(2.0, 2.2, 0.1, false)] [InlineData(2.0, 2.0, 0.0, true)] [InlineData(2.0, 2.1, 0.0, false)] @@ -23,7 +22,7 @@ public void Equals_WithTolerance_ReturnsExpectedResult(double value1, double val Assert.Equal(expected, result); } - [Fact(Skip = "Fails due to rounding")] + [Fact] public void Equals_WithToleranceAtTheLimit_ReturnsTrue() { var quantity = Length.FromMeters(1); @@ -46,8 +45,7 @@ public void Equals_WithToleranceAtTheLimit_ReturnsTrue() [Theory] [InlineData(2.0, 2.0, 0.1, true)] - // [InlineData(2.0, 2.1, 0.1, true)] // should be equal but fails due to rounding - [InlineData(2.0, 2.1, 0.10001, true)] + [InlineData(2.0, 2.1, 0.1, true)] [InlineData(2.0, 2.2, 0.1, false)] [InlineData(2.0, 2.0, 0.0, true)] [InlineData(2.0, 2.1, 0.0, false)] @@ -72,8 +70,8 @@ public void Equals_WithNullOther_ReturnsFalse() Assert.False(result); } - - [Fact(Skip = "Currently throws a StackOverflowException")] + + [Fact] public void Equals_TQuantity_WithUnknownUnits_ThrowsUnitNotFoundException() { var quantity = Length.FromMeters(1); @@ -83,7 +81,7 @@ public void Equals_TQuantity_WithUnknownUnits_ThrowsUnitNotFoundException() Assert.Throws(() => quantity.Equals(quantity, invalidQuantity)); } - [Fact(Skip = "Currently throws a StackOverflowException")] + [Fact] public void Equals_IQuantity_WithUnknownUnits_ThrowsUnitNotFoundException() { var quantity = Length.FromMeters(1); diff --git a/UnitsNet.Tests/LogarithmicQuantityExtensionsTest.cs b/UnitsNet.Tests/LogarithmicQuantityExtensionsTest.cs index 3407d45ea0..9787cd909d 100644 --- a/UnitsNet.Tests/LogarithmicQuantityExtensionsTest.cs +++ b/UnitsNet.Tests/LogarithmicQuantityExtensionsTest.cs @@ -1,7 +1,6 @@ // 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. - namespace UnitsNet.Tests; public class LogarithmicQuantityExtensionsTest @@ -15,8 +14,8 @@ public void Equals_TQuantity_ComparesInLinearSpace(double firstValue, double sec var quantity = PowerRatio.FromDecibelWatts(firstValue); var otherQuantity = PowerRatio.FromDecibelWatts(secondValue); PowerRatio maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - PowerRatio largerTolerance = maxTolerance * 1.1; - PowerRatio smallerTolerance = maxTolerance / 1.1; + PowerRatio largerTolerance = maxTolerance * 1.1m; + PowerRatio smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals(quantity, PowerRatio.Zero)); Assert.True(quantity.Equals(quantity, maxTolerance)); Assert.True(quantity.Equals(otherQuantity, largerTolerance)); @@ -34,8 +33,8 @@ public void Equals_IQuantity_ComparesInLinearSpace(double firstValue, double sec var quantity = PowerRatio.FromDecibelWatts(firstValue); var otherQuantity = PowerRatio.FromDecibelWatts(secondValue); PowerRatio maxTolerance = quantity > otherQuantity ? quantity - otherQuantity : otherQuantity - quantity; - PowerRatio largerTolerance = maxTolerance * 1.1; - PowerRatio smallerTolerance = maxTolerance / 1.1; + PowerRatio largerTolerance = maxTolerance * 1.1m; + PowerRatio smallerTolerance = maxTolerance / 1.1m; Assert.True(quantity.Equals((IQuantity)quantity, PowerRatio.Zero)); Assert.True(quantity.Equals((IQuantity)quantity, maxTolerance)); Assert.True(quantity.Equals((IQuantity)otherQuantity, largerTolerance)); @@ -51,8 +50,8 @@ public void Equals_NullQuantity_ReturnsFalse() var tolerance = PowerRatio.FromDecibelWatts(1); Assert.False(quantity.Equals(null, tolerance)); } - - [Fact(Skip = "Currently throws a StackOverflowException")] + + [Fact] public void Equals_TQuantity_WithUnknownUnits_ThrowsUnitNotFoundException() { var quantity = PowerRatio.FromDecibelWatts(1); @@ -61,8 +60,8 @@ public void Equals_TQuantity_WithUnknownUnits_ThrowsUnitNotFoundException() Assert.Throws(() => quantity.Equals(invalidQuantity, quantity)); Assert.Throws(() => quantity.Equals(quantity, invalidQuantity)); } - - [Fact(Skip = "Currently throws a StackOverflowException")] + + [Fact] public void Equals_IQuantity_WithUnknownUnits_ThrowsUnitNotFoundException() { var quantity = PowerRatio.FromDecibelWatts(1); @@ -151,7 +150,7 @@ public void Sum_SingleQuantity_ReturnsCorrectSum(double value, PowerRatioUnit un PowerRatio result = quantities.Sum(); - Assert.Equal(quantity.Value, result.Value, 1e-5); + Assert.Equal(quantity.Value, result.Value); Assert.Equal(quantity.Unit, result.Unit); } @@ -167,8 +166,8 @@ public void Sum_SingleQuantity_WithSelector_ReturnsCorrectSum(double value, Powe IEnumerable quantities = new List { quantity }; PowerRatio result = quantities.Sum(x => x); - - Assert.Equal(quantity.Value, result.Value, 1e-5); + + Assert.Equal(quantity.Value, result.Value); Assert.Equal(quantity.Unit, result.Unit); } @@ -196,7 +195,7 @@ public void Sum_ReturnsCorrectSum(double value1, PowerRatioUnit unit1, double va PowerRatio result = quantities.Sum(); - Assert.Equal(expectedValue.Value, result.Value, 1e-5); + Assert.Equal(expectedValue, result); Assert.Equal(unit1, result.Unit); } @@ -223,8 +222,8 @@ public void Sum_WithSelector_ReturnsCorrectSum(double value1, PowerRatioUnit uni PowerRatio expectedValue = quantity1 + quantity2; PowerRatio result = quantities.Sum(x => x); - - Assert.Equal(expectedValue.Value, result.Value, 1e-5); + + Assert.Equal(expectedValue, result); Assert.Equal(unit1, result.Unit); } @@ -251,8 +250,8 @@ public void Sum_WithSelectorAndUnit_ReturnsCorrectSum(double value1, PowerRatioU PowerRatio expectedValue = quantity1 + quantity2; PowerRatio result = quantities.Sum(x => x, unit1); - - Assert.Equal(expectedValue.Value, result.Value, 1e-5); + + Assert.Equal(expectedValue, result); Assert.Equal(unit1, result.Unit); } @@ -261,7 +260,7 @@ public void ArithmeticMean_ThrowsOnEmptyCollection() { PowerRatio[] quantities = []; - Assert.Throws(() => LogarithmicQuantityExtensions.ArithmeticMean(quantities)); + Assert.Throws(() => quantities.ArithmeticMean(15)); } [Fact] @@ -285,7 +284,7 @@ public void ArithmeticMean_WithNullSequence_ThrowsArgumentNullException() { PowerRatio[] quantities = null!; - Assert.Throws(() => LogarithmicQuantityExtensions.ArithmeticMean(quantities)); + Assert.Throws(() => quantities.ArithmeticMean(15)); } [Fact] @@ -293,7 +292,7 @@ public void ArithmeticMean_WithNullSequenceAndUnit_ThrowsArgumentNullException() { PowerRatio[] quantities = null!; - Assert.Throws(() => LogarithmicQuantityExtensions.ArithmeticMean(quantities, PowerRatioUnit.DecibelWatt)); + Assert.Throws(() => quantities.ArithmeticMean(PowerRatioUnit.DecibelWatt, 15)); } [Fact] @@ -315,9 +314,9 @@ public void ArithmeticMean_SingleQuantity_ReturnsCorrectMean(double value, Power var quantity = new PowerRatio(value, unit); IEnumerable quantities = new List { quantity }; - PowerRatio result = LogarithmicQuantityExtensions.ArithmeticMean(quantities); + PowerRatio result = quantities.ArithmeticMean(15); - Assert.Equal(quantity.Value, result.Value, 1e-5); + Assert.Equal(quantity.Value, result.Value); Assert.Equal(quantity.Unit, result.Unit); } @@ -333,8 +332,8 @@ public void ArithmeticMean_SingleQuantity_WithSelector_ReturnsCorrectMean(double IEnumerable quantities = new List { quantity }; PowerRatio result = quantities.ArithmeticMean(x => x); - - Assert.Equal(quantity.Value, result.Value, 1e-5); + + Assert.Equal(quantity.Value, result.Value); Assert.Equal(quantity.Unit, result.Unit); } @@ -358,13 +357,13 @@ public void ArithmeticMean_ReturnsCorrectMean(double value1, PowerRatioUnit unit var quantity1 = new PowerRatio(value1, unit1); var quantity2 = new PowerRatio(value2, unit2); IEnumerable quantities = new List { quantity1, quantity2 }; - var scalingFactor = PowerRatio.LogarithmicScalingFactor; - var expectedValue = + QuantityValue scalingFactor = PowerRatio.LogarithmicScalingFactor; + QuantityValue expectedValue = ((quantity1.Value.ToLinearSpace(scalingFactor) + quantity2.As(unit1).ToLinearSpace(scalingFactor)) / 2).ToLogSpace(scalingFactor); - PowerRatio result = LogarithmicQuantityExtensions.ArithmeticMean(quantities); + PowerRatio result = quantities.ArithmeticMean(15); - Assert.Equal(expectedValue, result.Value, 1e-5); + Assert.Equal(expectedValue, result.Value); Assert.Equal(unit1, result.Unit); } @@ -388,13 +387,13 @@ public void ArithmeticMean_WithSelector_ReturnsCorrectMean(double value1, PowerR var quantity1 = new PowerRatio(value1, unit1); var quantity2 = new PowerRatio(value2, unit2); IEnumerable quantities = new List { quantity1, quantity2 }; - var scalingFactor = PowerRatio.LogarithmicScalingFactor; - var expectedValue = + QuantityValue scalingFactor = PowerRatio.LogarithmicScalingFactor; + QuantityValue expectedValue = ((quantity1.Value.ToLinearSpace(scalingFactor) + quantity2.As(unit1).ToLinearSpace(scalingFactor)) / 2).ToLogSpace(scalingFactor); PowerRatio result = quantities.ArithmeticMean(x => x); - Assert.Equal(expectedValue, result.Value, 1e-5); + Assert.Equal(expectedValue, result.Value); Assert.Equal(unit1, result.Unit); } @@ -418,13 +417,13 @@ public void ArithmeticMean_WithSelectorAndUnit_ReturnsCorrectMean(double value1, var quantity1 = new PowerRatio(value1, unit1); var quantity2 = new PowerRatio(value2, unit2); IEnumerable quantities = new List { quantity1, quantity2 }; - var scalingFactor = PowerRatio.LogarithmicScalingFactor; - var expectedValue = + QuantityValue scalingFactor = PowerRatio.LogarithmicScalingFactor; + QuantityValue expectedValue = ((quantity1.Value.ToLinearSpace(scalingFactor) + quantity2.As(unit1).ToLinearSpace(scalingFactor)) / 2).ToLogSpace(scalingFactor); PowerRatio result = quantities.ArithmeticMean(x => x, unit1); - Assert.Equal(expectedValue, result.Value, 1e-5); + Assert.Equal(expectedValue, result.Value); Assert.Equal(unit1, result.Unit); } @@ -489,7 +488,7 @@ public void GeometricMean_SingleQuantity_ReturnsCorrectMean(double value, PowerR PowerRatio result = quantities.GeometricMean(); - Assert.Equal(quantity.Value, result.Value, 1e-5); + Assert.Equal(quantity.Value, result.Value); Assert.Equal(quantity.Unit, result.Unit); } @@ -506,7 +505,7 @@ public void GeometricMean_SingleQuantity_WithSelector_ReturnsCorrectMean(double PowerRatio result = quantities.GeometricMean(x => x); - Assert.Equal(quantity.Value, result.Value, 1e-5); + Assert.Equal(quantity.Value, result.Value); Assert.Equal(quantity.Unit, result.Unit); } @@ -530,11 +529,11 @@ public void GeometricMean_ReturnsCorrectMean(double value1, PowerRatioUnit unit1 var quantity1 = new PowerRatio(value1, unit1); var quantity2 = new PowerRatio(value2, unit2); IEnumerable quantities = new List { quantity1, quantity2 }; - var expectedValue = double.RootN(quantity1.Value + quantity2.As(unit1), 2); + var expectedValue = QuantityValue.RootN(quantity1.Value + quantity2.As(unit1), 2); PowerRatio result = quantities.GeometricMean(); - Assert.Equal(expectedValue, result.Value, 1e-5); + Assert.Equal(expectedValue, result.Value); Assert.Equal(unit1, result.Unit); } @@ -558,11 +557,11 @@ public void GeometricMean_WithSelector_ReturnsCorrectMean(double value1, PowerRa var quantity1 = new PowerRatio(value1, unit1); var quantity2 = new PowerRatio(value2, unit2); IEnumerable quantities = new List { quantity1, quantity2 }; - var expectedValue = double.RootN(quantity1.Value + quantity2.As(unit1), 2); + var expectedValue = QuantityValue.RootN(quantity1.Value + quantity2.As(unit1), 2); PowerRatio result = quantities.GeometricMean(x => x); - Assert.Equal(expectedValue, result.Value, 1e-5); + Assert.Equal(expectedValue, result.Value); Assert.Equal(unit1, result.Unit); } @@ -586,11 +585,11 @@ public void GeometricMean_WithUnitAndSelector_ReturnsCorrectMean(double value1, var quantity1 = new PowerRatio(value1, unit1); var quantity2 = new PowerRatio(value2, unit2); IEnumerable quantities = new List { quantity1, quantity2 }; - var expectedValue = double.RootN(quantity1.Value + quantity2.As(unit1), 2); + var expectedValue = QuantityValue.RootN(quantity1.Value + quantity2.As(unit1), 2); PowerRatio result = quantities.GeometricMean(x => x, unit1); - Assert.Equal(expectedValue, result.Value, 1e-5); + Assert.Equal(expectedValue, result.Value); Assert.Equal(unit1, result.Unit); } } diff --git a/UnitsNet.Tests/QuantityConversionOptionsTest.cs b/UnitsNet.Tests/QuantityConversionOptionsTest.cs new file mode 100644 index 0000000000..f9304f2f6e --- /dev/null +++ b/UnitsNet.Tests/QuantityConversionOptionsTest.cs @@ -0,0 +1,146 @@ +// 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 UnitsNet.Units; +using Xunit; + +namespace UnitsNet.Tests; + +public class QuantityConversionOptionsTest +{ + [Fact] + public void CustomConversions_ShouldBeEmpty_WhenInitialized() + { + var options = new QuantityConversionOptions(); + Assert.Empty(options.CustomConversions); + } + + [Fact] + public void ConversionUnits_ShouldBeEmpty_WhenInitialized() + { + var options = new QuantityConversionOptions(); + Assert.Empty(options.ConversionUnits); + } + + [Fact] + public void CustomConversionFunctions_ShouldBeEmpty_WhenInitialized() + { + var options = new QuantityConversionOptions(); + Assert.Empty(options.CustomConversionFunctions); + } + + [Fact] + public void SetCustomConversion_ShouldAddConversionMapping() + { + var expectedConversion = QuantityConversionMapping.Create(); + var options = new QuantityConversionOptions(); + options.SetCustomConversion(); + Assert.Single(options.CustomConversions, expectedConversion); + } + + [Fact] + public void SetConversionUnits_ShouldAddUnitConversionMapping() + { + var options = new QuantityConversionOptions(); + options.SetConversionUnits(LengthUnit.Meter, MassUnit.Kilogram); + + Assert.Contains(options.ConversionUnits, mapping => + mapping.FromUnitKey.UnitEnumType == typeof(LengthUnit) && mapping.ToUnitKey.UnitEnumType == typeof(MassUnit)); + } + + [Fact] + public void SetCustomConversionFunction_ShouldAddConversionFunction() + { + var options = new QuantityConversionOptions(); + ConvertValueDelegate conversionFunction = value => value * 2; + options.SetCustomConversion(LengthUnit.Meter, MassUnit.Kilogram, conversionFunction); + + var key = new UnitConversionMapping(UnitKey.ForUnit(LengthUnit.Meter), UnitKey.ForUnit(MassUnit.Kilogram)); + Assert.True(options.CustomConversionFunctions.ContainsKey(key)); + Assert.Equal(conversionFunction, options.CustomConversionFunctions[key]); + } + + [Fact] + public void SetCustomConversion_ShouldThrowException_WhenSameType() + { + var options = new QuantityConversionOptions(); + Assert.Throws(() => options.SetCustomConversion()); + } + + [Fact] + public void SetConversionUnits_ShouldThrowException_WhenSameUnit() + { + var options = new QuantityConversionOptions(); + Assert.Throws(() => options.SetConversionUnits(LengthUnit.Meter, LengthUnit.Centimeter)); + } + + [Fact] + public void SetCustomConversion_ShouldThrowException_WhenSameUnit() + { + var options = new QuantityConversionOptions(); + Assert.Throws(() => options.SetCustomConversion(LengthUnit.Meter, LengthUnit.Centimeter, 2)); + } + + [Fact] + public void SetCustomConversionFunction_ShouldThrowException_WhenSameUnit() + { + var options = new QuantityConversionOptions(); + ConvertValueDelegate conversionFunction = value => value * 2; + Assert.Throws(() => options.SetCustomConversion(LengthUnit.Meter, LengthUnit.Centimeter, conversionFunction)); + } + + [Fact] + public void SetCustomConversion_ShouldBeCommutative() + { + var options = new QuantityConversionOptions(); + options.SetCustomConversion(); + + Assert.Contains(QuantityConversionMapping.Create(), options.CustomConversions); + } + + [Fact] + public void SetConversionUnits_ShouldMapBothDirections_WhenMapBothDirectionsIsTrue() + { + var options = new QuantityConversionOptions(); + options.SetConversionUnits(LengthUnit.Meter, MassUnit.Kilogram, true); + Assert.Contains(UnitConversionMapping.Create(MassUnit.Kilogram, LengthUnit.Meter), options.ConversionUnits); + } + + [Fact] + public void SetConversionUnits_ShouldNotMapBothDirections_WhenMapBothDirectionsIsFalse() + { + var options = new QuantityConversionOptions(); + options.SetConversionUnits(LengthUnit.Meter, MassUnit.Kilogram, false); + Assert.DoesNotContain(UnitConversionMapping.Create(MassUnit.Kilogram, LengthUnit.Meter), options.ConversionUnits); + } + + [Fact] + public void SetCustomConversion_ShouldMapBothDirections_WhenMapBothDirectionsIsTrue() + { + var options = new QuantityConversionOptions(); + options.SetCustomConversion(LengthUnit.Meter, MassUnit.Kilogram, 2, true); + + Assert.Contains(new UnitConversionMapping(UnitKey.ForUnit(LengthUnit.Meter), UnitKey.ForUnit(MassUnit.Kilogram)), options.CustomConversionFunctions); + Assert.Contains(new UnitConversionMapping(UnitKey.ForUnit(MassUnit.Kilogram), UnitKey.ForUnit(LengthUnit.Meter)), options.CustomConversionFunctions); + } + + [Fact] + public void SetCustomConversion_ShouldNotMapBothDirections_WhenMapBothDirectionsIsFalse() + { + var options = new QuantityConversionOptions(); + options.SetCustomConversion(LengthUnit.Meter, MassUnit.Kilogram, 2, false); + + Assert.Contains(new UnitConversionMapping(UnitKey.ForUnit(LengthUnit.Meter), UnitKey.ForUnit(MassUnit.Kilogram)), options.CustomConversionFunctions); + Assert.DoesNotContain(new UnitConversionMapping(UnitKey.ForUnit(MassUnit.Kilogram), UnitKey.ForUnit(LengthUnit.Meter)), options.CustomConversionFunctions); + } + + [Fact] + public void SetCustomConversionFunction_ShouldNotBeCommutative() + { + var options = new QuantityConversionOptions(); + options.SetCustomConversion(LengthUnit.Meter, MassUnit.Kilogram, value => value * 2); + + Assert.DoesNotContain(new UnitConversionMapping(UnitKey.ForUnit(MassUnit.Kilogram), UnitKey.ForUnit(LengthUnit.Meter)), options.CustomConversionFunctions); + } +} diff --git a/UnitsNet.Tests/QuantityConversionsBuilderExtensionsTests.cs b/UnitsNet.Tests/QuantityConversionsBuilderExtensionsTests.cs new file mode 100644 index 0000000000..1e02053c5f --- /dev/null +++ b/UnitsNet.Tests/QuantityConversionsBuilderExtensionsTests.cs @@ -0,0 +1,1251 @@ +// 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 System.Collections.Generic; +using System.Linq; +using System.Numerics; +using UnitsNet.Units; +using Xunit; + +namespace UnitsNet.Tests; + +public class QuantityConversionsBuilderExtensionsTests +{ + [Fact] + public void QuantityInfoLookup_GetQuantityConversions_ReturnsConversionsForQuantitiesPresentInTheLookup() + { + var quantityInfoLookup = new QuantityInfoLookup([Area.Info, ReciprocalArea.Info]); + IEnumerable quantityConversionMappings = Quantity.DefaultProvider.Conversions; + + QuantityConversion[] conversions = quantityInfoLookup.GetQuantityConversions(quantityConversionMappings).ToArray(); + + Assert.Single(conversions); + Assert.Equal(Area.Info, conversions[0].LeftQuantity); + Assert.Equal(ReciprocalArea.Info, conversions[0].RightQuantity); + } + + [Fact] + public void QuantityInfoLookup_GetQuantityConversionMappingOptions_WithCustomConversion_ReturnsTheExpectedConversion() + { + var quantityInfoLookup = new QuantityInfoLookup([Mass.Info, Volume.Info]); + QuantityConversionOptions conversionOptions = new QuantityConversionOptions().SetCustomConversion(); + + Dictionary mappingOptions = quantityInfoLookup.GetQuantityConversionMappingOptions(conversionOptions); + + Assert.Empty(mappingOptions); // no QuantityConversionMappingOptions required + } + + [Fact] + public void QuantityInfoLookup_GetQuantityConversionMappingOptions_WithCustomUnitMapping_ReturnsTheExpectedConversion() + { + var quantityInfoLookup = new QuantityInfoLookup([Mass.Info, Volume.Info]); + QuantityConversionOptions conversionOptions = new QuantityConversionOptions() + .SetCustomConversion() + .SetConversionUnits(Mass.BaseUnit, Volume.BaseUnit); + var mappingKey = new QuantityConversion(Mass.Info, Volume.Info); + + Dictionary mappingOptions = quantityInfoLookup.GetQuantityConversionMappingOptions(conversionOptions); + + Assert.Single(mappingOptions); + Assert.Contains(mappingKey, mappingOptions); + Assert.Empty(mappingOptions[mappingKey].ConversionExpressions); + Assert.Single(mappingOptions[mappingKey].CustomUnitMappings); + Assert.Contains(mappingOptions[mappingKey].CustomUnitMappings, pair => + pair.Key == UnitConversionMapping.Create(Mass.BaseUnit, Volume.BaseUnit) && + pair.Value.SourceUnit == Mass.Info.BaseUnitInfo && + pair.Value.TargetUnit == Volume.Info.BaseUnitInfo); + } + + [Fact] + public void QuantityInfoLookup_GetQuantityConversionMappingOptions_WithCustomUnitMappingAndConversionFunction_ReturnsTheExpectedConversion() + { + var quantityInfoLookup = new QuantityInfoLookup([Mass.Info, Volume.Info]); + var conversionExpression = new ConversionExpression(1); + QuantityConversionOptions conversionOptions = new QuantityConversionOptions() + .SetCustomConversion() + .SetConversionUnits(MassUnit.Gram, VolumeUnit.Liter) + .SetCustomConversion(Mass.BaseUnit, Volume.BaseUnit, conversionExpression); + var mappingKey = new QuantityConversion(Mass.Info, Volume.Info); + + Dictionary mappingOptions = quantityInfoLookup.GetQuantityConversionMappingOptions(conversionOptions); + + Assert.Single(mappingOptions); + Assert.Contains(mappingKey, mappingOptions); + Assert.Single(mappingOptions[mappingKey].ConversionExpressions); + Assert.Contains(mappingOptions[mappingKey].ConversionExpressions, pair => + pair.Key == UnitConversionMapping.Create(Mass.BaseUnit, Volume.BaseUnit) && + pair.Value.SourceUnit == Mass.Info.BaseUnitInfo && + pair.Value.TargetUnit == Volume.Info.BaseUnitInfo && + pair.Value.ConversionExpression == conversionExpression); + Assert.Single(mappingOptions[mappingKey].CustomUnitMappings); + Assert.Contains(mappingOptions[mappingKey].CustomUnitMappings, pair => + pair.Key == UnitConversionMapping.Create(MassUnit.Gram, VolumeUnit.Liter) && + pair.Value.SourceUnit == Mass.Info[MassUnit.Gram] && + pair.Value.TargetUnit == Volume.Info[VolumeUnit.Liter]); + } + + [Fact] + public void QuantityInfoLookup_GetQuantityConversionMappingOptions_IgnoresConversionsForQuantitiesNotPresentInTheLookup() + { + var quantityInfoLookup = new QuantityInfoLookup([Area.Info, ReciprocalArea.Info]); + Assert.Multiple(() => + { + Assert.Empty(quantityInfoLookup.GetQuantityConversionMappingOptions(new QuantityConversionOptions() + .SetConversionUnits(Mass.BaseUnit, Volume.BaseUnit))); + }, () => + { + Assert.Empty(quantityInfoLookup.GetQuantityConversionMappingOptions(new QuantityConversionOptions() + .SetCustomConversion(Mass.BaseUnit, Volume.BaseUnit, 1))); + }, () => + { + Assert.Empty(quantityInfoLookup.GetQuantityConversionMappingOptions(new QuantityConversionOptions() + .SetCustomConversion() + .SetConversionUnits(Mass.BaseUnit, Volume.BaseUnit) + .SetCustomConversion(Mass.BaseUnit, Volume.BaseUnit, 1))); + }); + } + + [Fact] + public void DefaultQuantityInfoLookup_GetQuantityConversions_ReturnsAllDefaultConversions() + { + IReadOnlyCollection conversionMappings = Quantity.DefaultProvider.Conversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.Quantities; + + QuantityConversion[] quantityConversions = quantityInfoLookup.GetQuantityConversions(conversionMappings).ToArray(); + + Assert.Equal(conversionMappings.Count, quantityConversions.Length); + Assert.All(conversionMappings.Zip(quantityConversions, (mapping, conversion) => (mapping, conversion)), tuple => + { + (QuantityConversionMapping mapping, QuantityConversion conversion) = tuple; + Assert.Equal(mapping.FirstQuantityType, conversion.LeftQuantity.QuantityType); + Assert.Equal(mapping.SecondQuantityType, conversion.RightQuantity.QuantityType); + }); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void NoCaching_ReturnsNoConversions(bool reduceConstants) + { + IEnumerable conversionMappings = Quantity.DefaultProvider.Conversions; + + IEnumerable conversions = UnitsNetSetup.Default.Quantities.GetQuantityConversions(conversionMappings); + + Assert.Empty(conversions.GetConversionFunctions(ConversionCachingMode.None, reduceConstants)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void BaseOnlyCaching_ReturnsBaseUnitConversions(bool reduceConstants) + { + IReadOnlyCollection conversionMappings = Quantity.DefaultProvider.Conversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.Quantities; + IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(conversionMappings).ToArray(); + + // there are currently 32 conversions here + var conversionExpressions = defaultConversions.GetConversionFunctions(ConversionCachingMode.BaseOnly, reduceConstants) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.All(defaultConversions, conversion => + { + Assert.Multiple( + () => { ConversionsWithBaseUnits_ConvertToTargetQuantity(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ConversionsWithBaseUnits_ConvertToTargetQuantity(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + }); + } + + private static void ConversionsWithBaseUnits_ConvertToTargetQuantity(Dictionary conversionExpressions, + QuantityInfo fromQuantityInfo, QuantityInfo toQuantityInfo) + { + Assert.All(fromQuantityInfo.UnitInfos, fromUnit => + { + var conversionKey = new QuantityConversionKey(fromUnit.UnitKey, toQuantityInfo.UnitType); + if (fromUnit.BaseUnits != BaseUnits.Undefined) + { + Assert.All(UnitInfo.GetUnitsWithBase(toQuantityInfo.UnitInfos, fromUnit.BaseUnits), targetUnit => + { + QuantityValue valueToConvert = 123.45m; + QuantityValue expectedValue = toQuantityInfo.ConvertFrom(valueToConvert, fromUnit).As(targetUnit.Value); + Assert.Contains(conversionKey, conversionExpressions); + Assert.Equal(targetUnit.UnitKey, conversionExpressions[conversionKey].TargetUnit); + Assert.Equal(expectedValue, conversionExpressions[conversionKey].Convert(valueToConvert)); + }); + } + else + { + Assert.DoesNotContain(conversionKey, conversionExpressions); + } + }); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AllCaching_ReturnsAllUnitConversions(bool reduceConstants) + { + IReadOnlyCollection conversionMappings = Quantity.DefaultProvider.Conversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.Quantities; + IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(conversionMappings).ToArray(); + // there are currently 156 conversions here + var expectedNumberOfConversions = defaultConversions.Sum(x => x.LeftQuantity.UnitInfos.Count + x.RightQuantity.UnitInfos.Count); + + var conversionExpressions = defaultConversions.GetConversionFunctions(ConversionCachingMode.All, reduceConstants) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.All(defaultConversions, conversion => + { + Assert.Multiple( + () => { ConversionsWithAllUnits_ConvertToTargetQuantity(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ConversionsWithAllUnits_ConvertToTargetQuantity(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + }); + Assert.Equal(expectedNumberOfConversions, conversionExpressions.Count); + } + + private static void ConversionsWithAllUnits_ConvertToTargetQuantity(Dictionary conversionExpressions, + QuantityInfo fromQuantityInfo, QuantityInfo toQuantityInfo) + { + Assert.All(fromQuantityInfo.UnitInfos, fromUnit => + { + var conversionKey = new QuantityConversionKey(fromUnit.UnitKey, toQuantityInfo.UnitType); + QuantityValue valueToConvert = 123.45m; + IQuantity expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnit); + + Assert.Contains(conversionKey, conversionExpressions); + QuantityConversionFunction conversionFunction = conversionExpressions[conversionKey]; + QuantityValue convertedValue = conversionFunction.Convert(valueToConvert); + Assert.Equal(expectedQuantity, toQuantityInfo.From(convertedValue, (Enum)conversionFunction.TargetUnit)); + }); + } + + [Theory] + [InlineData(true, typeof(Density), true)] + [InlineData(true, typeof(Density), false)] + [InlineData(false, typeof(Density), true)] + [InlineData(false, typeof(Density), false)] + [InlineData(true, typeof(SpecificVolume), true)] + [InlineData(true, typeof(SpecificVolume), false)] + [InlineData(false, typeof(SpecificVolume), true)] + [InlineData(false, typeof(SpecificVolume), false)] + public void AllCaching_WithSpecificNoneOptions_ReturnsSpecifiedUnitConversions(bool defaultConstantsReduction, Type customizedType, + bool customConstantsReduction) + { + IReadOnlyCollection conversionMappings = Quantity.DefaultProvider.Conversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.Quantities; + IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(conversionMappings).ToArray(); + // when removing the Density (with it's 56 units) the number of conversions drops from 156 to 100 (there are only 3 units of SpecificVolume which are all cached) + var expectedNumberOfConversions = defaultConversions + .Sum(x => (x.LeftQuantity.QuantityType == customizedType ? 0 : x.LeftQuantity.UnitInfos.Count) + (x.RightQuantity.QuantityType == customizedType ? 0 : x.RightQuantity.UnitInfos.Count)); + var customCachingOptions = new Dictionary { [customizedType] = new(ConversionCachingMode.None, customConstantsReduction) }; + + var conversionExpressions = defaultConversions.GetConversionFunctions(ConversionCachingMode.All, defaultConstantsReduction, customCachingOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.Multiple(() => Assert.Equal(expectedNumberOfConversions, conversionExpressions.Count), () => + { + Assert.All(defaultConversions, conversion => + { + if (conversion.LeftQuantity.QuantityType == customizedType) + { + Assert.Multiple(() => { ContainsNoConversionsFor(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ConversionsWithAllUnits_ConvertToTargetQuantity(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + } + else if (conversion.RightQuantity.QuantityType == customizedType) + { + Assert.Multiple(() => { ContainsNoConversionsFor(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }, + () => { ConversionsWithAllUnits_ConvertToTargetQuantity(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }); + } + else + { + Assert.Multiple( + () => { ConversionsWithAllUnits_ConvertToTargetQuantity(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ConversionsWithAllUnits_ConvertToTargetQuantity(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + } + }); + }); + } + [Theory] + [InlineData(true, true, false)] + [InlineData(true, false, false)] + [InlineData(false, true, false)] + [InlineData(false, false, false)] + [InlineData(true, true, true)] + [InlineData(true, false, true)] + [InlineData(false, true, true)] + [InlineData(false, false, true)] + public void AllCaching_WithSpecificNoneOptionsForBoth_ReturnsSpecifiedUnitConversions(bool defaultConstantsReduction, + bool densityConstantsReduction, bool specificVolumeConstantsReduction) + { + IReadOnlyCollection conversionMappings = Quantity.DefaultProvider.Conversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.Quantities; + IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(conversionMappings).ToArray(); + // when removing the Density (with its 56 units) and the SpecificVolume (with its 3 units) the number of conversions drops from 156 to 97 + var expectedNumberOfConversions = defaultConversions + .Where(conversion => conversion != new QuantityConversion(Density.Info, SpecificVolume.Info)) + .Sum(conversion => conversion.LeftQuantity.UnitInfos.Count + conversion.RightQuantity.UnitInfos.Count); + var customCachingOptions = new Dictionary + { + [typeof(Density)] = new(ConversionCachingMode.None, densityConstantsReduction), + [typeof(SpecificVolume)] = new(ConversionCachingMode.None, specificVolumeConstantsReduction) + }; + + var conversionExpressions = defaultConversions.GetConversionFunctions(ConversionCachingMode.All, defaultConstantsReduction, customCachingOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.Multiple(() => Assert.Equal(expectedNumberOfConversions, conversionExpressions.Count), () => + { + Assert.All(defaultConversions, conversion => + { + if (conversion.LeftQuantity.QuantityType == typeof(Density) || conversion.LeftQuantity.QuantityType == typeof(SpecificVolume)) + { + Assert.Multiple(() => { ContainsNoConversionsFor(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ContainsNoConversionsFor(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + } + else + { + Assert.Multiple( + () => { ConversionsWithAllUnits_ConvertToTargetQuantity(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ConversionsWithAllUnits_ConvertToTargetQuantity(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + } + }); + }); + } + + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(false, false)] + public void AllCaching_WithSpecificBaseOnlyOptions_ReturnsSpecifiedUnitConversions(bool defaultConstantsReduction, + bool densityConstantsReduction) + { + IReadOnlyCollection conversionMappings = Quantity.DefaultProvider.Conversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.Quantities; + IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(conversionMappings).ToArray(); + var customCachingOptions = new Dictionary { [typeof(Density)] = new(ConversionCachingMode.BaseOnly, densityConstantsReduction) }; + + var conversionExpressions = defaultConversions.GetConversionFunctions(ConversionCachingMode.All, defaultConstantsReduction, customCachingOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.All(defaultConversions, conversion => + { + if (conversion.LeftQuantity.QuantityType == typeof(Density)) + { + Assert.Multiple( + () => { ConversionsWithBaseUnits_ConvertToTargetQuantity(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ConversionsWithAllUnits_ConvertToTargetQuantity(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + } + else + { + Assert.Multiple( + () => { ConversionsWithAllUnits_ConvertToTargetQuantity(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ConversionsWithAllUnits_ConvertToTargetQuantity(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + } + }); + } + + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(false, false)] + public void AllCaching_WithSpecificAllOptions_ReturnsSpecifiedUnitConversions(bool defaultConstantsReduction, + bool densityConstantsReduction) + { + IReadOnlyCollection conversionMappings = Quantity.DefaultProvider.Conversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.Quantities; + IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(conversionMappings).ToArray(); + // the only difference is in the constants reduction parameter (there should still be 156 conversions here) + var expectedNumberOfConversions = defaultConversions.Sum(x => x.LeftQuantity.UnitInfos.Count + x.RightQuantity.UnitInfos.Count); + var customCachingOptions = new Dictionary { [typeof(Density)] = new(ConversionCachingMode.All, densityConstantsReduction) }; + + var conversionExpressions = defaultConversions.GetConversionFunctions(ConversionCachingMode.All, defaultConstantsReduction, customCachingOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.All(defaultConversions, conversion => + { + Assert.Multiple( + () => { ConversionsWithAllUnits_ConvertToTargetQuantity(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ConversionsWithAllUnits_ConvertToTargetQuantity(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + }); + Assert.Equal(expectedNumberOfConversions, conversionExpressions.Count); + } + + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(false, false)] + public void BaseOnlyCaching_WithSpecificNoneOptions_ReturnsSpecifiedUnitConversions(bool defaultConstantsReduction, + bool densityConstantsReduction) + { + IReadOnlyCollection conversionMappings = Quantity.DefaultProvider.Conversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.Quantities; + IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(conversionMappings).ToArray(); + var customCachingOptions = new Dictionary { [typeof(Density)] = new(ConversionCachingMode.None, densityConstantsReduction) }; + + var conversionExpressions = defaultConversions.GetConversionFunctions(ConversionCachingMode.BaseOnly, defaultConstantsReduction, customCachingOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.All(defaultConversions, conversion => + { + if (conversion.LeftQuantity.QuantityType == typeof(Density)) + { + Assert.Multiple(() => { ContainsNoConversionsFor(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ConversionsWithBaseUnits_ConvertToTargetQuantity(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + } + else + { + Assert.Multiple( + () => { ConversionsWithBaseUnits_ConvertToTargetQuantity(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ConversionsWithBaseUnits_ConvertToTargetQuantity(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + } + }); + } + + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(false, false)] + public void BaseOnlyCaching_WithSpecificBaseOnlyOptions_ReturnsSpecifiedUnitConversions(bool defaultConstantsReduction, + bool densityConstantsReduction) + { + IReadOnlyCollection conversionMappings = Quantity.DefaultProvider.Conversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.Quantities; + IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(conversionMappings).ToArray(); + var customCachingOptions = new Dictionary { [typeof(Density)] = new(ConversionCachingMode.BaseOnly, densityConstantsReduction) }; + + var conversionExpressions = defaultConversions.GetConversionFunctions(ConversionCachingMode.BaseOnly, defaultConstantsReduction, customCachingOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.All(defaultConversions, conversion => + { + Assert.Multiple( + () => { ConversionsWithBaseUnits_ConvertToTargetQuantity(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ConversionsWithBaseUnits_ConvertToTargetQuantity(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + }); + } + + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(false, false)] + public void BaseOnlyCaching_WithSpecificAllOptions_ReturnsSpecifiedUnitConversions(bool defaultConstantsReduction, + bool densityConstantsReduction) + { + IReadOnlyCollection conversionMappings = Quantity.DefaultProvider.Conversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.Quantities; + IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(conversionMappings).ToArray(); + var customCachingOptions = new Dictionary { [typeof(Density)] = new(ConversionCachingMode.All, densityConstantsReduction) }; + + var conversionExpressions = defaultConversions.GetConversionFunctions(ConversionCachingMode.BaseOnly, defaultConstantsReduction, customCachingOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.All(defaultConversions, conversion => + { + if (conversion.LeftQuantity.QuantityType == typeof(Density)) + { + Assert.Multiple( + () => { ConversionsWithAllUnits_ConvertToTargetQuantity(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ConversionsWithBaseUnits_ConvertToTargetQuantity(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + } + else + { + Assert.Multiple( + () => { ConversionsWithBaseUnits_ConvertToTargetQuantity(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ConversionsWithBaseUnits_ConvertToTargetQuantity(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + } + }); + } + + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(false, false)] + public void NoCaching_WithSpecificAllOptions_ReturnsSpecifiedUnitConversions(bool defaultConstantsReduction, + bool densityConstantsReduction) + { + IReadOnlyCollection conversionMappings = Quantity.DefaultProvider.Conversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.Quantities; + IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(conversionMappings).ToArray(); + // 56 units of Density + var expectedNumberOfConversions = Density.Info.UnitInfos.Count; + var customCachingOptions = new Dictionary { [typeof(Density)] = new(ConversionCachingMode.All, densityConstantsReduction) }; + + var conversionExpressions = defaultConversions.GetConversionFunctions(ConversionCachingMode.None, defaultConstantsReduction, customCachingOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.All(defaultConversions, conversion => + { + if (conversion.LeftQuantity.QuantityType == typeof(Density)) + { + Assert.Multiple(() => { ConversionsWithAllUnits_ConvertToTargetQuantity(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ContainsNoConversionsFor(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + } + else + { + Assert.Multiple( + () => { ContainsNoConversionsFor(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ContainsNoConversionsFor(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + } + }); + Assert.Equal(expectedNumberOfConversions, conversionExpressions.Count); + } + + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(false, false)] + public void NoCaching_WithSpecificBaseOnlyOptions_ReturnsSpecifiedUnitConversions(bool defaultConstantsReduction, + bool densityConstantsReduction) + { + IReadOnlyCollection conversionMappings = Quantity.DefaultProvider.Conversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.Quantities; + IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(conversionMappings).ToArray(); + var customCachingOptions = new Dictionary { [typeof(Density)] = new(ConversionCachingMode.BaseOnly, densityConstantsReduction) }; + + // there are currently only 3 conversions here (3 density units matching the 3 units of specific volume) + var conversionExpressions = defaultConversions.GetConversionFunctions(ConversionCachingMode.None, defaultConstantsReduction, customCachingOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.All(defaultConversions, conversion => + { + if (conversion.LeftQuantity.QuantityType == typeof(Density)) + { + Assert.Multiple( + () => { ConversionsWithBaseUnits_ConvertToTargetQuantity(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ContainsNoConversionsFor(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + } + else + { + Assert.Multiple(() => { ContainsNoConversionsFor(conversionExpressions, conversion.LeftQuantity, conversion.RightQuantity); }, + () => { ContainsNoConversionsFor(conversionExpressions, conversion.RightQuantity, conversion.LeftQuantity); }); + } + }); + } + + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(false, false)] + public void NoCaching_WithSpecificNoneOptions_ReturnsNoUnitConversions(bool defaultConstantsReduction, + bool densityConstantsReduction) + { + IReadOnlyCollection conversionMappings = Quantity.DefaultProvider.Conversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.Quantities; + IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(conversionMappings).ToArray(); + var customQuantityOptions = new Dictionary { [typeof(Density)] = new(ConversionCachingMode.None, densityConstantsReduction) }; + + Assert.Empty(defaultConversions.GetConversionFunctions(ConversionCachingMode.None, defaultConstantsReduction, customQuantityOptions)); + } + + private static void ContainsNoConversionsFor(Dictionary conversionExpressions, + QuantityInfo fromQuantityInfo, QuantityInfo toQuantityInfo) + { + Assert.All(fromQuantityInfo.UnitInfos, fromUnit => + { + var conversionKey = new QuantityConversionKey(fromUnit.UnitKey, toQuantityInfo.UnitType); + Assert.DoesNotContain(conversionKey, conversionExpressions); + }); + } + + [Theory] + [InlineData(ConversionCachingMode.All, true)] + [InlineData(ConversionCachingMode.BaseOnly, true)] + [InlineData(ConversionCachingMode.BaseOnly, false)] // the conversions from/to the base units are already reduced by the CodeGen + public void ReduceConstants_ReturnsUnitConversionsWithReducedCoefficients(ConversionCachingMode cachingMode, bool reduceConstants) + { + // Arrange + IReadOnlyCollection conversionMappings = Quantity.DefaultProvider.Conversions; + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.Quantities; + IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(conversionMappings); + + // Act + IEnumerable conversionExpressions = defaultConversions.GetConversionFunctions(cachingMode, reduceConstants) + .Select(pair => pair.Value.Convert); + + // Assert + Assert.All(conversionExpressions, valueDelegate => Assert.True(IsReduced(valueDelegate(QuantityValue.One)))); + } + + private static bool IsReduced(QuantityValue value) + { + (BigInteger numerator, BigInteger denominator) = value; + return BigInteger.GreatestCommonDivisor(numerator, denominator) == BigInteger.One; + } + + [Theory] + [InlineData(ConversionCachingMode.None, true, ConversionCachingMode.None, true)] + [InlineData(ConversionCachingMode.None, true, ConversionCachingMode.BaseOnly, true)] + [InlineData(ConversionCachingMode.None, true, ConversionCachingMode.All, true)] + [InlineData(ConversionCachingMode.None, false, ConversionCachingMode.None, false)] + [InlineData(ConversionCachingMode.None, false, ConversionCachingMode.BaseOnly, false)] + [InlineData(ConversionCachingMode.None, false, ConversionCachingMode.All, false)] + [InlineData(ConversionCachingMode.BaseOnly, true, ConversionCachingMode.None, true)] + [InlineData(ConversionCachingMode.BaseOnly, true, ConversionCachingMode.BaseOnly, true)] + [InlineData(ConversionCachingMode.BaseOnly, true, ConversionCachingMode.All, true)] + [InlineData(ConversionCachingMode.BaseOnly, false, ConversionCachingMode.None, false)] + [InlineData(ConversionCachingMode.BaseOnly, false, ConversionCachingMode.BaseOnly, false)] + [InlineData(ConversionCachingMode.BaseOnly, false, ConversionCachingMode.All, false)] + [InlineData(ConversionCachingMode.All, true, ConversionCachingMode.None, true)] + [InlineData(ConversionCachingMode.All, true, ConversionCachingMode.BaseOnly, true)] + [InlineData(ConversionCachingMode.All, true, ConversionCachingMode.All, true)] + [InlineData(ConversionCachingMode.All, false, ConversionCachingMode.None, false)] + [InlineData(ConversionCachingMode.All, false, ConversionCachingMode.BaseOnly, false)] + [InlineData(ConversionCachingMode.All, false, ConversionCachingMode.All, false)] + public void GetConversionFunctions_WithCustomConversionsAndCustomCachingOptions_ReturnsUnitConversionsThatIncludeTheCustomConversions( + ConversionCachingMode defaultCachingMode, bool defaultConstantsReduction, + ConversionCachingMode densityCachingMode, bool densityConstantsReduction) + { + // Arrange + var customConversionFromDensity = new CustomQuantityConversionExpressionMapping( + Density.Info[DensityUnit.KilogramPerCubicMeter], + SpecificVolume.Info[SpecificVolumeUnit.CubicMeterPerKilogram], + new ConversionExpression(2, null, -1)); + + var customConversionFromSpecificVolume = new CustomQuantityConversionExpressionMapping( + SpecificVolume.Info[SpecificVolumeUnit.CubicMeterPerKilogram], + Density.Info[DensityUnit.KilogramPerCubicMeter], + new ConversionExpression(new QuantityValue(1, 2), null, -1)); + + var conversionMappingOptions = new QuantityConversionMappingOptions + { + ConversionExpressions = + { + { + new UnitConversionMapping(customConversionFromDensity.SourceUnit.UnitKey, customConversionFromDensity.TargetUnit.UnitKey), + customConversionFromDensity + }, + { + new UnitConversionMapping(customConversionFromSpecificVolume.SourceUnit.UnitKey, customConversionFromSpecificVolume.TargetUnit.UnitKey), + customConversionFromSpecificVolume + } + } + }; + var conversionOptions = new Dictionary + { + { new QuantityConversion(Density.Info, SpecificVolume.Info), conversionMappingOptions } + }; + var customCachingOptions = new Dictionary { [typeof(Density)] = new(densityCachingMode, densityConstantsReduction) }; + IEnumerable defaultConversions = UnitsNetSetup.Default.Quantities.GetQuantityConversions(Quantity.DefaultProvider.Conversions); + + // Act + var conversionExpressions = defaultConversions.GetConversionFunctions(conversionOptions, defaultCachingMode, defaultConstantsReduction, customCachingOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + // Assert + Assert.Multiple(() => + { + // the returned result contains all our custom conversions + Assert.All(conversionMappingOptions.ConversionExpressions, pair => + { + UnitConversionMapping unitConversionKey = pair.Key; + CustomQuantityConversionExpressionMapping expressionMapping = pair.Value; + ConversionExpression conversionExpression = expressionMapping.ConversionExpression; + var conversionKey = new QuantityConversionKey(unitConversionKey.FromUnitKey, unitConversionKey.ToUnitKey.UnitEnumType); + Assert.Contains(conversionKey, conversionExpressions); + Assert.Equal(expressionMapping.TargetUnit.UnitKey, conversionExpressions[conversionKey].TargetUnit); + Assert.Equal(conversionExpression.Evaluate(10), conversionExpressions[conversionKey].Convert(10)); + }); + }, + () => + { + // all generated conversions from a DensityUnit are a function of the custom conversion expressions in our customConversionFromDensity + Assert.All(conversionExpressions.Where(x => x.Key.FromUnit.UnitEnumType == typeof(DensityUnit)), + pair => + { + QuantityConversionKey conversionKey = pair.Key; + QuantityConversionFunction conversionFunction = pair.Value; + + UnitInfo sourceUnit = Density.Info[conversionKey.FromUnit.ToUnit()]; + UnitInfo targetUnit = + SpecificVolume.Info[conversionFunction.TargetUnit.ToUnit()]; + QuantityValue valueToConvert = 10; + QuantityValue valueInSourceConversionUnit = customConversionFromDensity.SourceUnit.GetValueFrom(valueToConvert, sourceUnit); + QuantityValue valueInTargetConversionUnit = customConversionFromDensity.ConversionExpression.Evaluate(valueInSourceConversionUnit); + QuantityValue expectedValue = targetUnit.GetValueFrom(valueInTargetConversionUnit, customConversionFromDensity.TargetUnit); + + Assert.Equal(expectedValue, conversionFunction.Convert(valueToConvert)); + if (densityConstantsReduction) + { + Assert.True(IsReduced(conversionFunction.Convert(1))); + } + }); + }, + () => + { + // all generated conversions from a SpecificVolumeUnit are a function of the custom conversion expressions in our customConversionFromSpecificVolume + Assert.All(conversionExpressions.Where(x => x.Key.FromUnit.UnitEnumType == typeof(SpecificVolumeUnit)), + pair => + { + QuantityConversionKey conversionKey = pair.Key; + QuantityConversionFunction conversionFunction = pair.Value; + + UnitInfo sourceUnit = SpecificVolume.Info[conversionKey.FromUnit.ToUnit()]; + UnitInfo targetUnit = Density.Info[conversionFunction.TargetUnit.ToUnit()]; + QuantityValue valueToConvert = 10; + QuantityValue valueInSourceConversionUnit = customConversionFromSpecificVolume.SourceUnit.GetValueFrom(valueToConvert, sourceUnit); + QuantityValue valueInTargetConversionUnit = + customConversionFromSpecificVolume.ConversionExpression.Evaluate(valueInSourceConversionUnit); + QuantityValue expectedValue = targetUnit.GetValueFrom(valueInTargetConversionUnit, customConversionFromSpecificVolume.TargetUnit); + + Assert.Equal(expectedValue, conversionFunction.Convert(valueToConvert)); + if (defaultConstantsReduction) + { + Assert.True(IsReduced(conversionFunction.Convert(1))); + } + }); + } + ); + } + + [Theory] + [InlineData(ConversionCachingMode.None, true)] + [InlineData(ConversionCachingMode.BaseOnly, true)] + [InlineData(ConversionCachingMode.All, true)] + [InlineData(ConversionCachingMode.None, false)] + [InlineData(ConversionCachingMode.BaseOnly, false)] + [InlineData(ConversionCachingMode.All, false)] + public void GetConversionFunctions_WithUnitConversionMappings_ReturnsTheSpecifiedConversions(ConversionCachingMode conversionCachingMode, bool reduceConstants) + { + // Arrange + var conversionMappingOptions = new QuantityConversionMappingOptions + { + CustomUnitMappings = + { + { + new UnitConversionMapping(DensityUnit.GramPerLiter, SpecificVolumeUnit.CubicMeterPerKilogram), + new CustomQuantityConversionUnitMapping(Density.Info[DensityUnit.GramPerLiter], + SpecificVolume.Info[SpecificVolumeUnit.CubicMeterPerKilogram]) + }, + { + new UnitConversionMapping(DensityUnit.GramPerCubicCentimeter, SpecificVolumeUnit.CubicFootPerPound), + new CustomQuantityConversionUnitMapping(Density.Info[DensityUnit.GramPerCubicCentimeter], + SpecificVolume.Info[SpecificVolumeUnit.CubicFootPerPound]) + }, + { + new UnitConversionMapping(DensityUnit.NanogramPerMilliliter, SpecificVolumeUnit.CubicFootPerPound), + new CustomQuantityConversionUnitMapping(Density.Info[DensityUnit.NanogramPerMilliliter], + SpecificVolume.Info[SpecificVolumeUnit.CubicFootPerPound]) + }, + { + new UnitConversionMapping(SpecificVolumeUnit.CubicFootPerPound, DensityUnit.NanogramPerMilliliter), + new CustomQuantityConversionUnitMapping(SpecificVolume.Info[SpecificVolumeUnit.CubicFootPerPound], + Density.Info[DensityUnit.NanogramPerMilliliter]) + }, + { + new UnitConversionMapping(SpecificVolumeUnit.CubicMeterPerKilogram, DensityUnit.MilligramPerMilliliter), + new CustomQuantityConversionUnitMapping(SpecificVolume.Info[SpecificVolumeUnit.CubicMeterPerKilogram], + Density.Info[DensityUnit.MilligramPerMilliliter]) + }, + } + }; + var conversionOptions = new Dictionary() + { + { + new QuantityConversion(Density.Info, SpecificVolume.Info), + conversionMappingOptions + } + }; + IEnumerable defaultConversions = UnitsNetSetup.Default.Quantities.GetQuantityConversions(Quantity.DefaultProvider.Conversions); + var emptyCachingOptions = new Dictionary(); + + // Act + var conversionExpressions = defaultConversions.GetConversionFunctions(conversionOptions, conversionCachingMode, reduceConstants, emptyCachingOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + // Assert + Assert.All(conversionMappingOptions.CustomUnitMappings, mapping => + { + UnitInfo fromUnit = mapping.Value.SourceUnit; + UnitInfo toUnit = mapping.Value.TargetUnit; + QuantityValue valueToConvert = 123.45m; + QuantityValue expectedValue = toUnit.QuantityInfo.ConvertFrom(valueToConvert, fromUnit).As(toUnit.Value); + var conversionKey = new QuantityConversionKey(fromUnit.UnitKey, toUnit.QuantityInfo.UnitType); + Assert.Contains(conversionKey, conversionExpressions); + Assert.Equal(expectedValue, conversionExpressions[conversionKey].Convert(valueToConvert)); + Assert.Equal(toUnit.UnitKey, conversionExpressions[conversionKey].TargetUnit); + // this maybe a bit redundant but that's the only covering line for the ResultType property (its only used for the default equality contract) + Assert.Equal(conversionKey.ResultType, conversionExpressions[conversionKey].TargetUnit.UnitEnumType); + if (reduceConstants) + { + Assert.True(IsReduced(conversionExpressions[conversionKey].Convert(1))); + } + }); + + if (conversionCachingMode == ConversionCachingMode.None) + { + Assert.Equal(conversionMappingOptions.CustomUnitMappings.Count, conversionExpressions.Count); + } + } + + [Theory] + [InlineData(ConversionCachingMode.None, true)] + [InlineData(ConversionCachingMode.BaseOnly, true)] + [InlineData(ConversionCachingMode.All, true)] + [InlineData(ConversionCachingMode.None, false)] + [InlineData(ConversionCachingMode.BaseOnly, false)] + [InlineData(ConversionCachingMode.All, false)] + public void GetConversionFunctions_WithUnitConversionMappingsAndCustomFunctions_ReturnsTheMergedConversions(ConversionCachingMode conversionCachingMode, bool reduceConstants) + { + // Arrange + var customConversionFromDensity = new CustomQuantityConversionExpressionMapping( + Density.Info[DensityUnit.PoundPerCubicFoot], + SpecificVolume.Info[SpecificVolumeUnit.CubicFootPerPound], + new ConversionExpression(2, null, -1)); + var customConversionFromSpecificVolume = new CustomQuantityConversionExpressionMapping( + SpecificVolume.Info[SpecificVolumeUnit.CubicFootPerPound], + Density.Info[DensityUnit.PoundPerCubicFoot], + new ConversionExpression(new QuantityValue(1, 2), null, -1)); + var conversionMappingOptions = new QuantityConversionMappingOptions + { + ConversionExpressions = + { + { + new UnitConversionMapping(customConversionFromDensity.SourceUnit.UnitKey, customConversionFromDensity.TargetUnit.UnitKey), + customConversionFromDensity + }, + { + new UnitConversionMapping(customConversionFromSpecificVolume.SourceUnit.UnitKey, customConversionFromSpecificVolume.TargetUnit.UnitKey), + customConversionFromSpecificVolume + } + }, + CustomUnitMappings = + { + { + new UnitConversionMapping(DensityUnit.GramPerLiter, SpecificVolumeUnit.CubicMeterPerKilogram), new CustomQuantityConversionUnitMapping( + Density.Info[DensityUnit.GramPerLiter], + SpecificVolume.Info[SpecificVolumeUnit.CubicMeterPerKilogram]) + }, + { + new UnitConversionMapping(DensityUnit.NanogramPerMilliliter, SpecificVolumeUnit.CubicFootPerPound), new CustomQuantityConversionUnitMapping( + Density.Info[DensityUnit.NanogramPerMilliliter], + SpecificVolume.Info[SpecificVolumeUnit.CubicFootPerPound]) + } + } + }; + var conversionOptions = new Dictionary + { + { new QuantityConversion(Density.Info, SpecificVolume.Info), conversionMappingOptions } + }; + IEnumerable defaultConversions = UnitsNetSetup.Default.Quantities.GetQuantityConversions(Quantity.DefaultProvider.Conversions); + var emptyCachingOptions = new Dictionary(); + + // Act + var conversionExpressions = defaultConversions.GetConversionFunctions(conversionOptions, conversionCachingMode, reduceConstants, emptyCachingOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + // Assert + Assert.Multiple(() => + { + Assert.All(conversionMappingOptions.ConversionExpressions, pair => + { + var conversionKey = new QuantityConversionKey(pair.Key.FromUnitKey, pair.Key.ToUnitKey.UnitEnumType); + Assert.True(conversionExpressions.ContainsKey(conversionKey)); + Assert.Equal(pair.Value.ConversionExpression.Evaluate(10), conversionExpressions[conversionKey].Convert(10)); + }); + }, () => + { + Assert.All(conversionMappingOptions.CustomUnitMappings, pair => + { + var conversionKey = new QuantityConversionKey(pair.Key.FromUnitKey, pair.Key.ToUnitKey.UnitEnumType); + UnitInfo sourceUnit = pair.Value.SourceUnit; + UnitInfo targetUnit = pair.Value.TargetUnit; + QuantityValue valueToConvert = 10; + QuantityValue valueInSourceConversionUnit = customConversionFromDensity.SourceUnit.GetValueFrom(valueToConvert, sourceUnit); + QuantityValue valueInTargetConversionUnit = customConversionFromDensity.ConversionExpression.Evaluate(valueInSourceConversionUnit); + QuantityValue expectedValue = targetUnit.GetValueFrom(valueInTargetConversionUnit, customConversionFromDensity.TargetUnit); + Assert.True(conversionExpressions.ContainsKey(conversionKey)); + Assert.Equal(expectedValue, conversionExpressions[conversionKey].Convert(valueToConvert)); + if (reduceConstants) + { + Assert.True(IsReduced(conversionExpressions[conversionKey].Convert(1))); + } + }); + }); + + if (conversionCachingMode == ConversionCachingMode.None) + { + Assert.Equal(Density.Units.Count + SpecificVolume.Units.Count, + conversionExpressions.Count); // an expression is provided for each of the units (irrespective of the caching mode) + } + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void GetConversionFunctions_WithInvalidConversionDimensions_And_Caching_None_ReturnsEmpty(bool reduceConstants) + { + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.Quantities; + IEnumerable defaultConversionMappings = Quantity.DefaultProvider.Conversions; + IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(defaultConversionMappings) + .Append(new QuantityConversion(Mass.Info, Volume.Info)).ToList(); + + Assert.Empty(defaultConversions.GetConversionFunctions(ConversionCachingMode.None, reduceConstants)); + } + + [Theory] + [InlineData(ConversionCachingMode.BaseOnly, true)] + [InlineData(ConversionCachingMode.All, true)] + [InlineData(ConversionCachingMode.BaseOnly, false)] + [InlineData(ConversionCachingMode.All, false)] + public void GetConversionFunctions_WithInvalidConversionDimensions_And_Caching_ThrowsInvalidConversionException(ConversionCachingMode cachingMode, bool reduceConstants) + { + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.Quantities; + IEnumerable defaultConversionMappings = Quantity.DefaultProvider.Conversions; + IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(defaultConversionMappings) + .Append(new QuantityConversion(Mass.Info, Volume.Info)).ToList(); + + Assert.Throws(() => defaultConversions.GetConversionFunctions(cachingMode, reduceConstants).ToList()); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void GetConversionFunctions_WithNoMatchingBaseUnits_And_Caching_BaseOnly_ReturnsEmpty(bool reduceConstants) + { + // we simulate a target quantity without any base units + var densityInfo = Density.DensityInfo.CreateDefault(unitInfos => + unitInfos.Select(x => new UnitDefinition(x.Value, x.PluralName, BaseUnits.Undefined))); + IEnumerable defaultConversions = [new(densityInfo, SpecificVolume.Info)]; + + Assert.Empty(defaultConversions.GetConversionFunctions(ConversionCachingMode.BaseOnly, reduceConstants)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void GetConversionFunctions_WithNoMatchingBaseUnits_And_Caching_All_ThrowsInvalidConversionException(bool reduceConstants) + { + // we simulate a target quantity without any base units + var densityInfo = Density.DensityInfo.CreateDefault(unitInfos => + unitInfos.Select(x => new UnitDefinition(x.Value, x.PluralName, BaseUnits.Undefined))); + IEnumerable defaultConversions = [new(densityInfo, SpecificVolume.Info)]; + + Assert.Throws(() => defaultConversions.GetConversionFunctions(ConversionCachingMode.All, reduceConstants).ToList()); + } + + // [Theory] + // [InlineData(ConversionCachingMode.None, true, ConversionCachingMode.None, false)] + // [InlineData(ConversionCachingMode.BaseOnly, true, ConversionCachingMode.None, false)] + // [InlineData(ConversionCachingMode.All, true, ConversionCachingMode.None, false)] + // [InlineData(ConversionCachingMode.None, false, ConversionCachingMode.None, false)] + // [InlineData(ConversionCachingMode.BaseOnly, false, ConversionCachingMode.None, false)] + // [InlineData(ConversionCachingMode.All, false, ConversionCachingMode.None, false)] + // public void GetConversionFunctions_WithUnitConversionMappings_WithInvalidDimensions_ThrowsInvalidConversionException(ConversionCachingMode cachingMode, bool defaultConstantsReduction, + // ConversionCachingMode massCachingMode, bool massConstantsReduction) + // { + // QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.QuantityInfoLookup; + // IEnumerable defaultConversionMappings = Quantity.DefaultProvider.Conversions; + // IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(defaultConversionMappings) + // .Append(new QuantityConversion(Mass.Info, Volume.Info)).ToList(); + // var conversionMappingOptions = new QuantityConversionMappingOptions + // { + // CustomUnitMappings = + // { + // { + // new UnitConversionMapping(Mass.BaseUnit, Volume.BaseUnit), new CustomQuantityConversionUnitMapping(Mass.Info.BaseUnitInfo, Volume.Info.BaseUnitInfo) + // } + // } + // }; + // var conversionOptions = new Dictionary + // { + // { new QuantityConversion(Mass.Info, Volume.Info), conversionMappingOptions } + // }; + // + // var customCachingOptions = new Dictionary { [typeof(Mass)] = new(massCachingMode, massConstantsReduction) }; + // + // Assert.Throws(() => defaultConversions.GetConversionFunctions(conversionOptions, cachingMode, defaultConstantsReduction, customCachingOptions).ToList()); + // } + + // [Theory] + // [InlineData(ConversionCachingMode.None, true, ConversionCachingMode.None, false)] + // [InlineData(ConversionCachingMode.BaseOnly, true, ConversionCachingMode.None, false)] + // [InlineData(ConversionCachingMode.All, true, ConversionCachingMode.None, false)] + // [InlineData(ConversionCachingMode.None, false, ConversionCachingMode.None, false)] + // [InlineData(ConversionCachingMode.BaseOnly, false, ConversionCachingMode.None, false)] + // [InlineData(ConversionCachingMode.All, false, ConversionCachingMode.None, false)] + // public void GetConversionFunctions_WithUnitConversionMappings_WithNoBaseUnits_ThrowsInvalidConversionException(ConversionCachingMode cachingMode, bool defaultConstantsReduction, + // ConversionCachingMode massCachingMode, bool massConstantsReduction) + // { + // // we simulate a target quantity without any base units + // var densityInfo = Density.DensityInfo.CreateDefault(unitInfos => + // unitInfos.Select(x => new UnitDefinition(x.Value, x.PluralName, BaseUnits.Undefined))); + // IEnumerable defaultConversions = [new(densityInfo, SpecificVolume.Info)]; + // + // var conversionMappingOptions = new QuantityConversionMappingOptions + // { + // CustomUnitMappings = + // { + // { + // new UnitConversionMapping(Density.BaseUnit, SpecificVolume.BaseUnit), new CustomQuantityConversionUnitMapping(densityInfo.BaseUnitInfo, SpecificVolume.Info.BaseUnitInfo) + // } + // } + // }; + // var conversionOptions = new Dictionary + // { + // { new QuantityConversion(densityInfo, SpecificVolume.Info), conversionMappingOptions } + // }; + // + // var customCachingOptions = new Dictionary + // { + // [typeof(Mass)] = new(massCachingMode, massConstantsReduction) + // }; + // + // Assert.Throws(() => defaultConversions.GetConversionFunctions(conversionOptions, cachingMode, defaultConstantsReduction, customCachingOptions).ToList()); + // } + + [Theory] + [InlineData(ConversionCachingMode.None, true, ConversionCachingMode.None, false)] + [InlineData(ConversionCachingMode.BaseOnly, true, ConversionCachingMode.None, false)] + [InlineData(ConversionCachingMode.All, true, ConversionCachingMode.None, false)] + [InlineData(ConversionCachingMode.None, false, ConversionCachingMode.None, false)] + [InlineData(ConversionCachingMode.BaseOnly, false, ConversionCachingMode.None, false)] + [InlineData(ConversionCachingMode.All, false, ConversionCachingMode.None, false)] + [InlineData(ConversionCachingMode.None, true, ConversionCachingMode.BaseOnly, false)] + [InlineData(ConversionCachingMode.BaseOnly, true, ConversionCachingMode.BaseOnly, false)] + [InlineData(ConversionCachingMode.All, true, ConversionCachingMode.BaseOnly, false)] + [InlineData(ConversionCachingMode.None, false, ConversionCachingMode.BaseOnly, false)] + [InlineData(ConversionCachingMode.BaseOnly, false, ConversionCachingMode.BaseOnly, false)] + [InlineData(ConversionCachingMode.All, false, ConversionCachingMode.BaseOnly, false)] + [InlineData(ConversionCachingMode.All, true, ConversionCachingMode.All, false)] + [InlineData(ConversionCachingMode.None, false, ConversionCachingMode.All, false)] + [InlineData(ConversionCachingMode.BaseOnly, false, ConversionCachingMode.All, false)] + [InlineData(ConversionCachingMode.All, false, ConversionCachingMode.All, false)] + public void GetConversionFunctions_WithUnitConversionMappings_WithNoBaseUnits_ThrowsInvalidConversionException(ConversionCachingMode cachingMode, bool defaultConstantsReduction, + ConversionCachingMode massCachingMode, bool massConstantsReduction) + { + // we simulate a target quantity without any base units + var densityInfo = Density.DensityInfo.CreateDefault(unitInfos => + unitInfos.Select(x => new UnitDefinition(x.Value, x.PluralName, BaseUnits.Undefined))); + IEnumerable defaultConversions = [new(densityInfo, SpecificVolume.Info)]; + + var conversionMappingOptions = new QuantityConversionMappingOptions + { + CustomUnitMappings = + { + // { + // new UnitConversionMapping(Density.BaseUnit, SpecificVolume.BaseUnit), new CustomQuantityConversionUnitMapping(densityInfo.BaseUnitInfo, SpecificVolume.Info.BaseUnitInfo) + // }, + { + new UnitConversionMapping(SpecificVolume.BaseUnit, Density.BaseUnit), new CustomQuantityConversionUnitMapping(SpecificVolume.Info.BaseUnitInfo, densityInfo.BaseUnitInfo) + } + } + }; + var conversionOptions = new Dictionary + { + { new QuantityConversion(densityInfo, SpecificVolume.Info), conversionMappingOptions } + }; + + var customCachingOptions = new Dictionary + { + [typeof(Density)] = new(cachingMode, defaultConstantsReduction), + [typeof(SpecificVolume)] = new(massCachingMode, massConstantsReduction) + }; + + Assert.Throws(() => defaultConversions.GetConversionFunctions(conversionOptions, ConversionCachingMode.All, true, customCachingOptions).ToList()); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void GetConversionFunctions_WithInvalidCachingMode_ThrowsArgumentException(bool reduceConstants) + { + QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.Quantities; + IReadOnlyCollection conversionMappings = Quantity.DefaultProvider.Conversions; + const ConversionCachingMode invalidCachingMode = (ConversionCachingMode)(-1); + IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(conversionMappings); + + Assert.Multiple(() => + Assert.Throws(() => defaultConversions.GetConversionFunctions(invalidCachingMode, reduceConstants)), + () => + { + var emptyOptions = new Dictionary(); + Assert.Throws(() => defaultConversions.GetConversionFunctions(invalidCachingMode, reduceConstants, emptyOptions) + .ToList()); + }, + () => + { + var validOptions = new Dictionary { [typeof(Density)] = new() }; + Assert.Throws(() => defaultConversions.GetConversionFunctions(invalidCachingMode, reduceConstants, validOptions) + .ToList()); + }, + () => + { + var invalidOptions = new Dictionary { [typeof(Density)] = new(invalidCachingMode) }; + Assert.Throws(() => defaultConversions.GetConversionFunctions(default, reduceConstants, invalidOptions) + .ToList()); + }, + () => + { + var invalidOptions = new Dictionary { [typeof(Density)] = new(invalidCachingMode) }; + var conversionMappingOptions = new QuantityConversionMappingOptions + { + CustomUnitMappings = + { + { + new UnitConversionMapping(DensityUnit.GramPerLiter, SpecificVolumeUnit.CubicMeterPerKilogram), new CustomQuantityConversionUnitMapping( + Density.Info[DensityUnit.GramPerLiter], + SpecificVolume.Info[SpecificVolumeUnit.CubicMeterPerKilogram]) + }, + { + new UnitConversionMapping(DensityUnit.NanogramPerMilliliter, SpecificVolumeUnit.CubicFootPerPound), new CustomQuantityConversionUnitMapping( + Density.Info[DensityUnit.NanogramPerMilliliter], + SpecificVolume.Info[SpecificVolumeUnit.CubicFootPerPound]) + } + } + }; + var conversionOptions = new Dictionary + { + { new QuantityConversion(Density.Info, SpecificVolume.Info), conversionMappingOptions } + }; + + Assert.Throws(() => defaultConversions.GetConversionFunctions(conversionOptions, default, reduceConstants, invalidOptions) + .ToList()); + }); + } + + + // [Theory] + // [InlineData(true)] + // [InlineData(false)] + // public void GetConversionFunctions_WithInvalidConversionDimensions_And_CachingOptions_None_ReturnsEmpty(bool reduceConstants) + // { + // QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.QuantityInfoLookup; + // IEnumerable defaultConversionMappings = Quantity.DefaultProvider.Conversions; + // IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(defaultConversionMappings) + // .Append(new QuantityConversion(Mass.Info, Volume.Info)).ToList(); + // var customCachingOptions = new Dictionary + // { + // [typeof(Mass)] = new(ConversionCachingMode.None, reduceConstants), + // [typeof(Volume)] = new(ConversionCachingMode.None, reduceConstants) + // }; + // + // var conversions = defaultConversions.GetConversionFunctions(ConversionCachingMode.All, reduceConstants, customCachingOptions) + // .ToDictionary(pair => pair.Key, pair => pair.Value); + // + // Assert.NotEmpty(conversions); + // Assert.False(conversions.ContainsKey(new QuantityConversionKey(Mass.BaseUnit, typeof(Volume)))); + // } + // + // [Theory] + // [InlineData(ConversionCachingMode.BaseOnly, true)] + // [InlineData(ConversionCachingMode.All, true)] + // [InlineData(ConversionCachingMode.BaseOnly, false)] + // [InlineData(ConversionCachingMode.All, false)] + // public void GetConversionFunctions_WithInvalidConversionDimensions_And_CachingOptions_ThrowsInvalidConversionException(ConversionCachingMode cachingMode, bool reduceConstants) + // { + // QuantityInfoLookup quantityInfoLookup = UnitsNetSetup.Default.QuantityInfoLookup; + // IEnumerable defaultConversionMappings = Quantity.DefaultProvider.Conversions; + // IEnumerable defaultConversions = quantityInfoLookup.GetQuantityConversions(defaultConversionMappings) + // .Append(new QuantityConversion(Mass.Info, Volume.Info)).ToList(); + // var customCachingOptions = new Dictionary + // { + // [typeof(Mass)] = new(cachingMode, reduceConstants), + // [typeof(Volume)] = new(cachingMode, reduceConstants) + // }; + // + // Assert.Throws(() => defaultConversions.GetConversionFunctions(ConversionCachingMode.None, reduceConstants, customCachingOptions).ToList()); + // } + // + // [Theory] + // [InlineData(true)] + // [InlineData(false)] + // public void GetConversionFunctions_WithNoMatchingBaseUnits_And_CachingOptions_BaseOnly_ReturnsEmpty(bool reduceConstants) + // { + // // we simulate a target quantity without any base units + // var densityInfo = Density.DensityInfo.CreateDefault(unitInfos => + // unitInfos.Select(x => new UnitDefinition(x.Value, x.PluralName, BaseUnits.Undefined))); + // IEnumerable defaultConversions = [new(densityInfo, SpecificVolume.Info)]; + // var customCachingOptions = new Dictionary + // { + // [typeof(Density)] = new(ConversionCachingMode.BaseOnly, reduceConstants), + // [typeof(SpecificVolume)] = new(ConversionCachingMode.BaseOnly, reduceConstants) + // }; + // + // Assert.Empty(defaultConversions.GetConversionFunctions(ConversionCachingMode.None, reduceConstants, customCachingOptions)); + // } + // + // [Theory] + // [InlineData(true)] + // [InlineData(false)] + // public void GetConversionFunctions_WithNoMatchingBaseUnits_And_CachingOptions_All_ThrowsInvalidConversionException(bool reduceConstants) + // { + // // we simulate a target quantity without any base units + // var densityInfo = Density.DensityInfo.CreateDefault(unitInfos => + // unitInfos.Select(x => new UnitDefinition(x.Value, x.PluralName, BaseUnits.Undefined))); + // IEnumerable defaultConversions = [new(densityInfo, SpecificVolume.Info)]; + // var customCachingOptions = new Dictionary + // { + // [typeof(Density)] = new(ConversionCachingMode.All, reduceConstants), + // [typeof(SpecificVolume)] = new(ConversionCachingMode.All, reduceConstants) + // }; + // + // Assert.Throws(() => defaultConversions.GetConversionFunctions(ConversionCachingMode.None, reduceConstants, customCachingOptions).ToList()); + // } + + + [Theory] + [InlineData(AreaUnit.SquareMeter, ReciprocalAreaUnit.InverseSquareMeter, 1)] + [InlineData(AreaUnit.SquareCentimeter, ReciprocalAreaUnit.InverseSquareCentimeter, 1)] + [InlineData(AreaUnit.SquareFoot, ReciprocalAreaUnit.InverseSquareFoot, 1)] + [InlineData(AreaUnit.Acre, ReciprocalAreaUnit.InverseSquareKilometer, 247.1053814671653)] + public void GetQuantityConversionFrom_QuantityWithInverseDimensions_ReturnsTheClosestMatchingUnit(AreaUnit fromUnit, ReciprocalAreaUnit expectedUnit, double expectedCoefficient) + { + QuantityConversionFunction conversionFunction = ReciprocalArea.Info.GetQuantityConversionFrom(Area.Info[fromUnit]); + + Assert.Equal(expectedUnit, conversionFunction.TargetUnit.ToUnit()); + Assert.Equal(expectedCoefficient, conversionFunction.Convert(QuantityValue.One).ToDouble(), 14); + } + + [Theory] + [InlineData(MassConcentrationUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicMeter, 1)] + [InlineData(MassConcentrationUnit.GramPerCubicMeter, DensityUnit.GramPerCubicMeter, 1)] + [InlineData(MassConcentrationUnit.PoundPerCubicFoot, DensityUnit.PoundPerCubicFoot, 1)] + [InlineData(MassConcentrationUnit.GramPerLiter, DensityUnit.GramPerLiter, 1)] + [InlineData(MassConcentrationUnit.PoundPerUSGallon, DensityUnit.PoundPerUSGallon, 1)] + public void GetQuantityConversionFrom_QuantityWithSameDimensions_ReturnsTheClosestMatchingUnit(MassConcentrationUnit fromUnit, DensityUnit expectedUnit, double expectedCoefficient) + { + QuantityConversionFunction conversionFunction = Density.Info.GetQuantityConversionFrom(MassConcentration.Info[fromUnit]); + + Assert.Equal(expectedUnit, conversionFunction.TargetUnit.ToUnit()); + Assert.Equal(expectedCoefficient, conversionFunction.Convert(QuantityValue.One)); + } + + [Theory] + [InlineData(MassFractionUnit.DecimalFraction, RatioUnit.DecimalFraction, 1)] + [InlineData(MassFractionUnit.Percent, RatioUnit.Percent, 1)] + [InlineData(MassFractionUnit.PartPerMillion, RatioUnit.PartPerMillion, 1)] + [InlineData(MassFractionUnit.GramPerKilogram, RatioUnit.PartPerThousand, 1)] + [InlineData(MassFractionUnit.HectogramPerGram, RatioUnit.DecimalFraction, 100)] + public void GetQuantityConversionFrom_DimensionlessQuantity_ReturnsTheClosestMatchingUnit(MassFractionUnit fromUnit, RatioUnit expectedUnit, double expectedCoefficient) + { + QuantityConversionFunction conversionFunction = Ratio.Info.GetQuantityConversionFrom(MassFraction.Info[fromUnit]); + + Assert.Equal(expectedUnit, conversionFunction.TargetUnit.ToUnit()); + Assert.Equal(expectedCoefficient, conversionFunction.Convert(QuantityValue.One)); + } + + [Fact] + public void GetQuantityConversionFrom_QuantityWithIncompatibleBaseDimensions_ThrowsInvalidConversionException() + { + Assert.Throws(() => Mass.Info.GetQuantityConversionFrom(Volume.Info.BaseUnitInfo)); + } + + [Fact] + public void GetQuantityConversionFrom_QuantityWithIncompatibleBaseUnits_ThrowsInvalidConversionException() + { + UnitInfo sourceUnitInfo = MassConcentration.Info.BaseUnitInfo; + // we simulate a target quantity without any base units + var targetQuantityInfo = Density.DensityInfo.CreateDefault(unitInfos => + unitInfos.Select(x => new UnitDefinition(x.Value, x.PluralName, BaseUnits.Undefined))); + + Assert.Throws(() => targetQuantityInfo.GetQuantityConversionFrom(sourceUnitInfo)); + } +} diff --git a/UnitsNet.Tests/QuantityIFormattableTests.cs b/UnitsNet.Tests/QuantityIFormattableTests.cs index a214cc6392..ca8bd9a86c 100644 --- a/UnitsNet.Tests/QuantityIFormattableTests.cs +++ b/UnitsNet.Tests/QuantityIFormattableTests.cs @@ -25,8 +25,8 @@ public void GFormatStringEqualsToString() [Fact] public void EmptyOrNullFormatStringEqualsGFormat() { - Assert.Equal(MyLength.ToString("G"), MyLength.ToString(string.Empty)); - Assert.Equal(MyLength.ToString("G"), MyLength.ToString(format: null)); + Assert.Equal(MyLength.ToString("G"), MyLength.ToString(format: string.Empty)); + Assert.Equal(MyLength.ToString("G"), MyLength.ToString(format: null!)); } [Fact] @@ -51,14 +51,14 @@ public void UnsupportedFormatStringThrowsException() { Assert.Throws(() => MyLength.ToString("z")); } - + // The default, parameterless ToString() method represents the result with all significant digits, without a group separator. [Theory] -#if NET - [InlineData(double.MinValue, "-1.7976931348623157E+308 m")] -#else + #if NET + [InlineData(double.MinValue, "-1.797693134862315E+308 m")] + #else [InlineData(double.MinValue, "-1.79769313486232E+308 m")] -#endif + #endif [InlineData(-0.819999999999, "-0.819999999999 m")] [InlineData(-0.111234, "-0.111234 m")] [InlineData(-0.1, "-0.1 m")] @@ -70,16 +70,17 @@ public void UnsupportedFormatStringThrowsException() [InlineData(0.1, "0.1 m")] [InlineData(0.111234, "0.111234 m")] [InlineData(0.819999999999, "0.819999999999 m")] -#if NET - [InlineData(double.MaxValue, "1.7976931348623157E+308 m")] -#else + #if NET + [InlineData(double.MaxValue, "1.797693134862315E+308 m")] + #else [InlineData(double.MaxValue, "1.79769313486232E+308 m")] -#endif + #endif public void DefaultToStringFormatting(double value, string expected) { string actual = Length.FromMeters(value).ToString(AmericanCulture); Assert.Equal(expected, actual); } + [Theory] [InlineData("de-DE")] [InlineData("da-DK")] @@ -173,7 +174,7 @@ public void FeetInches_UseGroupingSeparator_ForCulture(string cultureName) { CultureInfo culture = CultureInfo.GetCultureInfo(cultureName); string gs = culture.NumberFormat.NumberGroupSeparator; - + // Feet/Inch and Stone/Pound combinations are only used (customarily) in the US, UK and maybe Ireland - all English speaking countries. // FeetInches returns a whole number of feet, with the remainder expressed (rounded) in inches. Same for StonePounds. Assert.Equal($"3{gs}333 st 7 lb", Mass.FromStonePounds(3333, 7).StonePounds.ToString(culture)); @@ -196,12 +197,12 @@ public void StonePounds_UseGroupingSeparator_ForCulture(string cultureName) { CultureInfo culture = CultureInfo.GetCultureInfo(cultureName); string gs = culture.NumberFormat.NumberGroupSeparator; - + // Feet/Inch and Stone/Pound combinations are only used (customarily) in the US, UK and maybe Ireland - all English speaking countries. // FeetInches returns a whole number of feet, with the remainder expressed (rounded) in inches. Same for StonePounds. Assert.Equal($"3{gs}333 st 7 lb", Mass.FromStonePounds(3333, 7).StonePounds.ToString(culture)); } - + // Due to rounding, the values will result in the same string representation regardless of the number of significant digits (up to a certain point) [Theory] [InlineData(-0.819999999999, "S", "-0.819999999999 m")] @@ -217,6 +218,7 @@ public void StonePounds_UseGroupingSeparator_ForCulture(string cultureName) [InlineData(0.00299999999, "s4", "0.003 m")] [InlineData(0.0003000001, "s2", "3e-04 m")] [InlineData(0.0003000001, "s4", "3e-04 m")] + [InlineData(0.0003000001, "S4", "3E-04 m")] public void ToString_SFormat_RoundsToSignificantDigitsAfterRadix(double value, string significantDigitsAfterRadixFormatString, string expected) { @@ -323,6 +325,5 @@ public void ToString_WithRussianCulture() Assert.Equal("1 Н·м", Torque.FromNewtonMeters(1).ToUnit(TorqueUnit.NewtonMeter).ToString(RussianCulture)); Assert.Equal("1 м³", Volume.FromCubicMeters(1).ToUnit(VolumeUnit.CubicMeter).ToString(RussianCulture)); } - } } diff --git a/UnitsNet.Tests/QuantityInfoTest.cs b/UnitsNet.Tests/QuantityInfoTest.cs index 623bea64c2..ac631076e0 100644 --- a/UnitsNet.Tests/QuantityInfoTest.cs +++ b/UnitsNet.Tests/QuantityInfoTest.cs @@ -16,7 +16,7 @@ public void Constructor_AssignsProperties() UnitDefinition[] expectedUnitInfos = [ new(LengthUnit.Centimeter, "Centimeters", new BaseUnits(LengthUnit.Centimeter)), - new(LengthUnit.Kilometer, "Kilometers", new BaseUnits(LengthUnit.Kilometer)) + new(LengthUnit.Kilometer, "Kilometers", new BaseUnits(LengthUnit.Kilometer), 100) ]; const LengthUnit expectedBaseUnit = LengthUnit.Centimeter; var expectedZero = Length.FromCentimeters(10); @@ -56,6 +56,8 @@ public void Constructor_AssignsProperties() Assert.Equal(expectedUnitInfos[0].Name, firstUnitInfo.Name); Assert.Equal(expectedUnitInfos[0].PluralName, firstUnitInfo.PluralName); Assert.Equal(expectedUnitInfos[0].BaseUnits, firstUnitInfo.BaseUnits); + Assert.Equal(expectedUnitInfos[0].ConversionFromBase, firstUnitInfo.ConversionFromBase); + Assert.Equal(expectedUnitInfos[0].ConversionToBase, firstUnitInfo.ConversionToBase); Assert.Equal(quantityInfo, firstUnitInfo.QuantityInfo); }, secondUnitInfo => { @@ -63,6 +65,8 @@ public void Constructor_AssignsProperties() Assert.Equal(expectedUnitInfos[1].Name, secondUnitInfo.Name); Assert.Equal(expectedUnitInfos[1].PluralName, secondUnitInfo.PluralName); Assert.Equal(expectedUnitInfos[1].BaseUnits, secondUnitInfo.BaseUnits); + Assert.Equal(expectedUnitInfos[1].ConversionFromBase, secondUnitInfo.ConversionFromBase); + Assert.Equal(expectedUnitInfos[1].ConversionToBase, secondUnitInfo.ConversionToBase); Assert.Equal(quantityInfo, secondUnitInfo.QuantityInfo); }); }, () => @@ -105,8 +109,8 @@ public void Constructor_AssignsPropertiesForCustomQuantity() UnitDefinition[] expectedUnitInfos = [ new(HowMuchUnit.Some, "Some", BaseUnits.Undefined), - new(HowMuchUnit.ATon, "Tons", BaseUnits.Undefined), - new(HowMuchUnit.AShitTon, "ShitTons", BaseUnits.Undefined) + new(HowMuchUnit.ATon, "Tons", BaseUnits.Undefined, new QuantityValue(1, 10)), + new(HowMuchUnit.AShitTon, "ShitTons", BaseUnits.Undefined, new QuantityValue(1, 100)) ]; const HowMuchUnit expectedBaseUnit = HowMuchUnit.Some; var expectedZero = new HowMuch(10, HowMuchUnit.Some); @@ -125,6 +129,8 @@ public void Constructor_AssignsPropertiesForCustomQuantity() Assert.Equal(expectedUnitInfos[0].Name, firstUnitInfo.Name); Assert.Equal(expectedUnitInfos[0].PluralName, firstUnitInfo.PluralName); Assert.Equal(expectedUnitInfos[0].BaseUnits, firstUnitInfo.BaseUnits); + Assert.Equal(expectedUnitInfos[0].ConversionFromBase, firstUnitInfo.ConversionFromBase); + Assert.Equal(expectedUnitInfos[0].ConversionToBase, firstUnitInfo.ConversionToBase); Assert.Equal(quantityInfo, firstUnitInfo.QuantityInfo); }, secondUnitInfo => { @@ -132,6 +138,8 @@ public void Constructor_AssignsPropertiesForCustomQuantity() Assert.Equal(expectedUnitInfos[1].Name, secondUnitInfo.Name); Assert.Equal(expectedUnitInfos[1].PluralName, secondUnitInfo.PluralName); Assert.Equal(expectedUnitInfos[1].BaseUnits, secondUnitInfo.BaseUnits); + Assert.Equal(expectedUnitInfos[1].ConversionFromBase, secondUnitInfo.ConversionFromBase); + Assert.Equal(expectedUnitInfos[1].ConversionToBase, secondUnitInfo.ConversionToBase); Assert.Equal(quantityInfo, secondUnitInfo.QuantityInfo); }, thirdUnitInfo => { @@ -139,6 +147,8 @@ public void Constructor_AssignsPropertiesForCustomQuantity() Assert.Equal(expectedUnitInfos[2].Name, thirdUnitInfo.Name); Assert.Equal(expectedUnitInfos[2].PluralName, thirdUnitInfo.PluralName); Assert.Equal(expectedUnitInfos[2].BaseUnits, thirdUnitInfo.BaseUnits); + Assert.Equal(expectedUnitInfos[2].ConversionFromBase, thirdUnitInfo.ConversionFromBase); + Assert.Equal(expectedUnitInfos[2].ConversionToBase, thirdUnitInfo.ConversionToBase); Assert.Equal(quantityInfo, thirdUnitInfo.QuantityInfo); }); Assert.Equal(expectedZero, quantityInfo.Zero); @@ -167,7 +177,9 @@ public void Constructor_WithoutZero_UsesZeroBaseUnit() expectedBaseUnit == unitInfo.Value && expectedUnitInfos[0].Name == unitInfo.Name && expectedUnitInfos[0].PluralName == unitInfo.PluralName && - expectedUnitInfos[0].BaseUnits == unitInfo.BaseUnits + expectedUnitInfos[0].BaseUnits == unitInfo.BaseUnits && + expectedUnitInfos[0].ConversionFromBase == unitInfo.ConversionFromBase && + expectedUnitInfos[0].ConversionToBase == unitInfo.ConversionToBase ); Assert.Equal(expectedBaseDimensions, quantityInfo.BaseDimensions); Assert.Null(quantityInfo.UnitAbbreviations); @@ -195,7 +207,9 @@ public void Constructor_WithoutName_UsesDefaultQuantityTypeName() expectedBaseUnit == firstUnitInfo.Value && expectedUnitInfos[0].Name == firstUnitInfo.Name && expectedUnitInfos[0].PluralName == firstUnitInfo.PluralName && - expectedUnitInfos[0].BaseUnits == firstUnitInfo.BaseUnits + expectedUnitInfos[0].BaseUnits == firstUnitInfo.BaseUnits && + expectedUnitInfos[0].ConversionFromBase == firstUnitInfo.ConversionFromBase && + expectedUnitInfos[0].ConversionToBase == firstUnitInfo.ConversionToBase ); Assert.Equal(expectedBaseDimensions, quantityInfo.BaseDimensions); Assert.Equal(abbreviations, quantityInfo.UnitAbbreviations); @@ -227,8 +241,8 @@ public void Constructor_GivenANullUnitInfo_ThrowsArgumentNullException() Assert.Throws(() => new QuantityInfo(nameof(Length), LengthUnit.Meter, collectionContainingANull, Length.BaseDimensions, Length.From)); #else - Assert.Throws(() => new QuantityInfo(nameof(Length), - LengthUnit.Meter, collectionContainingANull, Length.BaseDimensions, Length.From)); + Assert.Throws(() => new QuantityInfo(nameof(Length), + LengthUnit.Meter, collectionContainingANull, Length.BaseDimensions, Length.From)); #endif } @@ -611,7 +625,6 @@ public void ToString_ReturnsTheQuantityName() } #if NET - [Fact] public void Constructor_WithoutDelegate_UsesTheDefaultQuantityFrom() { @@ -634,7 +647,9 @@ public void Constructor_WithoutDelegate_UsesTheDefaultQuantityFrom() expectedBaseUnit == firstUnitInfo.Value && expectedUnitInfos[0].Name == firstUnitInfo.Name && expectedUnitInfos[0].PluralName == firstUnitInfo.PluralName && - expectedUnitInfos[0].BaseUnits == firstUnitInfo.BaseUnits + expectedUnitInfos[0].BaseUnits == firstUnitInfo.BaseUnits && + expectedUnitInfos[0].ConversionFromBase == firstUnitInfo.ConversionFromBase && + expectedUnitInfos[0].ConversionToBase == firstUnitInfo.ConversionToBase ); Assert.Equal(expectedBaseDimensions, quantityInfo.BaseDimensions); Assert.Equal(abbreviations, quantityInfo.UnitAbbreviations); @@ -661,7 +676,9 @@ public void Constructor_WithoutNameOrDelegate_UsesTheDefaultQuantityNameAndFrom( expectedBaseUnit == firstUnitInfo.Value && expectedUnitInfos[0].Name == firstUnitInfo.Name && expectedUnitInfos[0].PluralName == firstUnitInfo.PluralName && - expectedUnitInfos[0].BaseUnits == firstUnitInfo.BaseUnits + expectedUnitInfos[0].BaseUnits == firstUnitInfo.BaseUnits && + expectedUnitInfos[0].ConversionFromBase == firstUnitInfo.ConversionFromBase && + expectedUnitInfos[0].ConversionToBase == firstUnitInfo.ConversionToBase ); Assert.Equal(expectedBaseDimensions, quantityInfo.BaseDimensions); Assert.Equal(abbreviations, quantityInfo.UnitAbbreviations); diff --git a/UnitsNet.Tests/QuantityTest.cs b/UnitsNet.Tests/QuantityTest.cs index b074f9df99..9ddbfe74f2 100644 --- a/UnitsNet.Tests/QuantityTest.cs +++ b/UnitsNet.Tests/QuantityTest.cs @@ -38,7 +38,7 @@ public void TryFrom_GivenNullUnit_ReturnsFalse() Enum? nullUnit = null; Assert.False(Quantity.TryFrom(1, nullUnit, out IQuantity? _)); } - + [Fact] public void TryFrom_GivenUnknownUnitType_ReturnsFalse() { diff --git a/UnitsNet.Tests/QuantityTests.cs b/UnitsNet.Tests/QuantityTests.cs index c3ad83bd97..89685059e1 100644 --- a/UnitsNet.Tests/QuantityTests.cs +++ b/UnitsNet.Tests/QuantityTests.cs @@ -18,6 +18,80 @@ public void GetHashCodeForDifferentQuantitiesWithSameValuesAreNotEqual() Assert.NotEqual(length.GetHashCode(), area.GetHashCode()); } + // [Theory] + // [InlineData("10 m", "9.89 m" , "0.1 m", false)] // +/- 0.1m absolute tolerance and some additional margin tolerate rounding errors in test case. + // [InlineData("10 m", "9.91 m" , "0.1 m", true)] + // [InlineData("10 m", "10.09 m", "0.1 m", true)] + // [InlineData("10 m", "1009 cm", "0.1 m", true)] // Different unit, still equal. + // [InlineData("10 m", "10.11 m", "0.1 m", false)] + // [InlineData("10 m", "8.9 m" , "0.1 m", false)] // +/- 1m relative tolerance (10%) and some additional margin tolerate rounding errors in test case. + // public void Equals_IGenericEquatableQuantity(string q1String, string q2String, string toleranceString, bool expectedEqual) + // { + // // This interfaces implements .NET generic math interfaces. + // IQuantity q1 = ParseLength(q1String); + // IQuantity q2 = ParseLength(q2String); + // IQuantity tolerance = ParseLength(toleranceString); + // + // Assert.Equal(expectedEqual, q1.Equals(q2, tolerance)); + // } + // + // [Theory] + // [InlineData("10 m", "9.89 m" , "0.1 m", false)] // +/- 0.1m absolute tolerance and some additional margin tolerate rounding errors in test case. + // [InlineData("10 m", "9.91 m" , "0.1 m", true)] + // [InlineData("10 m", "10.09 m", "0.1 m", true)] + // [InlineData("10 m", "1009 cm", "0.1 m", true)] // Different unit, still equal. + // [InlineData("10 m", "10.11 m", "0.1 m", false)] + // [InlineData("10 m", "8.9 m" , "0.1 m", false)] // +/- 1m relative tolerance (10%) and some additional margin tolerate rounding errors in test case. + // public void Equals_IQuantity(string q1String, string q2String, string toleranceString, bool expectedEqual) + // { + // IQuantity q1 = ParseLength(q1String); + // IQuantity q2 = ParseLength(q2String); + // IQuantity tolerance = ParseLength(toleranceString); + // + // Assert.NotEqual(q1, q2); // Strict equality should not be equal. + // Assert.Equal(expectedEqual, q1.Equals(q2, tolerance)); + // } + // + // [Fact] + // public void Equals_IQuantity_OtherIsNull_ReturnsFalse() + // { + // IQuantity q1 = ParseLength("10 m"); + // IQuantity? q2 = null; + // IQuantity tolerance = ParseLength("0.1 m"); + // + // Assert.False(q1.Equals(q2, tolerance)); + // } + // + // [Fact] + // public void Equals_IQuantity_OtherIsDifferentType_ReturnsFalse() + // { + // IQuantity q1 = ParseLength("10 m"); + // IQuantity q2 = Mass.FromKilograms(10); + // IQuantity tolerance = Mass.FromKilograms(0.1); + // + // Assert.False(q1.Equals(q2, tolerance)); + // } + // + // [Fact] + // public void Equals_IQuantity_ToleranceIsDifferentType_Throws() + // { + // IQuantity q1 = ParseLength("10 m"); + // IQuantity q2 = ParseLength("10 m"); + // IQuantity tolerance = Mass.FromKilograms(0.1); + // + // Assert.Throws(() => q1.Equals(q2, tolerance)); + // } + // + // [Fact] + // public void Equals_GenericEquatableIQuantity_OtherIsNull_ReturnsFalse() + // { + // IQuantity q1 = ParseLength("10 m"); + // IQuantity? q2 = null; + // IQuantity tolerance = ParseLength("0.1 m"); + // + // Assert.False(q1.Equals(q2, tolerance)); + // } + [Fact] public void TryFrom_ValidQuantityNameAndUnitName_ReturnsTrueAndQuantity() { @@ -160,10 +234,5 @@ public void AllowSpecialValue() Assert.Fail("Special double values (NaN, -Inf, +Inf) must be allowed."); } } - - private static Length ParseLength(string str) - { - return Length.Parse(str, CultureInfo.InvariantCulture); - } } } diff --git a/UnitsNet.Tests/Serialization/Json/DefaultDataContractJsonSerializerTests.cs b/UnitsNet.Tests/Serialization/Json/DefaultDataContractJsonSerializerTests.cs index 3f4eaaea1e..73efb965d4 100644 --- a/UnitsNet.Tests/Serialization/Json/DefaultDataContractJsonSerializerTests.cs +++ b/UnitsNet.Tests/Serialization/Json/DefaultDataContractJsonSerializerTests.cs @@ -1,13 +1,10 @@ -using System; -using System.Globalization; -using System.IO; -using System.Runtime.Serialization; +using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using UnitsNet.Units; -using Xunit; namespace UnitsNet.Tests.Serialization.Json { + /// /// These tests demonstrate the default behavior of the DataContractJsonSerializer when dealing with quantities /// @@ -21,7 +18,7 @@ public class DefaultDataContractJsonSerializerTests : SerializationTestsBase(string xml) + protected override T DeserializeObject(string json) { var serializer = new DataContractJsonSerializer(typeof(T)); using var stream = new MemoryStream(); using var writer = new StreamWriter(stream); - writer.Write(xml); + writer.Write(json); writer.Flush(); stream.Position = 0; return (T)(serializer.ReadObject(stream) ?? throw new InvalidOperationException("Read 'null' from stream.")); @@ -43,11 +40,11 @@ protected override T DeserializeObject(string xml) #region Serialization tests [Fact] - public void DoubleQuantity_SerializedWithDoubleValueAndunitInt() + public void Quantity_SerializedWithNumeratorAndDenominatorValueAndIntegerUnit() { var quantity = new Mass(1.20, MassUnit.Milligram); var unitInt = (int)quantity.Unit; - var expectedJson = $"{{\"Value\":1.2,\"Unit\":{unitInt}}}"; + var expectedJson = $$$"""{"Value":{"N":{"_bits":null,"_sign":12},"D":{"_bits":null,"_sign":10}},"Unit":{{{unitInt}}}}"""; var json = SerializeObject(quantity); @@ -59,11 +56,11 @@ public void DoubleQuantity_SerializedWithDoubleValueAndunitInt() #region Deserialization tests [Fact] - public void DoubleQuantity_DeserializedFromDoubleValueAndunitInt() + public void Quantity_DeserializedFromValueAndIntegerUnit() { var expectedUnit = MassUnit.Milligram; var unitInt = (int)expectedUnit; - var json = $"{{\"Value\":1.2,\"Unit\":{unitInt}}}"; + var json = $$$"""{"Value":{"N":{"_bits":null,"_sign":12},"D":{"_bits":null,"_sign":10}},"Unit":{{{unitInt}}}}"""; var quantity = DeserializeObject(json); @@ -72,20 +69,7 @@ public void DoubleQuantity_DeserializedFromDoubleValueAndunitInt() } [Fact] - public void DoubleQuantity_DeserializedFromQuotedDoubleValueAndunitInt() - { - var expectedUnit = MassUnit.Milligram; - var unitInt = (int)expectedUnit; - var json = $"{{\"Value\":\"1.2\",\"Unit\":{unitInt}}}"; - - var quantity = DeserializeObject(json); - - Assert.Equal(1.2, quantity.Value); - Assert.Equal(expectedUnit, quantity.Unit); - } - - [Fact] - public void DoubleZeroQuantity_DeserializedFromunitIntAndNoValue() + public void ZeroQuantity_DeserializedFromIntegerUnitAndNoValue() { var expectedUnit = MassUnit.Milligram; var unitInt = (int)expectedUnit; @@ -103,7 +87,7 @@ public void InterfaceObject_IncludesTypeInformation() var unit = InformationUnit.Exabyte; var unitInt = (int)unit; var testObject = new TestInterfaceObject { Quantity = new Information(1.2, unit) }; - var expectedJson = $"{{\"Quantity\":{{\"__type\":\"Information:#UnitsNet\",\"Value\":1.2,\"Unit\":{unitInt}}}}}"; + var expectedJson = $$$"""{"Quantity":{"__type":"Information:#UnitsNet","Value":{"N":{"_bits":null,"_sign":12},"D":{"_bits":null,"_sign":10}},"Unit":{{{unitInt}}}}}"""; var json = SerializeObject(testObject); @@ -111,9 +95,9 @@ public void InterfaceObject_IncludesTypeInformation() } [Fact] - public void DoubleBaseUnitQuantity_DeserializedFromValueAndNoUnit() + public void BaseUnitQuantity_DeserializedFromValueAndNoUnit() { - var json = "{\"Value\":1.2}"; + var json = """{"Value":{"N":{"_bits":null,"_sign":12},"D":{"_bits":null,"_sign":10}}"""; var quantity = DeserializeObject(json); @@ -122,30 +106,11 @@ public void DoubleBaseUnitQuantity_DeserializedFromValueAndNoUnit() } [Fact] - public void DoubleZeroBaseQuantity_DeserializedFromEmptyInput() - { - var json = "{}"; - - var quantity = DeserializeObject(json); - - Assert.Equal(0, quantity.Value); - Assert.Equal(Mass.BaseUnit, quantity.Unit); - } - - [Fact] - public void InterfaceObject_WithMissingKnownTypeInformation_ThrowsSerializationException() - { - var testObject = new TestInterfaceObject { Quantity = new Volume(1.2, VolumeUnit.Microliter) }; - - Assert.Throws(() => SerializeObject(testObject)); - } - - [Fact] - public void DecimalZeroQuantity_DeserializedFromUnitIntAndNoValue() + public void ZeroQuantity_DeserializedFromUnitIntAndNoValue() { var expectedUnit = InformationUnit.Exabyte; var unitInt = (int)expectedUnit; - var json = $"{{\"Unit\":{unitInt}}}"; + var json = $$"""{"Unit":{{unitInt}}}"""; var quantity = DeserializeObject(json); @@ -154,14 +119,22 @@ public void DecimalZeroQuantity_DeserializedFromUnitIntAndNoValue() } [Fact] - public void DecimalZeroBaseQuantity_DeserializedFromEmptyInput() + public void ZeroBaseQuantity_DeserializedFromEmptyInput() { var json = "{}"; - var quantity = DeserializeObject(json); + var quantity = DeserializeObject(json); Assert.Equal(0, quantity.Value); - Assert.Equal(Information.BaseUnit, quantity.Unit); + Assert.Equal(Mass.BaseUnit, quantity.Unit); + } + + [Fact] + public void InterfaceObject_WithMissingKnownTypeInformation_ThrowsSerializationException() + { + var testObject = new TestInterfaceObject { Quantity = new Volume(1.2, VolumeUnit.Microliter) }; + + Assert.Throws(() => SerializeObject(testObject)); } #endregion diff --git a/UnitsNet.Tests/Serialization/Json/DefaultDataContractJsonSerializerWithSurrogateProviderTests.cs b/UnitsNet.Tests/Serialization/Json/DefaultDataContractJsonSerializerWithSurrogateProviderTests.cs new file mode 100644 index 0000000000..68e1c9240c --- /dev/null +++ b/UnitsNet.Tests/Serialization/Json/DefaultDataContractJsonSerializerWithSurrogateProviderTests.cs @@ -0,0 +1,177 @@ +// 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.Runtime.Serialization; +using System.Runtime.Serialization.Json; +using UnitsNet.Serialization; +using UnitsNet.Units; + +namespace UnitsNet.Tests.Serialization.Json; + +/// +/// These tests demonstrate the default behavior of the DataContractJsonSerializer when dealing with quantities +/// +/// Note that the produced schema is different from the one generated using the UnitsNet.Json package +/// +/// The default schema can easily be modified using a converter, a.k.a. DataContractSurrogate (.NET Framework) +/// +/// +/// +#pragma warning disable xUnit1000 +// these tests no longer pass due to the surrogate provider not being passed downstream: +// https://github.com/dotnet/runtime/issues/100553 +internal class DefaultDataContractJsonSerializerWithSurrogateProviderTests : SerializationTestsBase +#pragma warning restore xUnit1000 +{ + // I tried using the IXmlSerializable interface but that is also broken: the contract generation with the svcutil seems to only work with .NET Framework + // https://github.com/dotnet/wcf/issues/5638 + // anyway, this is how the DataContractJsonSerializer formats an IXmlSerializable... + private const string OnePointTwoJson = + """ + "12<\/N>10<\/D><\/QuantityValue>" + """; + + protected override string SerializeObject(object obj) + { + var serializer = new DataContractJsonSerializer(obj.GetType(), new DataContractJsonSerializerSettings(){SerializeReadOnlyTypes = true}); +#if NET + serializer.SetSerializationSurrogateProvider(QuantityValueSurrogateSerializationProvider.Instance); // this doesn't work as expected because of https://github.com/dotnet/runtime/issues/100553 +#else + // TODO in case the linked issue is fixed, we could consider providing the old surrogate types (netstandard doesn't support the same interface) +#endif + using var stream = new MemoryStream(); + serializer.WriteObject(stream, obj); + stream.Position = 0; + using var streamReader = new StreamReader(stream); + return streamReader.ReadToEnd(); + } + + protected override T DeserializeObject(string json) + { + var serializer = new DataContractJsonSerializer(typeof(T)); +#if NET + serializer.SetSerializationSurrogateProvider(QuantityValueSurrogateSerializationProvider.Instance); // this doesn't work as expected because of https://github.com/dotnet/runtime/issues/100553 +#else + // TODO in case the linked issue is fixed, we could consider providing the old surrogate types (netstandard doesn't support the same interface) +#endif + using var stream = new MemoryStream(); + using var writer = new StreamWriter(stream); + writer.Write(json); + writer.Flush(); + stream.Position = 0; + return (T)(serializer.ReadObject(stream) ?? throw new InvalidOperationException("Read 'null' from stream.")); + } + + #region Serialization tests + + [Fact] + public void DoubleQuantity_SerializedWithDoubleValueAndunitInt() + { + var quantity = new Mass(1.20, MassUnit.Milligram); + var unitInt = (int)quantity.Unit; + var expectedJson = $$"""{"Value":"QuantityValue":{"N":"12","D":10"},"Unit":{{unitInt}}}"""; + + var json = SerializeObject(quantity); + + Assert.Equal(expectedJson, json); + } + + #endregion + + #region Deserialization tests + + [Fact] + public void DoubleQuantity_DeserializedFromXmlValueAndIntegerUnit() + { + var expectedUnit = MassUnit.Milligram; + var unitInt = (int)expectedUnit; + var json = $$"""{"Value":"QuantityValue":{"N":"12","D":10"},"Unit":{{unitInt}}}"""; + + var quantity = DeserializeObject(json); + + Assert.Equal(1.2, quantity.Value); + Assert.Equal(expectedUnit, quantity.Unit); + } + + [Fact] + public void DoubleZeroQuantity_DeserializedFromIntegerUnitAndNoValue() + { + var expectedUnit = MassUnit.Milligram; + var unitInt = (int)expectedUnit; + var json = $"{{\"Unit\":{unitInt}}}"; + + var quantity = DeserializeObject(json); + + Assert.Equal(0, quantity.Value); + Assert.Equal(expectedUnit, quantity.Unit); + } + + [Fact] + public void InterfaceObject_IncludesTypeInformation() + { + var unit = InformationUnit.Exabyte; + var unitInt = (int)unit; + var testObject = new TestInterfaceObject { Quantity = new Information(1.2, unit) }; + var expectedJson = $$$"""{"Quantity":{"__type":"Information:#UnitsNet","Value":"QuantityValue":{"N":"12","D":10"},"Unit":{{{unitInt}}}}}"""; + + var json = SerializeObject(testObject); + + Assert.Equal(expectedJson, json); + } + + [Fact] + public void DoubleBaseUnitQuantity_DeserializedFromXmlValueAndNoUnit() + { + var json = """{"Value":"QuantityValue":{"N":"12","D":10"}"""; + + var quantity = DeserializeObject(json); + + Assert.Equal(1.2, quantity.Value); + Assert.Equal(Mass.BaseUnit, quantity.Unit); + } + + [Fact] + public void DoubleZeroBaseQuantity_DeserializedFromEmptyInput() + { + var json = "{}"; + + var quantity = DeserializeObject(json); + + Assert.Equal(0, quantity.Value); + Assert.Equal(Mass.BaseUnit, quantity.Unit); + } + + [Fact] + public void InterfaceObject_WithMissingKnownTypeInformation_ThrowsSerializationException() + { + var testObject = new TestInterfaceObject { Quantity = new Volume(1.2, VolumeUnit.Microliter) }; + + Assert.Throws(() => SerializeObject(testObject)); + } + + [Fact] + public void DecimalZeroQuantity_DeserializedFromUnitIntAndNoValue() + { + var expectedUnit = InformationUnit.Exabyte; + var unitInt = (int)expectedUnit; + var json = $$"""{"Unit":{{unitInt}}}"""; + + var quantity = DeserializeObject(json); + + Assert.Equal(0, quantity.Value); + Assert.Equal(expectedUnit, quantity.Unit); + } + + [Fact] + public void DecimalZeroBaseQuantity_DeserializedFromEmptyInput() + { + var json = "{}"; + + var quantity = DeserializeObject(json); + + Assert.Equal(0, quantity.Value); + Assert.Equal(Information.BaseUnit, quantity.Unit); + } + + #endregion +} diff --git a/UnitsNet.Tests/Serialization/SerializationTestsBase.cs b/UnitsNet.Tests/Serialization/SerializationTestsBase.cs index 4a8e99e772..75eedcbb39 100644 --- a/UnitsNet.Tests/Serialization/SerializationTestsBase.cs +++ b/UnitsNet.Tests/Serialization/SerializationTestsBase.cs @@ -31,6 +31,8 @@ public abstract class SerializationTestsBase [InlineData(1.0)] [InlineData(0)] [InlineData(-1.0)] + [InlineData(1.2)] + [InlineData(-1.2)] [InlineData(1E+36)] [InlineData(1E-36)] [InlineData(-1E+36)] diff --git a/UnitsNet.Tests/Serialization/Xml/DataContractSerializerTests.cs b/UnitsNet.Tests/Serialization/Xml/DataContractSerializerTests.cs index f37b32293c..1b6185c9f4 100644 --- a/UnitsNet.Tests/Serialization/Xml/DataContractSerializerTests.cs +++ b/UnitsNet.Tests/Serialization/Xml/DataContractSerializerTests.cs @@ -1,8 +1,5 @@ -using System; -using System.IO; -using System.Runtime.Serialization; +using System.Runtime.Serialization; using UnitsNet.Units; -using Xunit; namespace UnitsNet.Tests.Serialization.Xml { @@ -14,6 +11,8 @@ public class DataContractSerializerTests : SerializationTestsBase { private const string XmlSchema = "xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\""; private const string Namespace = "xmlns=\"http://schemas.datacontract.org/2004/07/UnitsNet\""; + private const string NumericsNamespace = "\"http://schemas.datacontract.org/2004/07/System.Numerics\""; + private const string ArraysNamespace = "\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\""; protected override string SerializeObject(object obj) { @@ -37,10 +36,47 @@ protected override T DeserializeObject(string xml) } [Fact] - public void DoubleQuantity_SerializedWithValueAndMemberName() + public void Quantity_SerializedWithValueAndMemberName() { var quantity = new Mass(1.20, MassUnit.Milligram); - var expectedXml = $"1.2Milligram"; + var numeratorFormat = $"12"; + var denominatorFormat = $"10"; + var expectedXml = $"{numeratorFormat}{denominatorFormat}Milligram"; + + var xml = SerializeObject(quantity); + + Assert.Equal(expectedXml, xml); + } + + [Fact] + public void IntegerQuantity_SerializedWithBothNumeratorAndDenominatorValueAndMemberName() + { + var quantity = new Mass(42, MassUnit.Milligram); + var numeratorFormat = $"42"; + var denominatorFormat = $"1"; + var expectedXml = $"{numeratorFormat}{denominatorFormat}Milligram"; + + var xml = SerializeObject(quantity); + + Assert.Equal(expectedXml, xml); + } + + [Fact] + public void ZeroQuantity_WithNonBaseUnit_SerializedMemberNameAndNoValue() + { + var quantity = new Mass(0, MassUnit.Milligram); + var expectedXml = $"Milligram"; + + var xml = SerializeObject(quantity); + + Assert.Equal(expectedXml, xml); + } + + [Fact] + public void DefaultQuantity_SerializedWithoutAnyFields() + { + var quantity = default(Mass); + var expectedXml = $""; var xml = SerializeObject(quantity); @@ -53,7 +89,11 @@ public void InterfaceObject_IncludesTypeInformation() var testObject = new TestInterfaceObject { Quantity = new Information(1.20, InformationUnit.Exabyte) }; var quantityNamespace = "xmlns:a=\"http://schemas.datacontract.org/2004/07/UnitsNet\""; // there is an extra 'a' compared to Namespace - var expectedQuantityXml = $"1.2Exabyte"; + + var numeratorFormat = "12"; + var denominatorFormat = "10"; + + var expectedQuantityXml = $"{numeratorFormat}{denominatorFormat}Exabyte"; var expectedXml = $"{expectedQuantityXml}"; var xml = SerializeObject(testObject); diff --git a/UnitsNet.Tests/Serialization/Xml/DataContractSerializerWithSurrogateProviderTests.cs b/UnitsNet.Tests/Serialization/Xml/DataContractSerializerWithSurrogateProviderTests.cs new file mode 100644 index 0000000000..010a45b91f --- /dev/null +++ b/UnitsNet.Tests/Serialization/Xml/DataContractSerializerWithSurrogateProviderTests.cs @@ -0,0 +1,108 @@ +// 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.Runtime.Serialization; +using UnitsNet.Serialization; +using UnitsNet.Units; + +namespace UnitsNet.Tests.Serialization.Xml; + +/// +/// These tests demonstrate the behavior of the DataContractSerializer (the default WCF serializer) + QuantityValueSurrogateSerializationProvider, when dealing with +/// quantities. +/// +/// Unlike the default serializer, here we store the BigInteger types as strings instead of "sign + bytes." +public class DataContractSerializerWithSurrogateProviderTests : SerializationTestsBase +{ + private const string XmlSchema = "xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\""; + private const string Namespace = "xmlns=\"http://schemas.datacontract.org/2004/07/UnitsNet\""; + + protected override string SerializeObject(object obj) + { + var serializer = new DataContractSerializer(obj.GetType()); + serializer.SetSerializationSurrogateProvider(QuantityValueSurrogateSerializationProvider.Instance); + using var stream = new MemoryStream(); + serializer.WriteObject(stream, obj); + stream.Position = 0; + using var streamReader = new StreamReader(stream); + return streamReader.ReadToEnd(); + } + + protected override T DeserializeObject(string xml) + { + var serializer = new DataContractSerializer(typeof(T)); + serializer.SetSerializationSurrogateProvider(QuantityValueSurrogateSerializationProvider.Instance); + using var stream = new MemoryStream(); + using var writer = new StreamWriter(stream); + writer.Write(xml); + writer.Flush(); + stream.Position = 0; + return (T)(serializer.ReadObject(stream) ?? throw new InvalidOperationException("Read 'null' from stream.")); + } + + [Fact] + public void DoubleQuantity_SerializedWithValueAndMemberName() + { + var quantity = new Mass(1.20, MassUnit.Milligram); + var expectedXml = $"1210Milligram"; + + var xml = SerializeObject(quantity); + + Assert.Equal(expectedXml, xml); + } + + [Fact] + public void IntegerQuantity_SerializedWithNumeratorOnlyValueAndMemberName() + { + var quantity = new Mass(42, MassUnit.Milligram); + var expectedXml = $"42Milligram"; + + var xml = SerializeObject(quantity); + + Assert.Equal(expectedXml, xml); + } + + [Fact] + public void ZeroQuantity_WithNonBaseUnit_SerializedMemberNameAndNoValue() + { + var quantity = new Mass(0, MassUnit.Milligram); + var expectedXml = $"Milligram"; + + var xml = SerializeObject(quantity); + + Assert.Equal(expectedXml, xml); + } + + [Fact] + public void DefaultQuantity_SerializedWithoutAnyFields() + { + var quantity = default(Mass); + var expectedXml = $""; + + var xml = SerializeObject(quantity); + + Assert.Equal(expectedXml, xml); + } + + [Fact] + public void InterfaceObject_IncludesTypeInformation() + { + var testObject = new TestInterfaceObject { Quantity = new Information(1.20, InformationUnit.Exabyte) }; + + var quantityNamespace = "xmlns:a=\"http://schemas.datacontract.org/2004/07/UnitsNet\""; // there is an extra 'a' compared to Namespace + var expectedQuantityXml = $"1210Exabyte"; + var expectedXml = $"{expectedQuantityXml}"; + + var xml = SerializeObject(testObject); + + Assert.Equal(expectedXml, xml); + } + + [Fact] + public void InterfaceObject_WithMissingKnownTypeInformation_ThrowsSerializationException() + { + var testObject = new TestInterfaceObject { Quantity = new Volume(1.2, VolumeUnit.Microliter) }; + + Assert.Throws(() => SerializeObject(testObject)); + } +} diff --git a/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs b/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs index d029208eb4..8d19c7739b 100644 --- a/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs +++ b/UnitsNet.Tests/UnitAbbreviationsCacheTests.cs @@ -48,6 +48,29 @@ public void CreateDefault_ReturnsAnAbbreviationCacheWithDefaultQuantityInfoLooku Assert.Equal("g", unitAbbreviationCache.GetUnitAbbreviations(MassUnit.Gram, AmericanCulture)[0]); Assert.Throws(() => unitAbbreviationCache.GetUnitAbbreviations(HowMuchUnit.Some)); } + + [Fact] + public void CreateDefault_WithConfigureAction_ReturnsAnAbbreviationCacheWithNewQuantityInfoLookup() + { + var unitAbbreviationCache = UnitAbbreviationsCache.CreateDefault(configuration => configuration.WithAdditionalQuantities([HowMuch.Info])); + + Assert.NotEqual(UnitsNetSetup.Default.Quantities, unitAbbreviationCache.Quantities); + Assert.Equal("g", unitAbbreviationCache.GetUnitAbbreviations(MassUnit.Gram, AmericanCulture)[0]); + Assert.Empty(unitAbbreviationCache.GetUnitAbbreviations(HowMuchUnit.Some, AmericanCulture)); + } + + [Fact] + public void Create_WithQuantitiesAndConfigureAction_ReturnsAnAbbreviationCacheWithNewQuantityInfoLookup() + { + var unitAbbreviationCache = UnitAbbreviationsCache.Create([Mass.Info, HowMuch.Info], + configuration => + configuration.Configure(() => Mass.MassInfo.CreateDefault(mappings => mappings.SelectUnits(MassUnit.Kilogram, MassUnit.Gram)))); + + Assert.NotEqual(UnitsNetSetup.Default.Quantities, unitAbbreviationCache.Quantities); + Assert.Equal("g", unitAbbreviationCache.GetUnitAbbreviations(MassUnit.Gram, AmericanCulture)[0]); + Assert.Empty(unitAbbreviationCache.GetUnitAbbreviations(HowMuchUnit.Some, AmericanCulture)); + Assert.Throws(() => unitAbbreviationCache.GetUnitAbbreviations(MassUnit.EarthMass)); + } [Fact] public void UnitAbbreviationsCache_Default_ReturnsInstanceFromUnitsNetSetup() diff --git a/UnitsNet.Tests/UnitConversionsBuilderExtensionsTests.cs b/UnitsNet.Tests/UnitConversionsBuilderExtensionsTests.cs new file mode 100644 index 0000000000..e6d24c26d7 --- /dev/null +++ b/UnitsNet.Tests/UnitConversionsBuilderExtensionsTests.cs @@ -0,0 +1,464 @@ +// 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 System.Collections.Generic; +using System.Linq; +using System.Numerics; +using Xunit; + +namespace UnitsNet.Tests; + +public class UnitConversionsBuilderExtensionsTests +{ + [Theory] + [InlineData(true)] + [InlineData(false)] + public void NoCaching_ReturnsNoConversions(bool reduceConstants) + { + var quantities = new QuantityInfo[] { Mass.Info, Volume.Info }; + Assert.Empty(quantities.GetUnitConversionFunctions(ConversionCachingMode.None, reduceConstants)); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void BaseOnlyCaching_ReturnsBaseUnitConversions(bool reduceConstants) + { + var quantities = new QuantityInfo[] { Mass.Info, Volume.Info }; + // 2 * (27 - 1) (Mass) + 2 * (54 - 1) (Volume) = 52 + 106 = 158 conversions (the Volume has the 3rd hightest number of units: (VolumeFlow, 75), (Density, 56)) + // Quantity.Infos.Sum(info => 2 * (info.UnitInfos.Count - 1)) => 2880 + var expectedNumberOfConversions = quantities.Sum(info => 2 * (info.UnitInfos.Count - 1)); + + var unitConversions = quantities.GetUnitConversionFunctions(ConversionCachingMode.BaseOnly, reduceConstants) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.Multiple(() => Assert.Equal(expectedNumberOfConversions, unitConversions.Count), () => + { + Assert.All(quantities, quantity => + { + UnitInfo baseUnit = quantity.BaseUnitInfo; + Assert.All(quantity.UnitInfos, fromUnit => + { + Assert.All(quantity.UnitInfos, toUnit => + { + var conversionKey = UnitConversionKey.Create(fromUnit.UnitKey, toUnit.UnitKey); + if ((fromUnit == baseUnit || toUnit == baseUnit) && fromUnit != toUnit) + { + QuantityValue valueToConvert = 123.45m; + QuantityValue expectedValue = toUnit.GetValueFrom(valueToConvert, fromUnit); + Assert.Contains(conversionKey, unitConversions); + Assert.Equal(expectedValue, unitConversions[conversionKey](valueToConvert)); + } + else + { + Assert.DoesNotContain(conversionKey, unitConversions); + } + }); + }); + }); + }); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AllCaching_ReturnsAllUnitConversions(bool reduceConstants) + { + var quantities = new QuantityInfo[] { Mass.Info, Volume.Info }; + // 27 * 26 (Mass) + 54 * 53 (Volume) = 702 + 2862 = 3564 conversions (the Volume has the 3rd hightest number of units: (VolumeFlow, 75), (Density, 56)) + // Quantity.Infos.Sum(info => info.UnitInfos.Count * (info.UnitInfos.Count - 1)) => 40114 + var expectedNumberOfConversions = quantities.Sum(info => info.UnitInfos.Count * (info.UnitInfos.Count - 1)); + + var unitConversions = quantities.GetUnitConversionFunctions(ConversionCachingMode.All, reduceConstants) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.Multiple(() => Assert.Equal(expectedNumberOfConversions, unitConversions.Count), () => + { + Assert.All(quantities, quantity => + { + Assert.All(quantity.UnitInfos, fromUnit => + { + Assert.All(quantity.UnitInfos, toUnit => + { + var conversionKey = UnitConversionKey.Create(fromUnit.UnitKey, toUnit.UnitKey); + if (fromUnit != toUnit) + { + QuantityValue valueToConvert = 123.45m; + QuantityValue expectedValue = toUnit.GetValueFrom(valueToConvert, fromUnit); + Assert.Contains(conversionKey, unitConversions); + Assert.Equal(expectedValue, unitConversions[conversionKey](valueToConvert)); + } + else + { + Assert.DoesNotContain(conversionKey, unitConversions); + } + }); + }); + }); + }); + } + + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(false, false)] + public void AllCaching_WithSpecificNoneOptions_ReturnsSpecifiedUnitConversions(bool defaultConstantsReduction, + bool volumeConstantsReduction) + { + var quantities = new QuantityInfo[] { Mass.Info, Volume.Info }; + var expectedNumberOfConversions = Mass.Info.UnitInfos.Count * (Mass.Info.UnitInfos.Count - 1); + var customQuantityOptions = new Dictionary { [typeof(Volume)] = new(ConversionCachingMode.None, volumeConstantsReduction) }; + + var unitConversions = quantities.GetUnitConversionFunctions(ConversionCachingMode.All, defaultConstantsReduction, customQuantityOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.Multiple(() => Assert.Equal(expectedNumberOfConversions, unitConversions.Count), + () => + { + Assert.All(Mass.Info.UnitInfos, fromUnit => + { + Assert.All(Mass.Info.UnitInfos, toUnit => + { + var conversionKey = UnitConversionKey.Create(fromUnit.UnitKey, toUnit.UnitKey); + if (fromUnit != toUnit) + { + QuantityValue valueToConvert = 123.45m; + QuantityValue expectedValue = toUnit.GetValueFrom(valueToConvert, fromUnit); + Assert.Contains(conversionKey, unitConversions); + Assert.Equal(expectedValue, unitConversions[conversionKey](valueToConvert)); + } + else + { + Assert.DoesNotContain(conversionKey, unitConversions); + } + }); + }); + }, + () => + { + Assert.All(Volume.Info.UnitInfos, + fromUnit => + { + Assert.All(Volume.Info.UnitInfos, + toUnit => { Assert.DoesNotContain(UnitConversionKey.Create(fromUnit.UnitKey, toUnit.UnitKey), unitConversions); }); + }); + }); + } + + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(false, false)] + public void AllCaching_WithSpecificBaseOnlyOptions_ReturnsSpecifiedUnitConversions(bool defaultConstantsReduction, + bool volumeConstantsReduction) + { + var quantities = new QuantityInfo[] { Mass.Info, Volume.Info }; + var expectedNumberOfConversions = Mass.Info.UnitInfos.Count * (Mass.Info.UnitInfos.Count - 1) + 2 * (Volume.Info.UnitInfos.Count - 1); + var customQuantityOptions = new Dictionary { [typeof(Volume)] = new(ConversionCachingMode.BaseOnly, volumeConstantsReduction) }; + + var unitConversions = quantities.GetUnitConversionFunctions(ConversionCachingMode.All, defaultConstantsReduction, customQuantityOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.Multiple(() => Assert.Equal(expectedNumberOfConversions, unitConversions.Count), + () => + { + Assert.All(Mass.Info.UnitInfos, fromUnit => + { + Assert.All(Mass.Info.UnitInfos, toUnit => + { + var conversionKey = UnitConversionKey.Create(fromUnit.UnitKey, toUnit.UnitKey); + if (fromUnit != toUnit) + { + QuantityValue valueToConvert = 123.45m; + QuantityValue expectedValue = toUnit.GetValueFrom(valueToConvert, fromUnit); + Assert.Contains(conversionKey, unitConversions); + Assert.Equal(expectedValue, unitConversions[conversionKey](valueToConvert)); + } + else + { + Assert.DoesNotContain(conversionKey, unitConversions); + } + }); + }); + }, + () => + { + Assert.All(Volume.Info.UnitInfos, fromUnit => + { + UnitInfo baseUnit = Volume.Info.BaseUnitInfo; + Assert.All(Volume.Info.UnitInfos, toUnit => + { + var conversionKey = UnitConversionKey.Create(fromUnit.UnitKey, toUnit.UnitKey); + if ((fromUnit == baseUnit || toUnit == baseUnit) && fromUnit != toUnit) + { + QuantityValue valueToConvert = 123.45m; + QuantityValue expectedValue = toUnit.GetValueFrom(valueToConvert, fromUnit); + Assert.Contains(conversionKey, unitConversions); + Assert.Equal(expectedValue, unitConversions[conversionKey](valueToConvert)); + } + else + { + Assert.DoesNotContain(conversionKey, unitConversions); + } + }); + }); + }); + } + + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(false, false)] + public void BaseOnlyCaching_WithSpecificAllOptions_ReturnsSpecifiedUnitConversions(bool defaultConstantsReduction, + bool volumeConstantsReduction) + { + var quantities = new QuantityInfo[] { Mass.Info, Volume.Info }; + var expectedNumberOfConversions = Mass.Info.UnitInfos.Count * (Mass.Info.UnitInfos.Count - 1) + 2 * (Volume.Info.UnitInfos.Count - 1); + var customQuantityOptions = new Dictionary { [typeof(Mass)] = new(ConversionCachingMode.All, volumeConstantsReduction) }; + + var unitConversions = quantities.GetUnitConversionFunctions(ConversionCachingMode.BaseOnly, defaultConstantsReduction, customQuantityOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.Multiple(() => Assert.Equal(expectedNumberOfConversions, unitConversions.Count), + () => + { + Assert.All(Mass.Info.UnitInfos, fromUnit => + { + Assert.All(Mass.Info.UnitInfos, toUnit => + { + var conversionKey = UnitConversionKey.Create(fromUnit.UnitKey, toUnit.UnitKey); + if (fromUnit != toUnit) + { + QuantityValue valueToConvert = 123.45m; + QuantityValue expectedValue = toUnit.GetValueFrom(valueToConvert, fromUnit); + Assert.Contains(conversionKey, unitConversions); + Assert.Equal(expectedValue, unitConversions[conversionKey](valueToConvert)); + } + else + { + Assert.DoesNotContain(conversionKey, unitConversions); + } + }); + }); + }, () => + { + Assert.All(Volume.Info.UnitInfos, fromUnit => + { + UnitInfo baseUnit = Volume.Info.BaseUnitInfo; + Assert.All(Volume.Info.UnitInfos, toUnit => + { + var conversionKey = UnitConversionKey.Create(fromUnit.UnitKey, toUnit.UnitKey); + if ((fromUnit == baseUnit || toUnit == baseUnit) && fromUnit != toUnit) + { + QuantityValue valueToConvert = 123.45m; + QuantityValue expectedValue = toUnit.GetValueFrom(valueToConvert, fromUnit); + Assert.Contains(conversionKey, unitConversions); + Assert.Equal(expectedValue, unitConversions[conversionKey](valueToConvert)); + } + else + { + Assert.DoesNotContain(conversionKey, unitConversions); + } + }); + }); + }); + } + + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(false, false)] + public void BaseOnlyCaching_WithSpecificNoneOptions_ReturnsSpecifiedUnitConversions(bool defaultConstantsReduction, + bool volumeConstantsReduction) + { + var quantities = new QuantityInfo[] { Mass.Info, Volume.Info }; + var expectedNumberOfConversions = 2 * (Volume.Info.UnitInfos.Count - 1); + var customQuantityOptions = new Dictionary { [typeof(Mass)] = new(ConversionCachingMode.None, volumeConstantsReduction) }; + + var unitConversions = quantities.GetUnitConversionFunctions(ConversionCachingMode.BaseOnly, defaultConstantsReduction, customQuantityOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.Multiple(() => Assert.Equal(expectedNumberOfConversions, unitConversions.Count), () => + { + Assert.All(Mass.Info.UnitInfos, + fromUnit => + { + Assert.All(Mass.Info.UnitInfos, + toUnit => { Assert.DoesNotContain(UnitConversionKey.Create(fromUnit.UnitKey, toUnit.UnitKey), unitConversions); }); + }); + }, () => + { + Assert.All(Volume.Info.UnitInfos, fromUnit => + { + UnitInfo baseUnit = Volume.Info.BaseUnitInfo; + Assert.All(Volume.Info.UnitInfos, toUnit => + { + var conversionKey = UnitConversionKey.Create(fromUnit.UnitKey, toUnit.UnitKey); + if ((fromUnit == baseUnit || toUnit == baseUnit) && fromUnit != toUnit) + { + QuantityValue valueToConvert = 123.45m; + QuantityValue expectedValue = toUnit.GetValueFrom(valueToConvert, fromUnit); + Assert.Contains(conversionKey, unitConversions); + Assert.Equal(expectedValue, unitConversions[conversionKey](valueToConvert)); + } + else + { + Assert.DoesNotContain(conversionKey, unitConversions); + } + }); + }); + }); + } + + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(false, false)] + public void NoCaching_WithSpecificAllOptions_ReturnsSpecifiedUnitConversions(bool defaultConstantsReduction, + bool volumeConstantsReduction) + { + var quantities = new QuantityInfo[] { Mass.Info, Volume.Info }; + var expectedNumberOfConversions = Volume.Info.UnitInfos.Count * (Volume.Info.UnitInfos.Count - 1); + var customQuantityOptions = new Dictionary { [typeof(Volume)] = new(ConversionCachingMode.All, volumeConstantsReduction) }; + + var unitConversions = quantities.GetUnitConversionFunctions(ConversionCachingMode.None, defaultConstantsReduction, customQuantityOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.Multiple(() => Assert.Equal(expectedNumberOfConversions, unitConversions.Count), + () => + { + Assert.All(Mass.Info.UnitInfos, fromUnit => + { + Assert.All(Mass.Info.UnitInfos, toUnit => + { + var conversionKey = UnitConversionKey.Create(fromUnit.UnitKey, toUnit.UnitKey); + Assert.DoesNotContain(conversionKey, unitConversions); + }); + }); + }, () => + { + Assert.All(Volume.Info.UnitInfos, fromUnit => + { + Assert.All(Volume.Info.UnitInfos, toUnit => + { + var conversionKey = UnitConversionKey.Create(fromUnit.UnitKey, toUnit.UnitKey); + if (fromUnit != toUnit) + { + QuantityValue valueToConvert = 123.45m; + QuantityValue expectedValue = toUnit.GetValueFrom(valueToConvert, fromUnit); + Assert.Contains(conversionKey, unitConversions); + Assert.Equal(expectedValue, unitConversions[conversionKey](valueToConvert)); + } + else + { + Assert.DoesNotContain(conversionKey, unitConversions); + } + }); + }); + }); + } + + [Theory] + [InlineData(true, true)] + [InlineData(true, false)] + [InlineData(false, true)] + [InlineData(false, false)] + public void NoCaching_WithSpecificBaseOnlyOptions_ReturnsSpecifiedUnitConversions(bool defaultConstantsReduction, + bool volumeConstantsReduction) + { + var quantities = new QuantityInfo[] { Mass.Info, Volume.Info }; + var expectedNumberOfConversions = 2 * (Volume.Info.UnitInfos.Count - 1); + var customQuantityOptions = + new Dictionary { [typeof(Volume)] = new(ConversionCachingMode.BaseOnly, volumeConstantsReduction) }; + + var unitConversions = quantities.GetUnitConversionFunctions(ConversionCachingMode.None, defaultConstantsReduction, customQuantityOptions) + .ToDictionary(pair => pair.Key, pair => pair.Value); + + Assert.Multiple(() => Assert.Equal(expectedNumberOfConversions, unitConversions.Count), () => + { + Assert.All(Mass.Info.UnitInfos, fromUnit => + { + Assert.All(Mass.Info.UnitInfos, toUnit => + { + var conversionKey = UnitConversionKey.Create(fromUnit.UnitKey, toUnit.UnitKey); + Assert.DoesNotContain(conversionKey, unitConversions); + }); + }); + }, () => + { + Assert.All(Volume.Info.UnitInfos, fromUnit => + { + UnitInfo baseUnit = Volume.Info.BaseUnitInfo; + Assert.All(Volume.Info.UnitInfos, toUnit => + { + var conversionKey = UnitConversionKey.Create(fromUnit.UnitKey, toUnit.UnitKey); + if ((fromUnit == baseUnit || toUnit == baseUnit) && fromUnit != toUnit) + { + QuantityValue valueToConvert = 123.45m; + QuantityValue expectedValue = toUnit.GetValueFrom(valueToConvert, fromUnit); + Assert.Contains(conversionKey, unitConversions); + Assert.Equal(expectedValue, unitConversions[conversionKey](valueToConvert)); + } + else + { + Assert.DoesNotContain(conversionKey, unitConversions); + } + }); + }); + }); + } + + [Theory] + [InlineData(ConversionCachingMode.All, true)] + [InlineData(ConversionCachingMode.BaseOnly, true)] + [InlineData(ConversionCachingMode.BaseOnly, false)] // the conversions from/to the base units are already reduced by the CodeGen + public void ReduceConstants_ReturnsUnitConversionsWithReducedCoefficients(ConversionCachingMode cachingMode, bool reduceConstants) + { + var quantities = new QuantityInfo[] { Mass.Info, Volume.Info }; + + IEnumerable unitConversions = quantities.GetUnitConversionFunctions(cachingMode, reduceConstants).Select(pair => pair.Value); + + Assert.All(unitConversions, valueDelegate => Assert.True(IsReduced(valueDelegate(QuantityValue.One)))); + } + + private static bool IsReduced(QuantityValue value) + { + (BigInteger numerator, BigInteger denominator) = value; + return BigInteger.GreatestCommonDivisor(numerator, denominator) == BigInteger.One; + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void GetUnitConversionFunctions_WithInvalidCachingMode_ThrowsArgumentException(bool reduceConstants) + { + var quantities = new QuantityInfo[] { Mass.Info, Volume.Info }; + const ConversionCachingMode invalidCachingMode = (ConversionCachingMode)(-1); + Assert.Multiple(() => + Assert.Throws(() => quantities.GetUnitConversionFunctions(invalidCachingMode, reduceConstants)), + () => + { + var emptyOptions = new Dictionary(); + Assert.Throws(() => quantities.GetUnitConversionFunctions(invalidCachingMode, reduceConstants, emptyOptions) + .ToList()); + }, + () => + { + var validOptions = new Dictionary { [typeof(Mass)] = new() }; + Assert.Throws(() => quantities.GetUnitConversionFunctions(invalidCachingMode, reduceConstants, validOptions) + .ToList()); + }, + () => + { + var invalidOptions = new Dictionary { [typeof(Mass)] = new(invalidCachingMode) }; + Assert.Throws(() => quantities.GetUnitConversionFunctions(default, reduceConstants, invalidOptions) + .ToList()); + }); + } +} diff --git a/UnitsNet.Tests/UnitConverterTest.cs b/UnitsNet.Tests/UnitConverterTest.cs index 17ffdb2305..dd894995d6 100644 --- a/UnitsNet.Tests/UnitConverterTest.cs +++ b/UnitsNet.Tests/UnitConverterTest.cs @@ -1,7 +1,10 @@ // 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 System.Collections.Generic; using System.Globalization; +using System.Linq; using UnitsNet.Tests.CustomQuantities; using UnitsNet.Units; using Xunit; @@ -10,117 +13,648 @@ namespace UnitsNet.Tests { public class UnitConverterTest { - [Fact] - public void CopyConstructorCopiesCoversionFunctions() + /// + /// Generates a collection of instances with all combinations of + /// constructor parameter values. + /// + /// + /// An of containing all possible + /// configurations + /// of freezing, caching modes, and constant reduction options. + /// + private static IEnumerable GetQuantityConverterBuildOptions() + { + bool[] frozenOptions = [true, false]; + ConversionCachingMode[] cachingOptions = [ConversionCachingMode.None, ConversionCachingMode.BaseOnly, ConversionCachingMode.All]; + bool[] reductionOptions = [true, false]; + return frozenOptions.SelectMany(freeze => cachingOptions.SelectMany(cachingMode => reductionOptions.Select(reduce => + new QuantityConverterBuildOptions(freeze, cachingMode, reduce)))); + } + + /// + /// Gets the test data for the unit converter tests. + /// + /// + /// A collection of tuples containing: + /// + /// + /// A indicating whether to freeze the conversion. + /// + /// + /// A specifying the caching mode. + /// + /// + /// A indicating whether to reduce constants. + /// + /// + /// + public static TheoryData ConverterTestOptions => + new() + { + { true, ConversionCachingMode.None, true }, + { true, ConversionCachingMode.BaseOnly, true }, + { true, ConversionCachingMode.All, true }, + { false, ConversionCachingMode.None, true }, + { false, ConversionCachingMode.BaseOnly, true }, + { false, ConversionCachingMode.All, true }, + { true, ConversionCachingMode.None, false }, + { true, ConversionCachingMode.BaseOnly, false }, + { true, ConversionCachingMode.All, false }, + { false, ConversionCachingMode.None, false }, + { false, ConversionCachingMode.BaseOnly, false }, + { false, ConversionCachingMode.All, false } + }; + + // [Fact] + // public void CopyConstructorCopiesCoversionFunctions() + // { + // Length ConversionFunction(Length from) => Length.FromInches(18); + // + // var unitConverter = new UnitConverter(); + // unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, ConversionFunction); + // + // var copiedUnitConverter = new UnitConverter(unitConverter); + // var foundConversionFunction = copiedUnitConverter.GetConversionFunction(LengthUnit.Meter, LengthUnit.Inch); + // Assert.NotNull(foundConversionFunction); + // } + + // [Fact] + // public void CustomConversionWithSameQuantityType() + // { + // Length ConversionFunction(Length from) => Length.FromInches(18); + // + // var unitConverter = new UnitConverter(); + // unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, ConversionFunction); + // + // var foundConversionFunction = unitConverter.GetConversionFunction(LengthUnit.Meter, LengthUnit.Inch); + // var converted = foundConversionFunction(Length.FromMeters(1.0)); + // + // Assert.Equal(Length.FromInches(18), converted); + // } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void GetConversionFunction_WithSameQuantityType(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) { - Length ConversionFunction(Length from) => Length.FromInches(18); + var unitParser = new UnitParser([Length.Info]); + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var unitConverter = UnitConverter.Create(unitParser, convertOptions); + + Assert.Multiple(() => + { + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(LengthUnit.Meter, LengthUnit.Meter); + QuantityValue converted = conversionFunction(1); + + Assert.Equal(1, converted); + }, () => + { + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(LengthUnit.Centimeter, LengthUnit.Meter); + QuantityValue converted = conversionFunction(10); - var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, ConversionFunction); + Assert.Equal(0.1m, converted); + }, () => + { + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(LengthUnit.Meter, LengthUnit.Centimeter); + QuantityValue converted = conversionFunction(1); - var copiedUnitConverter = new UnitConverter(unitConverter); - var foundConversionFunction = copiedUnitConverter.GetConversionFunction(LengthUnit.Meter, LengthUnit.Inch); - Assert.NotNull(foundConversionFunction); + Assert.Equal(100, converted); + }, () => + { + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(LengthUnit.Millimeter, LengthUnit.Centimeter); + QuantityValue converted = conversionFunction(10); + + Assert.Equal(1, converted); + }, () => + { + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(LengthUnit.Inch, LengthUnit.Inch); + QuantityValue converted = conversionFunction(1); + + Assert.Equal(1, converted); + }); } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryGetConversionFunction_WithSameQuantityType_ReturnsTrue(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var unitParser = new UnitParser([Length.Info]); + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var unitConverter = UnitConverter.Create(unitParser, convertOptions); - [Fact] - public void CustomConversionWithSameQuantityType() + Assert.Multiple(() => + { + var success = unitConverter.TryGetConversionFunction(LengthUnit.Meter, LengthUnit.Meter, out ConvertValueDelegate? conversionFunction); + Assert.True(success); + Assert.Equal(1, conversionFunction!(1)); + }, () => + { + var success = unitConverter.TryGetConversionFunction(LengthUnit.Centimeter, LengthUnit.Meter, out ConvertValueDelegate? conversionFunction); + Assert.True(success); + Assert.Equal(0.1m, conversionFunction!(10)); + }, () => + { + var success = unitConverter.TryGetConversionFunction(LengthUnit.Meter, LengthUnit.Centimeter, out ConvertValueDelegate? conversionFunction); + Assert.True(success); + Assert.Equal(100, conversionFunction!(1)); + }, () => + { + var success = unitConverter.TryGetConversionFunction(LengthUnit.Millimeter, LengthUnit.Centimeter, out ConvertValueDelegate? conversionFunction); + Assert.True(success); + Assert.Equal(1, conversionFunction!(10)); + }, () => + { + var success = unitConverter.TryGetConversionFunction(LengthUnit.Inch, LengthUnit.Inch, out ConvertValueDelegate? conversionFunction); + Assert.True(success); + Assert.Equal(1, conversionFunction!(1)); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void GetConversionFunction_WithCustomUnitConversion(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) { - Length ConversionFunction(Length from) => Length.FromInches(18); + var customLengthInfo = Length.LengthInfo.CreateDefault(unitDefinitions => + unitDefinitions.Configure(LengthUnit.Inch, definition => definition.WithConversionFromBase(18))); + + var unitParser = new UnitParser([customLengthInfo]); + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var unitConverter = UnitConverter.Create(unitParser, convertOptions); - var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, ConversionFunction); + Assert.Multiple(() => + { + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(LengthUnit.Meter, LengthUnit.Inch); + QuantityValue converted = conversionFunction(1); - var foundConversionFunction = unitConverter.GetConversionFunction(LengthUnit.Meter, LengthUnit.Inch); - var converted = foundConversionFunction(Length.FromMeters(1.0)); + Assert.Equal(18, converted); + }, () => + { + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(LengthUnit.Inch, LengthUnit.Meter); + QuantityValue converted = conversionFunction(18); - Assert.Equal(Length.FromInches(18), converted); + Assert.Equal(1, converted); + }, () => + { + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(LengthUnit.Meter, LengthUnit.Meter); + QuantityValue converted = conversionFunction(18); + + Assert.Equal(18, converted); + }, () => + { + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(LengthUnit.Inch, LengthUnit.Inch); + QuantityValue converted = conversionFunction(18); + + Assert.Equal(18, converted); + }, () => + { + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(LengthUnit.Meter, LengthUnit.Centimeter); + QuantityValue converted = conversionFunction(18); + + Assert.Equal(1800, converted); + }); } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryGetConversionFunction_WithCustomUnitConversion_ReturnsTrue(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var customLengthInfo = Length.LengthInfo.CreateDefault(unitDefinitions => + unitDefinitions.Configure(LengthUnit.Inch, definition => definition.WithConversionFromBase(18))); - [Fact] - public void CustomConversionWithSameQuantityTypeByTypeParam() + var unitParser = new UnitParser([customLengthInfo]); + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var unitConverter = UnitConverter.Create(unitParser, convertOptions); + + Assert.Multiple(() => + { + var success = unitConverter.TryGetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, out ConvertValueDelegate? conversionFunction); + Assert.True(success); + Assert.Equal(18, conversionFunction!(1)); + }, () => + { + var success = unitConverter.TryGetConversionFunction(LengthUnit.Inch, LengthUnit.Meter, out ConvertValueDelegate? conversionFunction); + Assert.True(success); + Assert.Equal(1, conversionFunction!(18)); + }, () => + { + var success = unitConverter.TryGetConversionFunction(LengthUnit.Meter, LengthUnit.Meter, out ConvertValueDelegate? conversionFunction); + Assert.True(success); + Assert.Equal(18, conversionFunction!(18)); + }, () => + { + var success = unitConverter.TryGetConversionFunction(LengthUnit.Inch, LengthUnit.Inch, out ConvertValueDelegate? conversionFunction); + Assert.True(success); + Assert.Equal(18, conversionFunction!(18)); + }, () => + { + var success = unitConverter.TryGetConversionFunction(LengthUnit.Meter, LengthUnit.Centimeter, out ConvertValueDelegate? conversionFunction); + Assert.True(success); + Assert.Equal(1800, conversionFunction!(18)); + }); + } + + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void GetConversionFunction_WithUnknownUnit_ThrowsUnitNotFoundException(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var unitParser = new UnitParser([Length.Info, Mass.Info]); + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var unitConverter = UnitConverter.Create(unitParser, convertOptions); + + Assert.Multiple(() => + { + Assert.Throws(() => unitConverter.GetConversionFunction(LengthUnit.Meter, (LengthUnit)(-1))); + }, + () => + { + Assert.Throws(() => unitConverter.GetConversionFunction((LengthUnit)(-1), LengthUnit.Meter)); + }, + () => + { + Assert.Throws(() => unitConverter.GetConversionFunction(MassUnit.Kilogram, (LengthUnit)(-1))); + }, + () => + { + Assert.Throws(() => unitConverter.GetConversionFunction((LengthUnit)(-1), MassUnit.Kilogram)); + }, + () => + { + Assert.Throws(() => unitConverter.GetConversionFunction(VolumeUnit.Milliliter, (LengthUnit)(-1))); + }, + () => + { + Assert.Throws(() => unitConverter.GetConversionFunction((LengthUnit)(-1), VolumeUnit.Milliliter)); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryGetConversionFunction_WithUnknownUnit_ReturnsFalse(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) { - Length ConversionFunction(Length from) => Length.FromInches(18); + var unitParser = new UnitParser([Length.Info, Mass.Info]); + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var unitConverter = UnitConverter.Create(unitParser, convertOptions); - var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, (ConversionFunction) ConversionFunction); + Assert.Multiple(() => + { + var success = unitConverter.TryGetConversionFunction(LengthUnit.Meter, (LengthUnit)(-1), out ConvertValueDelegate? conversionFunction); + Assert.False(success); + Assert.Null(conversionFunction); + }, () => + { + var success = unitConverter.TryGetConversionFunction((LengthUnit)(-1), LengthUnit.Meter, out ConvertValueDelegate? conversionFunction); + Assert.False(success); + Assert.Null(conversionFunction); + }, () => + { + var success = unitConverter.TryGetConversionFunction(MassUnit.Kilogram, (LengthUnit)(-1), out ConvertValueDelegate? conversionFunction); + Assert.False(success); + Assert.Null(conversionFunction); + }, () => + { + var success = unitConverter.TryGetConversionFunction((LengthUnit)(-1), MassUnit.Kilogram, out ConvertValueDelegate? conversionFunction); + Assert.False(success); + Assert.Null(conversionFunction); + }, () => + { + var success = unitConverter.TryGetConversionFunction(VolumeUnit.Milliliter, (LengthUnit)(-1), out ConvertValueDelegate? conversionFunction); + Assert.False(success); + Assert.Null(conversionFunction); + }, () => + { + var success = unitConverter.TryGetConversionFunction((LengthUnit)(-1), VolumeUnit.Milliliter, out ConvertValueDelegate? conversionFunction); + Assert.False(success); + Assert.Null(conversionFunction); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void GetConversionFunction_WithIncompatibleQuantities_ThrowsInvalidConversionException(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var unitParser = new UnitParser([Length.Info, Mass.Info]); + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var unitConverter = UnitConverter.Create(unitParser, convertOptions); - var foundConversionFunction = unitConverter.GetConversionFunction(typeof(Length), LengthUnit.Meter, typeof(Length), LengthUnit.Inch); - var converted = foundConversionFunction(Length.FromMeters(1.0)); + Assert.Multiple(() => + { + Assert.Throws(() => unitConverter.GetConversionFunction(LengthUnit.Meter, MassUnit.Kilogram)); + }, + () => + { + Assert.Throws(() => unitConverter.GetConversionFunction(MassUnit.Kilogram, LengthUnit.Meter)); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryGetConversionFunction_WithInvalidUnit_ReturnsFalse(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var unitParser = new UnitParser([Length.Info, Mass.Info]); + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var unitConverter = UnitConverter.Create(unitParser, convertOptions); - Assert.Equal(Length.FromInches(18), converted); + Assert.Multiple(() => + { + var success = unitConverter.TryGetConversionFunction(LengthUnit.Meter, MassUnit.Kilogram, out ConvertValueDelegate? conversionFunction); + Assert.False(success); + Assert.Null(conversionFunction); + }, () => + { + var success = unitConverter.TryGetConversionFunction(MassUnit.Kilogram, LengthUnit.Meter, out ConvertValueDelegate? conversionFunction); + Assert.False(success); + Assert.Null(conversionFunction); + }); } + + [Theory] + [InlineData(1, LengthUnit.Meter, ReciprocalLengthUnit.InverseMeter, 1)] + [InlineData(1, LengthUnit.Centimeter, ReciprocalLengthUnit.InverseCentimeter, 1)] + [InlineData(1, LengthUnit.Centimeter, ReciprocalLengthUnit.InverseMillimeter, 0.1)] + [InlineData(1, LengthUnit.Millimeter, ReciprocalLengthUnit.InverseCentimeter, 10)] + [InlineData(10, LengthUnit.Millimeter, ReciprocalLengthUnit.InverseCentimeter, 1)] + [InlineData(-10, LengthUnit.Millimeter, ReciprocalLengthUnit.InverseCentimeter, -1)] + [InlineData(0, LengthUnit.Millimeter, ReciprocalLengthUnit.InverseCentimeter, double.PositiveInfinity)] + [InlineData(double.PositiveInfinity, LengthUnit.Millimeter, ReciprocalLengthUnit.InverseCentimeter, 0)] + [InlineData(double.NegativeInfinity, LengthUnit.Millimeter, ReciprocalLengthUnit.InverseCentimeter, 0)] + [InlineData(double.NaN, LengthUnit.Millimeter, ReciprocalLengthUnit.InverseCentimeter, double.NaN)] + public void GetConversionFunction_WithCompatibleQuantityType(double fromValue, LengthUnit fromUnit, ReciprocalLengthUnit toUnit, double expectedValue) + { + IEnumerable converterOptions = GetQuantityConverterBuildOptions(); - [Fact] - public void CustomConversionWithDifferentQuantityTypes() + Assert.All(converterOptions, options => + { + var unitConverter = UnitConverter.Create(new UnitParser([Length.Info, ReciprocalLength.Info]), options); + + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(fromUnit, toUnit); + QuantityValue converted = conversionFunction(fromValue); + + Assert.Equal(expectedValue, converted); + }); + } + + [Theory] + [InlineData(1, LengthUnit.Meter, ReciprocalLengthUnit.InverseMeter, 1)] + [InlineData(1, LengthUnit.Centimeter, ReciprocalLengthUnit.InverseCentimeter, 1)] + [InlineData(1, LengthUnit.Centimeter, ReciprocalLengthUnit.InverseMillimeter, 0.1)] + [InlineData(1, LengthUnit.Millimeter, ReciprocalLengthUnit.InverseCentimeter, 10)] + [InlineData(10, LengthUnit.Millimeter, ReciprocalLengthUnit.InverseCentimeter, 1)] + [InlineData(-10, LengthUnit.Millimeter, ReciprocalLengthUnit.InverseCentimeter, -1)] + [InlineData(0, LengthUnit.Millimeter, ReciprocalLengthUnit.InverseCentimeter, double.PositiveInfinity)] + [InlineData(double.PositiveInfinity, LengthUnit.Millimeter, ReciprocalLengthUnit.InverseCentimeter, 0)] + [InlineData(double.NegativeInfinity, LengthUnit.Millimeter, ReciprocalLengthUnit.InverseCentimeter, 0)] + [InlineData(double.NaN, LengthUnit.Millimeter, ReciprocalLengthUnit.InverseCentimeter, double.NaN)] + public void TryGetConversionFunction_WithCompatibleQuantityType(double fromValue, LengthUnit fromUnit, ReciprocalLengthUnit toUnit, double expectedValue) { - IQuantity ConversionFunction(IQuantity from) => Length.FromInches(18); + IEnumerable converterOptions = GetQuantityConverterBuildOptions(); - var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(MassUnit.Grain, LengthUnit.Inch, ConversionFunction); + Assert.All(converterOptions, options => + { + var unitConverter = UnitConverter.Create(new UnitParser([Length.Info, ReciprocalLength.Info]), options); + + var success = unitConverter.TryGetConversionFunction(fromUnit, toUnit, out ConvertValueDelegate? conversionFunction); + + Assert.True(success); + Assert.Equal(expectedValue, conversionFunction!(fromValue)); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConversionToSameUnit_ReturnsSameQuantity(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var unitConverter = UnitConverter.Create(new UnitParser([]), convertOptions); - var foundConversionFunction = unitConverter.GetConversionFunction(MassUnit.Grain, LengthUnit.Inch); - var converted = foundConversionFunction(Mass.FromGrains(100)); + ConvertValueDelegate foundConversionFunction = unitConverter.GetConversionFunction(HowMuchUnit.ATon, HowMuchUnit.ATon); + QuantityValue converted = foundConversionFunction(39); - Assert.Equal(Length.FromInches(18), converted); + Assert.Equal(39, converted); } - [Fact] - public void CustomConversionWithDifferentQuantityTypesByTypeParam() + [Theory] + [InlineData(1, HowMuchUnit.Some, HowMuchUnit.Some, 1)] + [InlineData(1, HowMuchUnit.Some, HowMuchUnit.ATon, 0.1)] + [InlineData(1, HowMuchUnit.Some, HowMuchUnit.AShitTon, 0.01)] + [InlineData(1, HowMuchUnit.ATon, HowMuchUnit.Some, 10)] + [InlineData(1, HowMuchUnit.AShitTon, HowMuchUnit.Some, 100)] + public void ConversionForUnitsOfCustomQuantity(double fromValue, HowMuchUnit fromUnit, HowMuchUnit toUnit, double expectedValue) { - IQuantity ConversionFunction(IQuantity from) => Length.FromInches(18); + IEnumerable converterOptions = GetQuantityConverterBuildOptions(); - var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(MassUnit.Grain, LengthUnit.Inch, ConversionFunction); + Assert.All(converterOptions, options => + { + var unitConverter = UnitConverter.Create(new UnitParser([HowMuch.Info]), options); - var foundConversionFunction = unitConverter.GetConversionFunction(typeof(Mass), MassUnit.Grain, typeof(Length), LengthUnit.Inch); - var converted = foundConversionFunction(Mass.FromGrains(100)); + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(fromUnit, toUnit); + QuantityValue converted = conversionFunction(fromValue); - Assert.Equal(Length.FromInches(18), converted); + Assert.Equal(expectedValue, converted); + }); } - [Fact] - public void TryCustomConversionForOilBarrelsToUsGallons() + [Theory] + [InlineData(1, MassUnit.Tonne, HowMuchUnit.ATon, 1)] + [InlineData(1000, MassUnit.Kilogram, HowMuchUnit.ATon, 1)] + [InlineData(100, MassUnit.Kilogram, HowMuchUnit.Some, 1)] + [InlineData(10000, MassUnit.Kilogram, HowMuchUnit.AShitTon, 1)] + public void GetConversionFunction_WithCustomConversionForDifferentQuantities(double fromValue, MassUnit fromUnit, HowMuchUnit toUnit, + double expectedValue) { - Volume ConversionFunction(Volume from) => Volume.FromUsGallons(from.Value * 42); + IEnumerable converterOptions = GetQuantityConverterBuildOptions(); - var unitConverter = new UnitConverter(); - unitConverter.SetConversionFunction(VolumeUnit.OilBarrel, VolumeUnit.UsGallon, ConversionFunction); + Assert.All(converterOptions, options => + { + var unitConverter = UnitConverter.Create(new UnitParser([Mass.Info, HowMuch.Info]), + options.WithImplicitConversionOptions(conversionOptions => + // since the dimensions of the two quantities are compatible and there is at least one pair of units that have the same BaseUnits (in our case these are the Mass.Tonne and HowMuch.ATon) + // we don't have to specify a conversion expression (it is assumed that "1 Tonne" is equal to "1 ATon") + conversionOptions.SetCustomConversion())); + + Assert.Multiple(() => + { + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(fromUnit, toUnit); + QuantityValue converted = conversionFunction(fromValue); + Assert.Equal(expectedValue, converted); + }, + () => + { + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(toUnit, fromUnit); + QuantityValue converted = conversionFunction(expectedValue); + Assert.Equal(fromValue, converted); + }); + }); + } + + [Theory] + [InlineData(1, MassUnit.Tonne, HowMuchUnit.ATon, 1)] + [InlineData(1000, MassUnit.Kilogram, HowMuchUnit.ATon, 1)] + [InlineData(100, MassUnit.Kilogram, HowMuchUnit.Some, 1)] + [InlineData(10000, MassUnit.Kilogram, HowMuchUnit.AShitTon, 1)] + public void TryGetConversionFunction_WithCustomConversionForDifferentQuantities(double fromValue, MassUnit fromUnit, HowMuchUnit toUnit, + double expectedValue) + { + IEnumerable converterOptions = GetQuantityConverterBuildOptions(); - var foundConversionFunction = unitConverter.GetConversionFunction(VolumeUnit.OilBarrel, VolumeUnit.UsGallon); - var converted = foundConversionFunction(Volume.FromOilBarrels(1)); + Assert.All(converterOptions, options => + { + var unitConverter = UnitConverter.Create(new UnitParser([Mass.Info, HowMuch.Info]), + options.WithImplicitConversionOptions(conversionOptions => + // since the dimensions of the two quantities are compatible and there is at least one pair of units that have the same BaseUnits (in our case these are the Mass.Tonne and HowMuch.ATon) + // we don't have to specify a conversion expression (it is assumed that "1 Tonne" is equal to "1 ATon") + conversionOptions.SetCustomConversion())); - Assert.Equal(Volume.FromUsGallons(42), converted); + Assert.Multiple(() => + { + var success = unitConverter.TryGetConversionFunction(fromUnit, toUnit, out ConvertValueDelegate? conversionFunction); + Assert.True(success); + Assert.Equal(expectedValue, conversionFunction!(fromValue)); + }, + () => + { + var success = unitConverter.TryGetConversionFunction(toUnit, fromUnit, out ConvertValueDelegate? conversionFunction); + Assert.True(success); + Assert.Equal(fromValue, conversionFunction!(expectedValue)); + }); + }); } - [Fact] - public void ConversionToSameUnit_ReturnsSameQuantity() + [Theory] + [InlineData(1, VolumeUnit.Liter, HowMuchUnit.Some, 1)] + [InlineData(1000, VolumeUnit.Milliliter, HowMuchUnit.Some, 1)] + [InlineData(10, VolumeUnit.Liter, HowMuchUnit.ATon, 1)] + [InlineData(1, VolumeUnit.Kiloliter, HowMuchUnit.AShitTon, 10)] + public void GetConversionFunction_WithCustomConversionExpressionForDifferentQuantities(double fromValue, VolumeUnit fromUnit, HowMuchUnit toUnit, + double expectedValue) { - var unitConverter = new UnitConverter(); + IEnumerable converterOptions = GetQuantityConverterBuildOptions(); - var foundConversionFunction = unitConverter.GetConversionFunction(HowMuchUnit.ATon, HowMuchUnit.ATon); - var converted = foundConversionFunction(new HowMuch(39, HowMuchUnit.Some)); // Intentionally pass the wrong unit here, to test that the exact same quantity is returned + Assert.All(converterOptions, options => + { + var unitConverter = UnitConverter.Create(new UnitParser([Volume.Info, HowMuch.Info]), + options.WithImplicitConversionOptions(conversionOptions => + conversionOptions + // since the dimensions / base units are incompatible we have to explicitly specify a conversion expression + .SetCustomConversion() + .SetCustomConversion(VolumeUnit.Liter, HowMuchUnit.Some, QuantityValue.One, true))); - Assert.Equal(39, converted.Value); - Assert.Equal(HowMuchUnit.Some, converted.Unit); + Assert.Multiple(() => + { + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(fromUnit, toUnit); + QuantityValue converted = conversionFunction(fromValue); + Assert.Equal(expectedValue, converted); + }, + () => + { + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(toUnit, fromUnit); + QuantityValue converted = conversionFunction(expectedValue); + Assert.Equal(fromValue, converted); + }); + }); } [Theory] - [InlineData(1, HowMuchUnit.Some, HowMuchUnit.Some, 1)] - [InlineData(1, HowMuchUnit.Some, HowMuchUnit.ATon, 2)] - [InlineData(1, HowMuchUnit.Some, HowMuchUnit.AShitTon, 10)] - public void ConversionForUnitsOfCustomQuantity(double fromValue, HowMuchUnit fromUnit, HowMuchUnit toUnit, double expectedValue) + [InlineData(1, VolumeUnit.Liter, HowMuchUnit.Some, 1)] + [InlineData(1000, VolumeUnit.Milliliter, HowMuchUnit.Some, 1)] + [InlineData(10, VolumeUnit.Liter, HowMuchUnit.ATon, 1)] + [InlineData(1, VolumeUnit.Kiloliter, HowMuchUnit.AShitTon, 10)] + public void TryGetConversionFunction_WithCustomConversionExpressionForDifferentQuantities(double fromValue, VolumeUnit fromUnit, HowMuchUnit toUnit, + double expectedValue) + { + IEnumerable converterOptions = GetQuantityConverterBuildOptions(); + + Assert.All(converterOptions, options => + { + var unitConverter = UnitConverter.Create(new UnitParser([Volume.Info, HowMuch.Info]), + options.WithImplicitConversionOptions(conversionOptions => + conversionOptions + // since the dimensions / base units are incompatible we have to explicitly specify a conversion expression + .SetCustomConversion() + .SetCustomConversion(VolumeUnit.Liter, HowMuchUnit.Some, QuantityValue.One, true))); + + Assert.Multiple(() => + { + var success = unitConverter.TryGetConversionFunction(fromUnit, toUnit, out ConvertValueDelegate? conversionFunction); + Assert.True(success); + Assert.Equal(expectedValue, conversionFunction!(fromValue)); + }, + () => + { + var success = unitConverter.TryGetConversionFunction(toUnit, fromUnit, out ConvertValueDelegate? conversionFunction); + Assert.True(success); + Assert.Equal(fromValue, conversionFunction!(expectedValue)); + }); + }); + } + + [Theory] + [InlineData(1, MassFractionUnit.DecimalFraction, RatioUnit.DecimalFraction, 1)] + [InlineData(1, MassFractionUnit.DecimalFraction, RatioUnit.PartPerThousand, 1000)] + [InlineData(100, MassFractionUnit.Percent, RatioUnit.DecimalFraction, 1)] + [InlineData(1, MassFractionUnit.GramPerKilogram, RatioUnit.PartPerThousand, 1)] + public void GetConversionFunction_WithCustomConversionForDifferentDimensionlessQuantities(double fromValue, MassFractionUnit fromUnit, RatioUnit toUnit, + double expectedValue) + { + IEnumerable converterOptions = GetQuantityConverterBuildOptions(); + + Assert.All(converterOptions, options => + { + var unitConverter = UnitConverter.Create(new UnitParser([MassFraction.Info, Ratio.Info]), + options.WithImplicitConversionOptions(conversionOptions => + // since both quantities are dimensionless it is assumed that the quantities can be converted using their BaseUnit (i.e. the DecimalFraction) + conversionOptions.SetCustomConversion())); + + Assert.Multiple(() => + { + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(fromUnit, toUnit); + QuantityValue converted = conversionFunction(fromValue); + Assert.Equal(expectedValue, converted); + }, + () => + { + ConvertValueDelegate conversionFunction = unitConverter.GetConversionFunction(toUnit, fromUnit); + QuantityValue converted = conversionFunction(expectedValue); + Assert.Equal(fromValue, converted); + }); + }); + } + + [Theory] + [InlineData(1, MassFractionUnit.DecimalFraction, RatioUnit.DecimalFraction, 1)] + [InlineData(1, MassFractionUnit.DecimalFraction, RatioUnit.PartPerThousand, 1000)] + [InlineData(100, MassFractionUnit.Percent, RatioUnit.DecimalFraction, 1)] + [InlineData(1, MassFractionUnit.GramPerKilogram, RatioUnit.PartPerThousand, 1)] + public void TryGetConversionFunction_WithCustomConversionForDifferentDimensionlessQuantities(double fromValue, MassFractionUnit fromUnit, RatioUnit toUnit, + double expectedValue) { - // Intentionally don't map conversion Some->Some, it is not necessary - var unitConverter = new UnitConverter(); - 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)); + IEnumerable converterOptions = GetQuantityConverterBuildOptions(); - var foundConversionFunction = unitConverter.GetConversionFunction(fromUnit, toUnit); - var converted = foundConversionFunction(new HowMuch(fromValue, fromUnit)); + Assert.All(converterOptions, options => + { + var unitConverter = UnitConverter.Create(new UnitParser([MassFraction.Info, Ratio.Info]), + options.WithImplicitConversionOptions(conversionOptions => + // since both quantities are dimensionless it is assumed that the quantities can be converted using their BaseUnit (i.e. the DecimalFraction) + conversionOptions.SetCustomConversion())); - Assert.Equal(expectedValue, converted.Value); - Assert.Equal(toUnit, converted.Unit); + Assert.Multiple(() => + { + var success = unitConverter.TryGetConversionFunction(fromUnit, toUnit, out ConvertValueDelegate? conversionFunction); + Assert.True(success); + Assert.Equal(expectedValue, conversionFunction!(fromValue)); + }, + () => + { + var success = unitConverter.TryGetConversionFunction(toUnit, fromUnit, out ConvertValueDelegate? conversionFunction); + Assert.True(success); + Assert.Equal(fromValue, conversionFunction!(expectedValue)); + }); + }); } [Theory] @@ -167,8 +701,7 @@ public void ConvertByName_ThrowsUnitNotFoundExceptionOnUnknownFromOrToUnit(doubl [InlineData(1, "Length", "Meter", "UnknownToUnit")] public void TryConvertByName_ReturnsFalseForInvalidInput(double inputValue, string quantityTypeName, string fromUnit, string toUnit) { - Assert.False(UnitConverter.TryConvertByName(inputValue, quantityTypeName, fromUnit, toUnit, out double result)); - Assert.Equal(0, result); + Assert.False(UnitConverter.TryConvertByName(inputValue, quantityTypeName, fromUnit, toUnit, out _)); } [Theory] @@ -179,43 +712,89 @@ public void TryConvertByName_ReturnsFalseForInvalidInput(double inputValue, stri public void TryConvertByName_ReturnsTrueOnSuccessAndOutputsResult(double 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 QuantityValue result)); Assert.Equal(expectedValue, result); } + [Theory] + [InlineData(0, 0, "Length", "Meter", "Centimeter")] // base -> non-base (zero) + [InlineData(100, 1, "Length", "Meter", "Centimeter")] // base -> non-base + [InlineData(10, 1, "Length", "Centimeter", "Millimeter")] // non-base -> non-base + [InlineData(1, 1, "Mass", "Gram", "Gram")] // same-units (non-base) + [InlineData(1, 1000, "Mass", "Gram", "Kilogram")] // non-base -> base + [InlineData(2000, 2, "Mass", "Gram", "Milligram")] // non-base -> non-base + public void TryConvertValueByName_ReturnsTrueOnSuccessAndOutputsResult(double expectedValue, double inputValue, string quantityTypeName, string fromUnit, + string toUnit) + { + Assert.Multiple(() => + { + var converter = new UnitConverter(UnitParser.Default); + + Assert.True(converter.TryConvertValueByName(inputValue, quantityTypeName, fromUnit, toUnit, out QuantityValue result)); + Assert.Equal(expectedValue, result); + }, () => + { + var converter = UnitConverter.Create(UnitParser.Default, + new QuantityConverterBuildOptions(defaultCachingMode: ConversionCachingMode.None, freeze: false)); + + Assert.True(converter.TryConvertValueByName(inputValue, quantityTypeName, fromUnit, toUnit, out QuantityValue result)); + Assert.Equal(expectedValue, result); + }, () => + { + var converter = UnitConverter.Create(UnitParser.Default, + new QuantityConverterBuildOptions(defaultCachingMode: ConversionCachingMode.None, freeze: true) + .WithCustomCachingOptions(new ConversionCacheOptions())); + + Assert.True(converter.TryConvertValueByName(inputValue, quantityTypeName, fromUnit, toUnit, out QuantityValue result)); + Assert.Equal(expectedValue, result); + }); + } + [Theory] [InlineData(0, 0, "Length", "m", "cm")] + [InlineData(1, 1, "Length", "cm", "cm")] [InlineData(100, 1, "Length", "m", "cm")] [InlineData(1, 1000, "Mass", "g", "kg")] [InlineData(1000, 1, "ElectricCurrent", "kA", "A")] - public void ConvertByAbbreviation_ConvertsTheValueToGivenUnit(double expectedValue, double inputValue, string quantityTypeName, string fromUnit, string toUnit) + public void ConvertByAbbreviation_ConvertsTheValueToGivenUnit(double expectedValue, double inputValue, string quantityTypeName, string fromUnit, + string toUnit) { Assert.Equal(expectedValue, UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit)); + Assert.Equal(expectedValue, UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, CultureInfo.InvariantCulture)); + Assert.Equal(expectedValue, UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, "en-US")); } [Theory] [InlineData(1, "UnknownQuantity", "m", "cm")] - public void ConvertByAbbreviation_ThrowsQuantityNotFoundExceptionOnUnknownQuantity( double inputValue, string quantityTypeName, string fromUnit, string toUnit) + public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownQuantity(double inputValue, string quantityTypeName, string fromUnit, + string toUnit) { Assert.Throws(() => UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit)); + Assert.Throws(() => UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, CultureInfo.InvariantCulture)); + Assert.Throws(() => UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, "en-US")); } [Theory] [InlineData(1, "Length", "UnknownFromUnit", "cm")] [InlineData(1, "Length", "m", "UnknownToUnit")] - public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownFromOrToUnitAbbreviation(double inputValue, string quantityTypeName, string fromUnit, string toUnit) + public void ConvertByAbbreviation_ThrowsUnitNotFoundExceptionOnUnknownFromOrToUnitAbbreviation(double inputValue, string quantityTypeName, + string fromUnit, string toUnit) { Assert.Throws(() => UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit)); + Assert.Throws(() => UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, CultureInfo.InvariantCulture)); + Assert.Throws(() => UnitConverter.ConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, "en-US")); } [Theory] [InlineData(1, "UnknownQuantity", "m", "cm", "en-US")] [InlineData(1, "Length", "UnknownFromUnit", "cm", "en-US")] [InlineData(1, "Length", "m", "UnknownToUnit", "en-US")] - public void TryConvertByAbbreviation_ReturnsFalseForInvalidInput(double inputValue, string quantityTypeName, string fromUnit, string toUnit, string culture) + public void TryConvertByAbbreviation_ReturnsFalseForInvalidInput(double inputValue, string quantityTypeName, string fromUnit, string toUnit, + string culture) { - Assert.False(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out double result, culture)); - Assert.Equal(0, result); + Assert.False(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, null, out _)); + Assert.False(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, CultureInfo.GetCultureInfo(culture), out _)); + Assert.False(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out _, culture)); } [Theory] @@ -223,10 +802,2633 @@ public void TryConvertByAbbreviation_ReturnsFalseForInvalidInput(double inputVal [InlineData(100, 1, "Length", "m", "cm", "en-US")] [InlineData(1, 1000, "Mass", "g", "kg", "en-US")] [InlineData(1000, 1, "ElectricCurrent", "kA", "A", "en-US")] - public void TryConvertByAbbreviation_ReturnsTrueOnSuccessAndOutputsResult(double expectedValue, double inputValue, string quantityTypeName, string fromUnit, string toUnit, string culture) + public void TryConvertByAbbreviation_ReturnsTrueOnSuccessAndOutputsResult(double expectedValue, double inputValue, string quantityTypeName, + string fromUnit, string toUnit, string culture) + { + Assert.Multiple( + () => + { + Assert.True(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, CultureInfo.GetCultureInfo(culture), out QuantityValue result), "TryConvertByAbbreviation() return value."); + Assert.Equal(expectedValue, result); + }, + () => + { + Assert.True(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out QuantityValue result, culture), "TryConvertByAbbreviation() return value."); + Assert.Equal(expectedValue, result); + }); + } + + [Theory] + // note: this test is culture-dependant, however using the international units should work with any "CurrentCulture" + [InlineData(0, 0, "Length", "m", "cm")] + [InlineData(1, 1, "Length", "cm", "cm")] + [InlineData(100, 1, "Length", "m", "cm")] + [InlineData(1, 1000, "Mass", "g", "kg")] + [InlineData(1000, 1, "ElectricCurrent", "kA", "A")] + public void TryConvertByAbbreviation_WithDefaultCulture_ReturnsTrueOnSuccessAndOutputsResult(double expectedValue, double inputValue, string quantityTypeName, + string fromUnit, string toUnit) + { + Assert.True(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out QuantityValue result)); + Assert.Equal(expectedValue, result); + } + + [Theory] + // note: this test is culture-dependant, however using the international units should work with any "CurrentCulture" + [InlineData(0, 0, "Length", "m", "cm")] + [InlineData(1, 1, "Length", "cm", "cm")] + [InlineData(100, 1, "Length", "m", "cm")] + [InlineData(1, 1000, "Mass", "g", "kg")] + [InlineData(1000, 1, "ElectricCurrent", "kA", "A")] + public void TryConvertValueByAbbreviation_ReturnsTrueOnSuccessAndOutputsResult(double expectedValue, double inputValue, string quantityTypeName, + string fromUnit, string toUnit) + { + UnitParser unitParser = UnitParser.Default; + Assert.Multiple(() => + { + var converter = new UnitConverter(unitParser); + + Assert.True(converter.TryConvertValueByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out QuantityValue result)); + Assert.Equal(expectedValue, result); + }, () => + { + var converter = UnitConverter.Create(unitParser, new QuantityConverterBuildOptions(defaultCachingMode: ConversionCachingMode.None, freeze: false)); + + Assert.True(converter.TryConvertValueByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out QuantityValue result)); + Assert.Equal(expectedValue, result); + }, () => + { + var converter = UnitConverter.Create(unitParser, new QuantityConverterBuildOptions(defaultCachingMode: ConversionCachingMode.None, freeze: true) + .WithCustomCachingOptions(new ConversionCacheOptions(cachingMode: ConversionCachingMode.All))); + + Assert.True(converter.TryConvertValueByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out QuantityValue result)); + Assert.Equal(expectedValue, result); + }); + } + + [Theory] + [InlineData(0, 0, LengthUnit.Meter, LengthUnit.Centimeter)] // base -> non-base (zero) + [InlineData(100, 1, LengthUnit.Meter, LengthUnit.Centimeter)] // base -> non-base + [InlineData(1, 1, LengthUnit.Centimeter, LengthUnit.Centimeter)] // same units (non-base) + [InlineData(1, 1000, MassUnit.Gram, MassUnit.Kilogram)] // non-base -> base + [InlineData(1000, 1, MassUnit.Gram, MassUnit.Milligram)] // non-base -> non-base + [InlineData(1000, 1, ElectricCurrentUnit.Kiloampere, ElectricCurrentUnit.Ampere)] + [InlineData(0.1, 10, AreaUnit.SquareCentimeter, ReciprocalAreaUnit.InverseSquareCentimeter)] // inverse relationship + public void Convert_ReturnsTrueOnSuccessAndOutputsResult(double expectedValue, double inputValue, Enum fromUnit, Enum toUnit) + { + QuantityValue convertedValue = UnitConverter.Convert(inputValue, fromUnit, toUnit); + Assert.Equal(expectedValue, convertedValue); + } + + [Theory] + [InlineData(0, 0, LengthUnit.Meter, LengthUnit.Centimeter)] // base -> non-base (zero) + [InlineData(100, 1, LengthUnit.Meter, LengthUnit.Centimeter)] // base -> non-base + [InlineData(1, 1, LengthUnit.Centimeter, LengthUnit.Centimeter)] // same units (non-base) + [InlineData(1, 1000, MassUnit.Gram, MassUnit.Kilogram)] // non-base -> base + [InlineData(1000, 1, MassUnit.Gram, MassUnit.Milligram)] // non-base -> non-base + [InlineData(1000, 1, ElectricCurrentUnit.Kiloampere, ElectricCurrentUnit.Ampere)] + [InlineData(0.1, 10, AreaUnit.SquareCentimeter, ReciprocalAreaUnit.InverseSquareCentimeter)] // inverse relationship + public void TryConvert_ReturnsTrueOnSuccessAndOutputsResult(double expectedValue, double inputValue, Enum fromUnit, Enum toUnit) { - Assert.True(UnitConverter.TryConvertByAbbreviation(inputValue, quantityTypeName, fromUnit, toUnit, out double result, culture), "TryConvertByAbbreviation() return value."); + Assert.True(UnitConverter.TryConvert(inputValue, fromUnit, toUnit, out QuantityValue result)); Assert.Equal(expectedValue, result); } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertValue_ShouldConvertValueToUnitWithinSameQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(UnitParser.Default, convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.All(Quantity.Infos, quantityInfo => + { + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + Enum fromUnit = fromUnitInfo.Value; + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + Enum toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertValue_ShouldConvertValueToUnitWithinSameQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(UnitParser.Default, convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.All(Quantity.Infos, quantityInfo => + { + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + Enum fromUnit = fromUnitInfo.Value; + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + Enum toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValue); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValue); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertValue_ShouldConvertValueToUnitWithinSameGenericQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(UnitParser.Default, convertOptions); + + QuantityValue valueToConvert = 123.45m; + QuantityInfo quantityInfo = Mass.Info; + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + MassUnit fromUnit = fromUnitInfo.Value; + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + MassUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertValue_ShouldConvertValueToUnitWithinSameGenericQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(UnitParser.Default, convertOptions); + + QuantityValue valueToConvert = 123.45m; + QuantityInfo quantityInfo = Mass.Info; + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + MassUnit fromUnit = fromUnitInfo.Value; + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + MassUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValueFromUnit); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValueFromUnit); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertTo_ShouldConvertQuantityToUnitWithinSameQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(UnitParser.Default, convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.All(Quantity.Infos, quantityInfo => + { + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + IQuantity quantityToConvert = fromUnitInfo.From(valueToConvert); + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + Enum toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + IQuantity convertedQuantity = converter.ConvertTo(quantityToConvert, toUnit); + + Assert.IsType(quantityInfo.QuantityType, convertedQuantity); + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_ShouldConvertQuantityToUnitWithinSameQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(UnitParser.Default, convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.All(Quantity.Infos, quantityInfo => + { + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + IQuantity quantityToConvert = fromUnitInfo.From(valueToConvert); + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + Enum toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + var success = converter.TryConvertTo(quantityToConvert, toUnit, out IQuantity? convertedQuantity); + + Assert.True(success); + Assert.IsType(quantityInfo.QuantityType, convertedQuantity); + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertTo_ShouldConvertQuantityToUnitWithinSameConcreteQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(UnitParser.Default, convertOptions); + + QuantityValue valueToConvert = 123.45m; + QuantityInfo quantityInfo = Temperature.Info; + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + Temperature quantityToConvert = fromUnitInfo.From(valueToConvert); + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + TemperatureUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + Temperature convertedQuantity = converter.ConvertToUnit(quantityToConvert, toUnit); + + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_ShouldConvertQuantityToUnitWithinSameConcreteQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(UnitParser.Default, convertOptions); + + QuantityValue valueToConvert = 123.45m; + QuantityInfo quantityInfo = Temperature.Info; + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + Temperature quantityToConvert = fromUnitInfo.From(valueToConvert); + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + TemperatureUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + var success = converter.TryConvertToUnit(quantityToConvert, toUnit, out Temperature convertedQuantity); + + Assert.True(success); + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertValue_ShouldConvertQuantityToUnitWithinSameConcreteQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(UnitParser.Default, convertOptions); + + QuantityValue valueToConvert = 123.45m; + QuantityInfo quantityInfo = Temperature.Info; + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + Temperature quantityToConvert = fromUnitInfo.From(valueToConvert); + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + TemperatureUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + var success = converter.TryConvertValue(quantityToConvert, toUnit, out QuantityValue convertedValue); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValue); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertValue_ShouldThrowUnitNotFoundExceptionForUnknownUnits(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Length.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.Throws(() => converter.ConvertValue(valueToConvert, MassUnit.Gram, MassUnit.Milligram)); + }, + () => + { + Assert.Throws(() => converter.ConvertValue(new Mass(valueToConvert, MassUnit.Gram), MassUnit.Milligram)); + }, + () => + { + Assert.Throws(() => converter.ConvertValue(valueToConvert, Mass.BaseUnit, Length.BaseUnit)); + Assert.Throws(() => converter.ConvertValue(valueToConvert, Length.BaseUnit, Mass.BaseUnit)); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertValue_ShouldReturnFalseForUnknownUnits(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Length.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.False(converter.TryConvertValue(valueToConvert, MassUnit.Gram, MassUnit.Milligram, out _)); + }, + () => + { + Assert.False(converter.TryConvertValue(new Mass(valueToConvert, MassUnit.Gram), MassUnit.Milligram, out _)); + }, + () => + { + Assert.False(converter.TryConvertValue(valueToConvert, Mass.BaseUnit, Length.BaseUnit, out _)); + Assert.False(converter.TryConvertValue(valueToConvert, Length.BaseUnit, Mass.BaseUnit, out _)); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertTo_ShouldThrowUnitNotFoundExceptionForUnknownUnits(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Length.Info]), convertOptions); + + Assert.Multiple(() => + { + var quantityToConvert = new Mass(1, MassUnit.Gram); + Assert.Throws(() => converter.ConvertToUnit(quantityToConvert, MassUnit.Milligram)); + }, + () => + { + IQuantity quantityToConvert = new Mass(1, MassUnit.Gram); + Assert.Throws(() => converter.ConvertTo(quantityToConvert, MassUnit.Milligram)); + }, + () => + { + var quantityToConvert = new Length(1, LengthUnit.Meter); + Assert.Throws(() => converter.ConvertTo(quantityToConvert, MassUnit.Milligram)); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_ShouldReturnFalseForUnknownUnits(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Length.Info]), convertOptions); + + Assert.Multiple(() => + { + var quantityToConvert = new Mass(1, MassUnit.Gram); + var success = converter.TryConvertToUnit(quantityToConvert, MassUnit.Milligram, out Mass _); + Assert.False(success); + }, + () => + { + IQuantity quantityToConvert = new Mass(1, MassUnit.Gram); + var success = converter.TryConvertTo(quantityToConvert, MassUnit.Milligram, out IQuantity? _); + Assert.False(success); + }, + () => + { + var quantityToConvert = new Length(1, LengthUnit.Meter); + var success = converter.TryConvertTo(quantityToConvert, MassUnit.Milligram, out IQuantity? _); + Assert.False(success); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertTo_UnknownRelation_Throws_InvalidConversionException(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Length.Info, Mass.Info]), convertOptions); + + Assert.Multiple(() => + { + // left to right + Assert.Throws(() => converter.ConvertTo(Length.Zero, MassUnit.Milligram)); + }, + () => + { + // right to left + Assert.Throws(() => converter.ConvertTo(Mass.Zero, LengthUnit.Meter)); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_UnknownRelation_ReturnsFalse(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Length.Info, Mass.Info]), convertOptions); + + Assert.Multiple(() => + { + var success = converter.TryConvertTo(Length.Zero, MassUnit.Milligram, out IQuantity? _); + Assert.False(success); + }, + () => + { + var success = converter.TryConvertTo(Mass.Zero, LengthUnit.Meter, out IQuantity? _); + Assert.False(success); + }); + } + + [Theory] + [InlineData( true,true)] + [InlineData( true,false)] + [InlineData(false,true)] + [InlineData(false,false)] + public void ConvertTo_QuantityWithIncompatibleDimensions_Throws_InvalidConversionException(bool freeze, bool reduceConstants) + { + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, ConversionCachingMode.None, reduceConstants) + // no conversion expressions can be determined using the base dimensions (a conversion function needs to be explicitly provided) + .WithImplicitConversionOptions(options => options.SetCustomConversion()); + var converter = UnitConverter.Create(new UnitParser([Length.Info, Mass.Info]), convertOptions); + + Assert.Multiple(() => + { + // left to right + Assert.Throws(() => converter.ConvertTo(Length.Zero, MassUnit.Milligram)); + }, + () => + { + // right to left + Assert.Throws(() => converter.ConvertTo(Mass.Zero, LengthUnit.Meter)); + }); + } + + [Theory] + [InlineData( true,true)] + [InlineData( true,false)] + [InlineData(false,true)] + [InlineData(false,false)] + public void TryConvertTo_QuantityWithIncompatibleDimensions_ReturnsFalse(bool freeze, bool reduceConstants) + { + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, ConversionCachingMode.None, reduceConstants) + // no conversion expressions can be determined using the base dimensions (a conversion function needs to be explicitly provided) + .WithImplicitConversionOptions(options => options.SetCustomConversion()); + var converter = UnitConverter.Create(new UnitParser([Length.Info, Mass.Info]), convertOptions); + + Assert.Multiple(() => + { + var success = converter.TryConvertTo(Length.Zero, MassUnit.Milligram, out IQuantity? _); + Assert.False(success); + }, + () => + { + var success = converter.TryConvertTo(Mass.Zero, LengthUnit.Meter, out IQuantity? _); + Assert.False(success); + }); + } + + [Theory] + [InlineData( true,true)] + [InlineData( true,false)] + [InlineData(false,true)] + [InlineData(false,false)] + public void ConvertTo_QuantityWithoutBaseUnits_Throws_InvalidConversionException(bool freeze, bool reduceConstants) + { + // we simulate a target quantity without any base units + var densityInfo = Density.DensityInfo.CreateDefault(unitInfos => + unitInfos.Select(x => new UnitDefinition(x.Value, x.PluralName, BaseUnits.Undefined))); + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, ConversionCachingMode.None, reduceConstants) + // no conversion expressions can be determined without the base units (a conversion function needs to be explicitly provided) + .WithImplicitConversionOptions(options => options.SetCustomConversion()); + var converter = UnitConverter.Create(new UnitParser([densityInfo, MassConcentration.Info]), convertOptions); + + Assert.Multiple(() => + { + // left to right + Assert.Throws(() => converter.ConvertTo(Density.Zero, MassConcentrationUnit.KilogramPerCubicMeter)); + }, + () => + { + // right to left + Assert.Throws(() => converter.ConvertTo(MassConcentration.Zero, DensityUnit.KilogramPerCubicMeter)); + }); + } + + [Theory] + [InlineData( true,true)] + [InlineData( true,false)] + [InlineData(false,true)] + [InlineData(false,false)] + public void TryConvertTo_QuantityWithoutBaseUnits_ReturnsFalse(bool freeze, bool reduceConstants) + { + // we simulate a target quantity without any base units + var densityInfo = Density.DensityInfo.CreateDefault(unitInfos => + unitInfos.Select(x => new UnitDefinition(x.Value, x.PluralName, BaseUnits.Undefined))); + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, ConversionCachingMode.None, reduceConstants) + // no conversion expressions can be determined without the base units (a conversion function needs to be explicitly provided) + .WithImplicitConversionOptions(options => options.SetCustomConversion()); + var converter = UnitConverter.Create(new UnitParser([densityInfo, MassConcentration.Info]), convertOptions); + + Assert.Multiple(() => + { + var success = converter.TryConvertTo(Density.Zero, MassConcentrationUnit.KilogramPerCubicMeter, out IQuantity? _); + Assert.False(success); + }, + () => + { + var success = converter.TryConvertTo(MassConcentration.Zero, DensityUnit.KilogramPerCubicMeter, out IQuantity? _); + Assert.False(success); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertValue_ShouldConvertValueForCustomQuantityToUnitWithinSameQuantity(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Mass.Info, HowMuch.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + QuantityInfo quantityInfo = Mass.Info; + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + MassUnit fromUnit = fromUnitInfo.Value; + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + MassUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + }, + () => + { + QuantityInfo quantityInfo = HowMuch.Info; + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + Enum fromUnit = fromUnitInfo.Value; + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + Enum toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertValue_ShouldConvertValueForCustomQuantityToUnitWithinSameQuantity(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Mass.Info, HowMuch.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + QuantityInfo quantityInfo = Mass.Info; + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + MassUnit fromUnit = fromUnitInfo.Value; + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + MassUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValue); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValue); + }); + }); + }, + () => + { + QuantityInfo quantityInfo = HowMuch.Info; + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + Enum fromUnit = fromUnitInfo.Value; + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + Enum toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValue); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValue); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertTo_ShouldConvertCustomQuantityToUnitWithinSameQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Mass.Info, HowMuch.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + QuantityInfo quantityInfo = Mass.Info; + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + Mass quantityToConvert = fromUnitInfo.From(valueToConvert); + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + MassUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + Mass convertedQuantity = converter.ConvertToUnit(quantityToConvert, toUnit); + + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }); + }, + () => + { + QuantityInfo quantityInfo = HowMuch.Info; + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + IQuantity quantityToConvert = fromUnitInfo.From(valueToConvert); + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + Enum toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + IQuantity convertedQuantity = converter.ConvertTo(quantityToConvert, toUnit); + + Assert.IsType(convertedQuantity); + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_ShouldConvertCustomQuantityToUnitWithinSameQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Mass.Info, HowMuch.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + QuantityInfo quantityInfo = Mass.Info; + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + Mass quantityToConvert = fromUnitInfo.From(valueToConvert); + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + MassUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + var success = converter.TryConvertToUnit(quantityToConvert, toUnit, out Mass convertedQuantity); + + Assert.True(success); + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }); + }, + () => + { + QuantityInfo quantityInfo = HowMuch.Info; + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + IQuantity quantityToConvert = fromUnitInfo.From(valueToConvert); + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + Enum toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + var success = converter.TryConvertTo(quantityToConvert, toUnit, out IQuantity? convertedQuantity); + + Assert.True(success); + Assert.IsType(convertedQuantity); + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertValue_ShouldConvertCustomQuantityToUnitWithinSameQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Mass.Info, HowMuch.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + QuantityInfo quantityInfo = Mass.Info; + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + Mass quantityToConvert = fromUnitInfo.From(valueToConvert); + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + MassUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + QuantityValue convertedValue = converter.ConvertValue(quantityToConvert, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertValue_ShouldConvertCustomQuantityToUnitWithinSameQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Mass.Info, HowMuch.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + QuantityInfo quantityInfo = Mass.Info; + Assert.All(quantityInfo.UnitInfos, fromUnitInfo => + { + Mass quantityToConvert = fromUnitInfo.From(valueToConvert); + Assert.All(quantityInfo.UnitInfos, toUnitInfo => + { + MassUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(valueToConvert, fromUnitInfo); + + var success = converter.TryConvertValue(quantityToConvert, toUnit, out QuantityValue convertedValue); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValue); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertValue_ShouldConvertValueToUnitOfAnotherQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info, SpecificVolume.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(Density.Info.UnitInfos, fromUnitInfo => + { + DensityUnit fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = SpecificVolume.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + SpecificVolumeUnit toUnit = toUnitInfo.Value; + SpecificVolume expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + }, + () => + { + Assert.All(SpecificVolume.Info.UnitInfos, fromUnitInfo => + { + SpecificVolumeUnit fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = Density.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + DensityUnit toUnit = toUnitInfo.Value; + Density expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertValue_ShouldConvertValueToUnitOfAnotherQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info, SpecificVolume.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(Density.Info.UnitInfos, fromUnitInfo => + { + DensityUnit fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = SpecificVolume.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + SpecificVolumeUnit toUnit = toUnitInfo.Value; + SpecificVolume expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValueFromUnit); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValueFromUnit); + }); + }); + }, + () => + { + Assert.All(SpecificVolume.Info.UnitInfos, fromUnitInfo => + { + SpecificVolumeUnit fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = Density.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + DensityUnit toUnit = toUnitInfo.Value; + Density expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValueFromUnit); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValueFromUnit); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertValue_ShouldConvertValueToUnitOfAnotherQuantityWithCustomConversion(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => + // since the dimensions of the two quantities are compatible and there is at least one pair of units that have the same BaseUnits (in our case these are the Mass.Tonne and HowMuch.ATon) + // we don't have to specify a conversion expression (it is assumed that "1 Tonne" is equal to "1 ATon") + options.SetCustomConversion()); + var converter = UnitConverter.Create(new UnitParser([Mass.Info, HowMuch.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(Mass.Info.UnitInfos, fromUnitInfo => + { + MassUnit fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = HowMuch.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + Enum toUnit = toUnitInfo.Value; + IQuantity expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + }, + () => + { + Assert.All(HowMuch.Info.UnitInfos, fromUnitInfo => + { + Enum fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = Mass.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + MassUnit toUnit = toUnitInfo.Value; + Mass expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertValue_ShouldConvertValueToUnitOfAnotherQuantityWithCustomConversion(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => + // since the dimensions of the two quantities are compatible and there is at least one pair of units that have the same BaseUnits (in our case these are the Mass.Tonne and HowMuch.ATon) + // we don't have to specify a conversion expression (it is assumed that "1 Tonne" is equal to "1 ATon") + options.SetCustomConversion()); + var converter = UnitConverter.Create(new UnitParser([Mass.Info, HowMuch.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(Mass.Info.UnitInfos, fromUnitInfo => + { + MassUnit fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = HowMuch.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + Enum toUnit = toUnitInfo.Value; + IQuantity expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValueFromUnit); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValueFromUnit); + }); + }); + }, + () => + { + Assert.All(HowMuch.Info.UnitInfos, fromUnitInfo => + { + Enum fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = Mass.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + MassUnit toUnit = toUnitInfo.Value; + Mass expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValueFromUnit); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValueFromUnit); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertTo_ShouldConvertValueToUnitOfAnotherQuantityWithCustomConversion(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => + // since the dimensions of the two quantities are compatible and there is at least one pair of units that have the same BaseUnits (in our case these are the Mass.Tonne and HowMuch.ATon) + // we don't have to specify a conversion expression (it is assumed that "1 Tonne" is equal to "1 ATon") + options.SetCustomConversion()); + var converter = UnitConverter.Create(new UnitParser([Mass.Info, HowMuch.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(Mass.Info.UnitInfos, fromUnitInfo => + { + var quantityToConvert = new Mass(valueToConvert, fromUnitInfo.Value); + QuantityInfo toQuantityInfo = HowMuch.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + Enum toUnit = toUnitInfo.Value; + IQuantity expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + IQuantity convertedQuantity = converter.ConvertTo(quantityToConvert, toUnit); + + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }); + }, + () => + { + Assert.All(HowMuch.Info.UnitInfos, fromUnitInfo => + { + var quantityToConvert = new HowMuch(valueToConvert, fromUnitInfo.Value); + QuantityInfo toQuantityInfo = Mass.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + MassUnit toUnit = toUnitInfo.Value; + Mass expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + IQuantity convertedQuantity = converter.ConvertTo(quantityToConvert, toUnit); + + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_ShouldConvertValueToUnitOfAnotherQuantityWithCustomConversion(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => + // since the dimensions of the two quantities are compatible and there is at least one pair of units that have the same BaseUnits (in our case these are the Mass.Tonne and HowMuch.ATon) + // we don't have to specify a conversion expression (it is assumed that "1 Tonne" is equal to "1 ATon") + options.SetCustomConversion()); + var converter = UnitConverter.Create(new UnitParser([Mass.Info, HowMuch.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(Mass.Info.UnitInfos, fromUnitInfo => + { + var quantityToConvert = new Mass(valueToConvert, fromUnitInfo.Value); + QuantityInfo toQuantityInfo = HowMuch.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + Enum toUnit = toUnitInfo.Value; + IQuantity expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + var success = converter.TryConvertTo(quantityToConvert, toUnit, out IQuantity? convertedQuantity); + + Assert.True(success); + Assert.Equal(toUnit, convertedQuantity!.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }); + }, + () => + { + Assert.All(HowMuch.Info.UnitInfos, fromUnitInfo => + { + var quantityToConvert = new HowMuch(valueToConvert, fromUnitInfo.Value); + QuantityInfo toQuantityInfo = Mass.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + MassUnit toUnit = toUnitInfo.Value; + Mass expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + var success = converter.TryConvertTo(quantityToConvert, toUnit, out IQuantity? convertedQuantity); + + Assert.True(success); + Assert.Equal(toUnit, convertedQuantity!.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertValue_ShouldConvertValueToUnitOfAnotherQuantityWithCustomConversionViaBase(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + // unlike the conversion between HowMuch and Mass where HowMuch.BaseUnitInfo.BaseUnits == Undefined + // here we have: Density.BaseUnitInfo.BaseUnits == MassConcentration.BaseUnitInfo.BaseUnits (an optimized scenario) + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => + // since the dimensions of the two quantities are compatible and there is at least one pair of units that have the same BaseUnits + // we don't have to specify a conversion expression (it is assumed that "1 Density.BaseUnit" is equal to "1 MassConcentration.BaseUnit") + options.SetCustomConversion()); + var converter = UnitConverter.Create(new UnitParser([Density.Info, MassConcentration.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(Density.Info.UnitInfos, fromUnitInfo => + { + DensityUnit fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = MassConcentration.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + MassConcentrationUnit toUnit = toUnitInfo.Value; + MassConcentration expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + }, + () => + { + Assert.All(MassConcentration.Info.UnitInfos, fromUnitInfo => + { + MassConcentrationUnit fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = Density.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + DensityUnit toUnit = toUnitInfo.Value; + Density expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertValue_ShouldConvertValueToUnitOfAnotherQuantityWithCustomConversionViaBase(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + // unlike the conversion between HowMuch and Mass where HowMuch.BaseUnitInfo.BaseUnits == Undefined + // here we have: Density.BaseUnitInfo.BaseUnits == MassConcentration.BaseUnitInfo.BaseUnits (an optimized scenario) + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => + // since the dimensions of the two quantities are compatible and there is at least one pair of units that have the same BaseUnits + // we don't have to specify a conversion expression (it is assumed that "1 Density.BaseUnit" is equal to "1 MassConcentration.BaseUnit") + options.SetCustomConversion()); + var converter = UnitConverter.Create(new UnitParser([Density.Info, MassConcentration.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(Density.Info.UnitInfos, fromUnitInfo => + { + DensityUnit fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = MassConcentration.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + MassConcentrationUnit toUnit = toUnitInfo.Value; + MassConcentration expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValueFromUnit); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValueFromUnit); + }); + }); + }, + () => + { + Assert.All(MassConcentration.Info.UnitInfos, fromUnitInfo => + { + MassConcentrationUnit fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = Density.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + DensityUnit toUnit = toUnitInfo.Value; + Density expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValueFromUnit); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValueFromUnit); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertValue_ShouldConvertValueToUnitOfAnotherDimensionlessQuantityWithCustomConversion(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => + // since both quantities are dimensionless it is assumed that the quantities can be converted using their BaseUnit (i.e. the DecimalFraction) + options.SetCustomConversion()); + var converter = UnitConverter.Create(new UnitParser([MassFraction.Info, Ratio.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(MassFraction.Info.UnitInfos, fromUnitInfo => + { + MassFractionUnit fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = Ratio.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + RatioUnit toUnit = toUnitInfo.Value; + Ratio expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + }, + () => + { + Assert.All(Ratio.Info.UnitInfos, fromUnitInfo => + { + RatioUnit fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = MassFraction.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + MassFractionUnit toUnit = toUnitInfo.Value; + MassFraction expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertValue_ShouldConvertValueToUnitOfAnotherDimensionlessQuantityWithCustomConversion(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => + // since both quantities are dimensionless it is assumed that the quantities can be converted using their BaseUnit (i.e. the DecimalFraction) + options.SetCustomConversion()); + var converter = UnitConverter.Create(new UnitParser([MassFraction.Info, Ratio.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(MassFraction.Info.UnitInfos, fromUnitInfo => + { + MassFractionUnit fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = Ratio.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + RatioUnit toUnit = toUnitInfo.Value; + Ratio expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValue); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValue); + }); + }); + }, + () => + { + Assert.All(Ratio.Info.UnitInfos, fromUnitInfo => + { + RatioUnit fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = MassFraction.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + MassFractionUnit toUnit = toUnitInfo.Value; + MassFraction expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, toQuantityInfo[expectedQuantity.Unit]); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValue); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValue); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertValue_ShouldConvertValueToUnitOfAnotherQuantityWithCustomConversionExpression(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => options + // since the dimensions / base units are incompatible we have to explicitly specify a conversion expression + .SetCustomConversion() + .SetCustomConversion(VolumeUnit.Liter, HowMuchUnit.Some, QuantityValue.One, true)); + var converter = UnitConverter.Create(new UnitParser([Volume.Info, HowMuch.Info]), convertOptions); + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(Volume.Info.UnitInfos, fromUnitInfo => + { + VolumeUnit fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = HowMuch.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + Enum toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(Volume.Info[VolumeUnit.Liter].GetValueFrom(valueToConvert, fromUnitInfo), toQuantityInfo[HowMuchUnit.Some]); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + }, + () => + { + Assert.All(HowMuch.Info.UnitInfos, fromUnitInfo => + { + Enum fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = Volume.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + VolumeUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(HowMuch.Info[HowMuchUnit.Some].GetValueFrom(valueToConvert, fromUnitInfo), toQuantityInfo[VolumeUnit.Liter]); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertValue_ShouldConvertValueToUnitOfAnotherQuantityWithCustomConversionExpression(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => options + // since the dimensions / base units are incompatible we have to explicitly specify a conversion expression + .SetCustomConversion() + .SetCustomConversion(VolumeUnit.Liter, HowMuchUnit.Some, QuantityValue.One, true)); + var converter = UnitConverter.Create(new UnitParser([Volume.Info, HowMuch.Info]), convertOptions); + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(Volume.Info.UnitInfos, fromUnitInfo => + { + VolumeUnit fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = HowMuch.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + Enum toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(Volume.Info[VolumeUnit.Liter].GetValueFrom(valueToConvert, fromUnitInfo), toQuantityInfo[HowMuchUnit.Some]); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValue); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValue); + }); + }); + }, + () => + { + Assert.All(HowMuch.Info.UnitInfos, fromUnitInfo => + { + Enum fromUnit = fromUnitInfo.Value; + QuantityInfo toQuantityInfo = Volume.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + VolumeUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(HowMuch.Info[HowMuchUnit.Some].GetValueFrom(valueToConvert, fromUnitInfo), toQuantityInfo[VolumeUnit.Liter]); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValue); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValue); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertTo_ShouldConvertQuantityToUnitOfAnotherQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info, SpecificVolume.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(Density.Info.UnitInfos, fromUnitInfo => + { + Density quantityToConvert = fromUnitInfo.From(valueToConvert); + QuantityInfo toQuantityInfo = SpecificVolume.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + SpecificVolumeUnit toUnit = toUnitInfo.Value; + SpecificVolume expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + + // note that passing a unit of another quantity forces us into the IQuantity overload + IQuantity convertedQuantity = converter.ConvertTo(quantityToConvert, toUnit); + + Assert.Equal(expectedQuantity, convertedQuantity); + Assert.Equal(toUnit, convertedQuantity.Unit); + }); + }); + }, + () => + { + Assert.All(SpecificVolume.Info.UnitInfos, fromUnitInfo => + { + SpecificVolume quantityToConvert = fromUnitInfo.From(valueToConvert); + QuantityInfo toQuantityInfo = Density.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + DensityUnit toUnit = toUnitInfo.Value; + Density expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + + // note that passing a unit of another quantity forces us into the IQuantity overload + IQuantity convertedQuantity = converter.ConvertTo(quantityToConvert, toUnit); + + Assert.Equal(expectedQuantity, convertedQuantity); + Assert.Equal(toUnit, convertedQuantity.Unit); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_ShouldConvertQuantityToUnitOfAnotherQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info, SpecificVolume.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(Density.Info.UnitInfos, fromUnitInfo => + { + Density quantityToConvert = fromUnitInfo.From(valueToConvert); + QuantityInfo toQuantityInfo = SpecificVolume.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + SpecificVolumeUnit toUnit = toUnitInfo.Value; + SpecificVolume expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + + // note that passing a unit of another quantity forces us into the IQuantity overload + IQuantity convertedQuantity = converter.ConvertTo(quantityToConvert, toUnit); + + Assert.Equal(expectedQuantity, convertedQuantity); + Assert.Equal(toUnit, convertedQuantity.Unit); + }); + }); + }, + () => + { + Assert.All(SpecificVolume.Info.UnitInfos, fromUnitInfo => + { + SpecificVolume quantityToConvert = fromUnitInfo.From(valueToConvert); + QuantityInfo toQuantityInfo = Density.Info; + Assert.All(toQuantityInfo.UnitInfos, toUnitInfo => + { + DensityUnit toUnit = toUnitInfo.Value; + Density expectedQuantity = toQuantityInfo.ConvertFrom(valueToConvert, fromUnitInfo); + + // note that passing a unit of another quantity forces us into the IQuantity overload + IQuantity convertedQuantity = converter.ConvertTo(quantityToConvert, toUnit); + + Assert.Equal(expectedQuantity, convertedQuantity); + Assert.Equal(toUnit, convertedQuantity.Unit); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertValue_WithCustomConversionExpression_ShouldConvertValueToUnitOfAnotherQuantity(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var customConversionFromDensity = new ConversionExpression(new QuantityValue(-1, 2)); + var customConversionFromSpecificVolume = new ConversionExpression(-2); + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => + { + options.SetCustomConversion(DensityUnit.MicrogramPerLiter, SpecificVolumeUnit.CubicFootPerPound, customConversionFromDensity); + options.SetCustomConversion(SpecificVolumeUnit.CubicFootPerPound, DensityUnit.MicrogramPerLiter, customConversionFromSpecificVolume); + }); + var converter = UnitConverter.Create(new UnitParser([Density.Info, SpecificVolume.Info]), convertOptions); + + UnitInfo customDensityInfo = Density.Info[DensityUnit.MicrogramPerLiter]; + UnitInfo customSpecificVolumeInfo = SpecificVolume.Info[SpecificVolumeUnit.CubicFootPerPound]; + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + // when the left unit is the customDensityInfo + DensityUnit fromUnit = customDensityInfo.Value; + Assert.All(SpecificVolume.Info.UnitInfos, toUnitInfo => + { + SpecificVolumeUnit toUnit = toUnitInfo.Value; + // (123.45, customDensityInfo) => (-123.45/2, customSpecificVolumeInfo) => ConvertValue((-123.45/2, customSpecificVolumeInfo), toUnitInfo) + QuantityValue expectedValue = toUnitInfo.GetValueFrom(customConversionFromDensity.Evaluate(valueToConvert), customSpecificVolumeInfo); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }, + () => + { + // all other density units are also converted using our custom conversion expression + Assert.All(Density.Info.UnitInfos.Where(info => info != customDensityInfo), fromUnitInfo => + { + DensityUnit fromUnit = fromUnitInfo.Value; + Assert.All(SpecificVolume.Info.UnitInfos, toUnitInfo => + { + SpecificVolumeUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(customConversionFromDensity.Evaluate(customDensityInfo.GetValueFrom(valueToConvert, fromUnitInfo)), customSpecificVolumeInfo); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + }, + () => + { + // when the left unit is the customSpecificVolumeInfo + SpecificVolumeUnit fromUnit = customSpecificVolumeInfo.Value; + Assert.All(Density.Info.UnitInfos, toUnitInfo => + { + DensityUnit toUnit = toUnitInfo.Value; + // (123.45, customSpecificVolumeInfo) => (-123.45 * 2, customDensityInfo) => ConvertValue((-123.45 * 2, customDensityInfo), toUnitInfo) + QuantityValue expectedValue = toUnitInfo.GetValueFrom(customConversionFromSpecificVolume.Evaluate(valueToConvert), customDensityInfo); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }, () => + { + // all other specific-volume units are also converted using our custom conversion expression + Assert.All(SpecificVolume.Info.UnitInfos.Where(info => info != customSpecificVolumeInfo), fromUnitInfo => + { + SpecificVolumeUnit fromUnit = fromUnitInfo.Value; + Assert.All(Density.Info.UnitInfos, toUnitInfo => + { + DensityUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(customConversionFromSpecificVolume.Evaluate(customSpecificVolumeInfo.GetValueFrom(valueToConvert, fromUnitInfo)), customDensityInfo); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertValue_WithCustomConversionFunction_ShouldConvertValueToUnitOfAnotherQuantity(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + // note: unlike the ConversionExpression, the overload using a lambda function won't be able to create the same "single-operation" conversions (there is always going to be an extra call to the NestedFunction) + ConvertValueDelegate customConversionFromDensity = value => -value / 2; + ConvertValueDelegate customConversionFromSpecificVolume = value => -value * 2; + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => + { + options.SetCustomConversion(DensityUnit.MicrogramPerLiter, SpecificVolumeUnit.CubicFootPerPound, customConversionFromDensity); + options.SetCustomConversion(SpecificVolumeUnit.CubicFootPerPound, DensityUnit.MicrogramPerLiter, customConversionFromSpecificVolume); + }); + var converter = UnitConverter.Create(new UnitParser([Density.Info, SpecificVolume.Info]), convertOptions); + + UnitInfo customDensityInfo = Density.Info[DensityUnit.MicrogramPerLiter]; + UnitInfo customSpecificVolumeInfo = SpecificVolume.Info[SpecificVolumeUnit.CubicFootPerPound]; + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + // when the left unit is the customDensityInfo + DensityUnit fromUnit = customDensityInfo.Value; + Assert.All(SpecificVolume.Info.UnitInfos, toUnitInfo => + { + SpecificVolumeUnit toUnit = toUnitInfo.Value; + // (123.45, customDensityInfo) => (-123.45/2, customSpecificVolumeInfo) => ConvertValue((-123.45/2, customSpecificVolumeInfo), toUnitInfo) + QuantityValue expectedValue = toUnitInfo.GetValueFrom(customConversionFromDensity(valueToConvert), customSpecificVolumeInfo); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }, + () => + { + // all other density units are also converted using our custom conversion function + Assert.All(Density.Info.UnitInfos.Where(info => info != customDensityInfo), fromUnitInfo => + { + DensityUnit fromUnit = fromUnitInfo.Value; + Assert.All(SpecificVolume.Info.UnitInfos, toUnitInfo => + { + SpecificVolumeUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(customConversionFromDensity(customDensityInfo.GetValueFrom(valueToConvert, fromUnitInfo)), customSpecificVolumeInfo); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + }, + () => + { + // when the left unit is the customSpecificVolumeInfo + SpecificVolumeUnit fromUnit = customSpecificVolumeInfo.Value; + Assert.All(Density.Info.UnitInfos, toUnitInfo => + { + DensityUnit toUnit = toUnitInfo.Value; + // (123.45, customSpecificVolumeInfo) => (-123.45 * 2, customDensityInfo) => ConvertValue((-123.45 * 2, customDensityInfo), toUnitInfo) + QuantityValue expectedValue = toUnitInfo.GetValueFrom(customConversionFromSpecificVolume(valueToConvert), customDensityInfo); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }, () => + { + // all other specific-volume units are also converted using our custom conversion function + Assert.All(SpecificVolume.Info.UnitInfos.Where(info => info != customSpecificVolumeInfo), fromUnitInfo => + { + SpecificVolumeUnit fromUnit = fromUnitInfo.Value; + Assert.All(Density.Info.UnitInfos, toUnitInfo => + { + DensityUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(customConversionFromSpecificVolume(customSpecificVolumeInfo.GetValueFrom(valueToConvert, fromUnitInfo)), customDensityInfo); + + QuantityValue convertedValue = converter.ConvertValue(valueToConvert, fromUnit, toUnit); + + Assert.Equal(expectedValue, convertedValue); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertValue_WithCustomConversionExpression_ShouldConvertValueToUnitOfAnotherQuantity(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var customConversionFromDensity = new ConversionExpression(new QuantityValue(-1, 2)); + var customConversionFromSpecificVolume = new ConversionExpression(-2); + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => + { + options.SetCustomConversion(DensityUnit.MicrogramPerLiter, SpecificVolumeUnit.CubicFootPerPound, customConversionFromDensity); + options.SetCustomConversion(SpecificVolumeUnit.CubicFootPerPound, DensityUnit.MicrogramPerLiter, customConversionFromSpecificVolume); + }); + var converter = UnitConverter.Create(new UnitParser([Density.Info, SpecificVolume.Info]), convertOptions); + + UnitInfo customDensityInfo = Density.Info[DensityUnit.MicrogramPerLiter]; + UnitInfo customSpecificVolumeInfo = SpecificVolume.Info[SpecificVolumeUnit.CubicFootPerPound]; + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + // when the left unit is the customDensityInfo + DensityUnit fromUnit = customDensityInfo.Value; + Assert.All(SpecificVolume.Info.UnitInfos, toUnitInfo => + { + SpecificVolumeUnit toUnit = toUnitInfo.Value; + // (123.45, customDensityInfo) => (-123.45/2, customSpecificVolumeInfo) => ConvertValue((-123.45/2, customSpecificVolumeInfo), toUnitInfo) + QuantityValue expectedValue = toUnitInfo.GetValueFrom(customConversionFromDensity.Evaluate(valueToConvert), customSpecificVolumeInfo); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValue); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValue); + }); + }, + () => + { + // all other density units are also converted using our custom conversion expression (possibly resulting in a different unit) + Assert.All(Density.Info.UnitInfos.Where(info => info != customDensityInfo), fromUnitInfo => + { + DensityUnit fromUnit = fromUnitInfo.Value; + Assert.All(SpecificVolume.Info.UnitInfos, toUnitInfo => + { + SpecificVolumeUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(customConversionFromDensity.Evaluate(customDensityInfo.GetValueFrom(valueToConvert, fromUnitInfo)), customSpecificVolumeInfo); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValue); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValue); + }); + }); + }, + () => + { + // when the left unit is the customSpecificVolumeInfo + SpecificVolumeUnit fromUnit = customSpecificVolumeInfo.Value; + Assert.All(Density.Info.UnitInfos, toUnitInfo => + { + DensityUnit toUnit = toUnitInfo.Value; + // (123.45, customSpecificVolumeInfo) => (-123.45 * 2, customDensityInfo) => ConvertValue((-123.45 * 2, customDensityInfo), toUnitInfo) + QuantityValue expectedValue = toUnitInfo.GetValueFrom(customConversionFromSpecificVolume.Evaluate(valueToConvert), customDensityInfo); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValue); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValue); + }); + }, () => + { + // all other specific-volume units are also converted using our custom conversion expression (possibly resulting in a different unit) + Assert.All(SpecificVolume.Info.UnitInfos.Where(info => info != customSpecificVolumeInfo), fromUnitInfo => + { + SpecificVolumeUnit fromUnit = fromUnitInfo.Value; + Assert.All(Density.Info.UnitInfos, toUnitInfo => + { + DensityUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(customConversionFromSpecificVolume.Evaluate(customSpecificVolumeInfo.GetValueFrom(valueToConvert, fromUnitInfo)), customDensityInfo); + + var success = converter.TryConvertValue(valueToConvert, fromUnit, toUnit, out QuantityValue convertedValue); + + Assert.True(success); + Assert.Equal(expectedValue, convertedValue); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertTo_WithCustomConversionExpression_ShouldConvertQuantityToUnitOfAnotherQuantity(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var customConversionFromDensity = new ConversionExpression(new QuantityValue(-1, 2)); + var customConversionFromSpecificVolume = new ConversionExpression(-2); + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => + { + options.SetCustomConversion(DensityUnit.MicrogramPerLiter, SpecificVolumeUnit.CubicFootPerPound, customConversionFromDensity); + options.SetCustomConversion(SpecificVolumeUnit.CubicFootPerPound, DensityUnit.MicrogramPerLiter, customConversionFromSpecificVolume); + }); + var converter = UnitConverter.Create(new UnitParser([Density.Info, SpecificVolume.Info]), convertOptions); + + UnitInfo customDensityInfo = Density.Info[DensityUnit.MicrogramPerLiter]; + UnitInfo customSpecificVolumeInfo = SpecificVolume.Info[SpecificVolumeUnit.CubicFootPerPound]; + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + // when the left unit is the customDensityInfo + Density quantityToConvert = customDensityInfo.From(valueToConvert); + Assert.All(SpecificVolume.Info.UnitInfos, toUnitInfo => + { + SpecificVolumeUnit toUnit = toUnitInfo.Value; + // (123.45, customDensityInfo) => (-123.45/2, customSpecificVolumeInfo) => ConvertValue((-123.45/2, customSpecificVolumeInfo), toUnitInfo) + QuantityValue expectedValue = toUnitInfo.GetValueFrom(customConversionFromDensity.Evaluate(valueToConvert), customSpecificVolumeInfo); + + IQuantity convertedQuantity = converter.ConvertTo(quantityToConvert, toUnit); + + Assert.IsType(convertedQuantity); + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }, + () => + { + // all other density units are also converted using our custom conversion expression (possibly resulting in a different unit) + Assert.All(Density.Info.UnitInfos.Where(info => info != customDensityInfo), fromUnitInfo => + { + Density quantityToConvert = fromUnitInfo.From(valueToConvert); + Assert.All(SpecificVolume.Info.UnitInfos, toUnitInfo => + { + SpecificVolumeUnit toUnit = toUnitInfo.Value; + SpecificVolume expectedQuantity = customSpecificVolumeInfo.From(customConversionFromDensity.Evaluate(customDensityInfo.GetValueFrom(valueToConvert, fromUnitInfo))); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, customSpecificVolumeInfo); + + IQuantity convertedQuantity = converter.ConvertTo(quantityToConvert, toUnit); + + Assert.IsType(convertedQuantity); + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }); + }, + () => + { + // when the left unit is the customSpecificVolumeInfo + SpecificVolume quantityToConvert = customSpecificVolumeInfo.From(valueToConvert); + Assert.All(Density.Info.UnitInfos, toUnitInfo => + { + DensityUnit toUnit = toUnitInfo.Value; + // (123.45, customSpecificVolumeInfo) => (-123.45 * 2, customDensityInfo) => ConvertValue((-123.45 * 2, customDensityInfo), toUnitInfo) + QuantityValue expectedValue = toUnitInfo.GetValueFrom(customConversionFromSpecificVolume.Evaluate(valueToConvert), customDensityInfo); + + IQuantity convertedQuantity = converter.ConvertTo(quantityToConvert, toUnit); + + Assert.IsType(convertedQuantity); + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }, () => + { + // all other specific-volume units are also converted using our custom conversion expression (possibly resulting in a different unit) + Assert.All(SpecificVolume.Info.UnitInfos.Where(info => info != customSpecificVolumeInfo), fromUnitInfo => + { + SpecificVolume quantityToConvert = fromUnitInfo.From(valueToConvert); + Assert.All(Density.Info.UnitInfos, toUnitInfo => + { + DensityUnit toUnit = toUnitInfo.Value; + Density expectedQuantity = customDensityInfo.From(customConversionFromSpecificVolume.Evaluate(customSpecificVolumeInfo.GetValueFrom(valueToConvert, fromUnitInfo))); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, customDensityInfo); + + IQuantity convertedQuantity = converter.ConvertTo(quantityToConvert, toUnit); + + Assert.IsType(convertedQuantity); + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_WithCustomConversionExpression_ShouldConvertQuantityToUnitOfAnotherQuantity(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var customConversionFromDensity = new ConversionExpression(new QuantityValue(-1, 2)); + var customConversionFromSpecificVolume = new ConversionExpression(-2); + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => + { + options.SetCustomConversion(DensityUnit.MicrogramPerLiter, SpecificVolumeUnit.CubicFootPerPound, customConversionFromDensity); + options.SetCustomConversion(SpecificVolumeUnit.CubicFootPerPound, DensityUnit.MicrogramPerLiter, customConversionFromSpecificVolume); + }); + var converter = UnitConverter.Create(new UnitParser([Density.Info, SpecificVolume.Info]), convertOptions); + + UnitInfo customDensityInfo = Density.Info[DensityUnit.MicrogramPerLiter]; + UnitInfo customSpecificVolumeInfo = SpecificVolume.Info[SpecificVolumeUnit.CubicFootPerPound]; + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + // when the left unit is the customDensityInfo + Density quantityToConvert = customDensityInfo.From(valueToConvert); + Assert.All(SpecificVolume.Info.UnitInfos, toUnitInfo => + { + SpecificVolumeUnit toUnit = toUnitInfo.Value; + // (123.45, customDensityInfo) => (-123.45/2, customSpecificVolumeInfo) => ConvertValue((-123.45/2, customSpecificVolumeInfo), toUnitInfo) + QuantityValue expectedValue = toUnitInfo.GetValueFrom(customConversionFromDensity.Evaluate(valueToConvert), customSpecificVolumeInfo); + + var success = converter.TryConvertTo(quantityToConvert, toUnit, out IQuantity? convertedQuantity); + + Assert.True(success); + Assert.IsType(convertedQuantity); + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }, + () => + { + // all other density units are also converted using our custom conversion expression + Assert.All(Density.Info.UnitInfos.Where(info => info != customDensityInfo), fromUnitInfo => + { + Density quantityToConvert = fromUnitInfo.From(valueToConvert); + Assert.All(SpecificVolume.Info.UnitInfos, toUnitInfo => + { + SpecificVolumeUnit toUnit = toUnitInfo.Value; + QuantityValue expectedValue = toUnitInfo.GetValueFrom(customConversionFromDensity.Evaluate(customDensityInfo.GetValueFrom(valueToConvert, fromUnitInfo)), customSpecificVolumeInfo); + + var success = converter.TryConvertTo(quantityToConvert, toUnit, out IQuantity? convertedQuantity); + + Assert.True(success); + Assert.IsType(convertedQuantity); + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }); + }, + () => + { + // when the left unit is the customSpecificVolumeInfo + SpecificVolume quantityToConvert = customSpecificVolumeInfo.From(valueToConvert); + Assert.All(Density.Info.UnitInfos, toUnitInfo => + { + DensityUnit toUnit = toUnitInfo.Value; + // (123.45, customSpecificVolumeInfo) => (-123.45 * 2, customDensityInfo) => ConvertValue((-123.45 * 2, customDensityInfo), toUnitInfo) + QuantityValue expectedValue = toUnitInfo.GetValueFrom(customConversionFromSpecificVolume.Evaluate(valueToConvert), customDensityInfo); + + var success = converter.TryConvertTo(quantityToConvert, toUnit, out IQuantity? convertedQuantity); + + Assert.True(success); + Assert.IsType(convertedQuantity); + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }, () => + { + // all other specific-volume units are also converted using our custom conversion expression + Assert.All(SpecificVolume.Info.UnitInfos.Where(info => info != customSpecificVolumeInfo), fromUnitInfo => + { + SpecificVolume quantityToConvert = fromUnitInfo.From(valueToConvert); + Assert.All(Density.Info.UnitInfos, toUnitInfo => + { + DensityUnit toUnit = toUnitInfo.Value; + Density expectedQuantity = customDensityInfo.From(customConversionFromSpecificVolume.Evaluate(customSpecificVolumeInfo.GetValueFrom(valueToConvert, fromUnitInfo))); + QuantityValue expectedValue = toUnitInfo.GetValueFrom(expectedQuantity.Value, customDensityInfo); + + var success = converter.TryConvertTo(quantityToConvert, toUnit, out IQuantity? convertedQuantity); + + Assert.True(success); + Assert.IsType(convertedQuantity); + Assert.Equal(toUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertTo_TargetQuantityInfo_ShouldConvertQuantityToTargetQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info, SpecificVolume.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(Density.Info.UnitInfos, fromUnitInfo => + { + DensityUnit fromUnit = fromUnitInfo.Value; + SpecificVolume expectedQuantity = SpecificVolume.Info.ConvertFrom(valueToConvert, fromUnitInfo); + + SpecificVolume convertedQuantity = converter.ConvertTo(valueToConvert, fromUnit, SpecificVolume.Info); + + Assert.Equal(expectedQuantity, convertedQuantity); + }); + }, + () => + { + Assert.All(SpecificVolume.Info.UnitInfos, fromUnitInfo => + { + SpecificVolumeUnit fromUnit = fromUnitInfo.Value; + Density expectedQuantity = Density.Info.ConvertFrom(valueToConvert, fromUnitInfo); + + Density convertedQuantity = converter.ConvertTo(valueToConvert, fromUnit, Density.Info); + + Assert.Equal(expectedQuantity, convertedQuantity); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertTo_TargetIQuantityInfo_ShouldConvertQuantityToTargetIQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info, SpecificVolume.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(Density.Info.UnitInfos, fromUnitInfo => + { + DensityUnit fromUnit = fromUnitInfo.Value; + QuantityInfo targetQuantityInfo = SpecificVolume.Info; + SpecificVolume expectedQuantity = SpecificVolume.Info.ConvertFrom(valueToConvert, fromUnitInfo); + + IQuantity convertedQuantity = converter.ConvertTo(valueToConvert, fromUnit, targetQuantityInfo); + + Assert.IsType(convertedQuantity); + Assert.Equal(expectedQuantity, convertedQuantity); + }); + }, + () => + { + Assert.All(SpecificVolume.Info.UnitInfos, fromUnitInfo => + { + SpecificVolumeUnit fromUnit = fromUnitInfo.Value; + QuantityInfo targetQuantityInfo = Density.Info; + Density expectedQuantity = Density.Info.ConvertFrom(valueToConvert, fromUnitInfo); + + IQuantity convertedQuantity = converter.ConvertTo(valueToConvert, fromUnit, targetQuantityInfo); + + Assert.IsType(convertedQuantity); + Assert.Equal(expectedQuantity, convertedQuantity); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertTo_TargetQuantityInfo_FromUnknownUnit_ShouldThrow_UnitNotFoundException(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info]), convertOptions); + + Assert.Throws(() => converter.ConvertTo(1, SpecificVolumeUnit.CubicMeterPerKilogram, Density.Info)); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertTo_TargetQuantityInfo_FromUnknownQuantity_ShouldThrow_InvalidConversionException(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info]), convertOptions); + + Assert.Throws(() => converter.ConvertTo(1, DensityUnit.KilogramPerCubicMeter, SpecificVolume.Info)); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertTo_TargetIQuantityInfo_FromUnknownUnit_ShouldThrow_UnitNotFoundException(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info]), convertOptions); + QuantityInfo targetQuantityInfo = Density.Info; + + Assert.Throws(() => converter.ConvertTo(1, SpecificVolumeUnit.CubicMeterPerKilogram, targetQuantityInfo)); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertTo_TargetIQuantityInfo_FromUnknownQuantity_ShouldThrow_InvalidConversionException(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info]), convertOptions); + QuantityInfo targetQuantityInfo = SpecificVolume.Info; + + Assert.Throws(() => converter.ConvertTo(1, DensityUnit.KilogramPerCubicMeter, targetQuantityInfo)); + } + + [Fact] + public void ConvertTo_TargetQuantityInfo_WithUnsupportedConversion_ShouldThrow_InvalidConversionException() + { + QuantityConversionOptions invalidConversionOptions = new QuantityConversionOptions().SetCustomConversion(); + // converter options with a custom conversion which cannot be deduced from the dimensions of the quantities (an explicit conversion function is required) + Assert.All(GetQuantityConverterBuildOptions().Where(x => x.DefaultCachingMode == ConversionCachingMode.None) + .Select(options => options.WithImplicitConversionOptions(invalidConversionOptions)), + convertOptions => + { + // this is not ideal, but since we aren't creating any conversion functions: no exception is thrown from the Create method + var converter = UnitConverter.Create(new UnitParser([Density.Info, Mass.Info]), convertOptions); + // the invalid conversion is only detected when attempting to convert "on the fly" + Assert.Throws(() => converter.ConvertTo(1, DensityUnit.KilogramPerCubicMeter, Mass.Info)); + Assert.Throws(() => converter.ConvertTo(1, MassUnit.Gram, Density.Info)); + }); + } + + [Fact] + public void ConvertTo_TargetIQuantityInfo_WithUnsupportedConversion_ShouldThrow_InvalidConversionException() + { + QuantityConversionOptions invalidConversionOptions = new QuantityConversionOptions().SetCustomConversion(); + // converter options with a custom conversion which cannot be deduced from the dimensions of the quantities (an explicit conversion function is required) + Assert.All(GetQuantityConverterBuildOptions().Where(x => x.DefaultCachingMode == ConversionCachingMode.None) + .Select(options => options.WithImplicitConversionOptions(invalidConversionOptions)), + convertOptions => + { + // this is not ideal, but since we aren't creating any conversion functions: no exception is thrown from the Create method + var converter = UnitConverter.Create(new UnitParser([Density.Info, Mass.Info]), convertOptions); + // the invalid conversion is only detected when attempting to convert "on the fly" + Assert.Throws(() => converter.ConvertTo(1, DensityUnit.KilogramPerCubicMeter, (QuantityInfo)Mass.Info)); + Assert.Throws(() => converter.ConvertTo(1, MassUnit.Gram, (QuantityInfo)Density.Info)); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void Create_WithCachingAndUnsupportedConversionUnits_ShouldThrow_InvalidConversionException(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + // converter options with a custom conversion unit-mapping which cannot be deduced from the dimensions of the quantities (an explicit conversion function is required) + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(conversionOptions => conversionOptions + .SetCustomConversion() // this is optional + .SetConversionUnits(DensityUnit.KilogramPerCubicMeter, MassUnit.Kilogram)); + + Assert.Throws(() => UnitConverter.Create(new UnitParser([Density.Info, Mass.Info]), convertOptions)); + } + + [Fact] + public void Create_WithCachingAndUnsupportedConversion_ShouldThrow_InvalidConversionException() + { + // converter options with a custom conversion which cannot be deduced from the dimensions of the quantities (an explicit conversion function is required) + Assert.All(GetQuantityConverterBuildOptions().Where(x => x.DefaultCachingMode != ConversionCachingMode.None) + .Select(options => options.WithImplicitConversionOptions(conversionOptions => conversionOptions.SetCustomConversion())), + convertOptions => + { + Assert.Throws(() => UnitConverter.Create(new UnitParser([Density.Info, Mass.Info]), convertOptions)); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_TargetQuantityInfo_FromUnknownUnit_ReturnFalse(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info]), convertOptions); + + var success = converter.TryConvertTo(1, SpecificVolumeUnit.CubicMeterPerKilogram, Density.Info, out _); + + Assert.False(success); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_TargetIQuantityInfo_FromUnknownUnit_ReturnFalse(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info]), convertOptions); + + var success = converter.TryConvertTo(1, SpecificVolumeUnit.CubicMeterPerKilogram, (QuantityInfo)Density.Info, out _); + + Assert.False(success); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_TargetQuantityInfo_FromUnknownQuantity_ReturnFalse(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info]), convertOptions); + + var success = converter.TryConvertTo(1, DensityUnit.KilogramPerCubicMeter, SpecificVolume.Info, out _); + + Assert.False(success); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_TargetIQuantityInfo_FromUnknownQuantity_ReturnFalse(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info]), convertOptions); + + var success = converter.TryConvertTo(1, DensityUnit.KilogramPerCubicMeter, (QuantityInfo)SpecificVolume.Info, out _); + + Assert.False(success); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_TargetQuantityInfo_WithUnknownRelation_ReturnFalse(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info, MassConcentration.Info]), convertOptions); + + Assert.False(converter.TryConvertTo(1, DensityUnit.KilogramPerCubicMeter, MassConcentration.Info, out _)); + Assert.False(converter.TryConvertTo(1, MassConcentrationUnit.KilogramPerCubicMeter, Density.Info, out _)); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_TargetIQuantityInfo_WithUnknownRelation_ReturnFalse(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info, MassConcentration.Info]), convertOptions); + + Assert.False(converter.TryConvertTo(1, DensityUnit.KilogramPerCubicMeter, (QuantityInfo)MassConcentration.Info, out _)); + Assert.False(converter.TryConvertTo(1, MassConcentrationUnit.KilogramPerCubicMeter, (QuantityInfo)Density.Info, out _)); + } + + [Fact] + public void TryConvertTo_TargetQuantityInfo_WithUnsupportedConversion_ShouldReturnFalse() + { + Assert.All(GetQuantityConverterBuildOptions().Where(x => x.DefaultCachingMode == ConversionCachingMode.None) + .Select(options => options.WithImplicitConversionOptions(conversionOptions => conversionOptions.SetCustomConversion())), + convertOptions => + { + // this is not ideal, but since we aren't creating any conversion functions: no exception is thrown from the Create method + var converter = UnitConverter.Create(new UnitParser([Density.Info, Mass.Info]), convertOptions); + // all subsequent attempts to use the invalid conversions would fail + Assert.Multiple(() => + { + var success = converter.TryConvertTo(1, MassUnit.Kilogram, Density.Info, out _); + + Assert.False(success); + }, () => + { + var success = converter.TryConvertTo(1, DensityUnit.KilogramPerLiter, Mass.Info, out _); + + Assert.False(success); + }); + }); + } + + [Fact] + public void TryConvertTo_TargetIQuantityInfo_WithUnsupportedConversion_ShouldReturnFalse() + { + Assert.All(GetQuantityConverterBuildOptions().Where(x => x.DefaultCachingMode == ConversionCachingMode.None) + .Select(options => options.WithImplicitConversionOptions(conversionOptions => conversionOptions.SetCustomConversion())), + convertOptions => + { + // this is not ideal, but since we aren't creating any conversion functions: no exception is thrown from the Create method + var converter = UnitConverter.Create(new UnitParser([Density.Info, Mass.Info]), convertOptions); + // all subsequent attempts to use the invalid conversions would fail + Assert.Multiple(() => + { + var success = converter.TryConvertTo(1, MassUnit.Kilogram, (QuantityInfo)Density.Info, out _); + + Assert.False(success); + }, () => + { + var success = converter.TryConvertTo(1, DensityUnit.KilogramPerLiter, (QuantityInfo)Mass.Info, out _); + + Assert.False(success); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_TargetQuantityInfo_ShouldConvertQuantityToTargetQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info, SpecificVolume.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(Density.Info.UnitInfos, fromUnitInfo => + { + DensityUnit fromUnit = fromUnitInfo.Value; + SpecificVolume expectedQuantity = SpecificVolume.Info.ConvertFrom(valueToConvert, fromUnitInfo); + + var success = converter.TryConvertTo(valueToConvert, fromUnit, SpecificVolume.Info, out SpecificVolume convertedQuantity); + + Assert.True(success); + Assert.Equal(expectedQuantity, convertedQuantity); + }); + }, + () => + { + Assert.All(SpecificVolume.Info.UnitInfos, fromUnitInfo => + { + SpecificVolumeUnit fromUnit = fromUnitInfo.Value; + Density expectedQuantity = Density.Info.ConvertFrom(valueToConvert, fromUnitInfo); + + var success = converter.TryConvertTo(valueToConvert, fromUnit, Density.Info, out Density convertedQuantity); + + Assert.True(success); + Assert.Equal(expectedQuantity, convertedQuantity); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_TargetIQuantityInfo_ShouldConvertQuantityToTargetIQuantity(bool freeze, ConversionCachingMode cachingMode, bool reduceConstants) + { + var convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants); + var converter = UnitConverter.Create(new UnitParser([Density.Info, SpecificVolume.Info]), convertOptions); + + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + Assert.All(Density.Info.UnitInfos, fromUnitInfo => + { + DensityUnit fromUnit = fromUnitInfo.Value; + QuantityInfo targetQuantityInfo = SpecificVolume.Info; + SpecificVolume expectedQuantity = SpecificVolume.Info.ConvertFrom(valueToConvert, fromUnitInfo); + + var success = converter.TryConvertTo(valueToConvert, fromUnit, targetQuantityInfo, out IQuantity? convertedQuantity); + + Assert.True(success); + Assert.IsType(convertedQuantity); + Assert.Equal(expectedQuantity, convertedQuantity); + }); + }, + () => + { + Assert.All(SpecificVolume.Info.UnitInfos, fromUnitInfo => + { + SpecificVolumeUnit fromUnit = fromUnitInfo.Value; + QuantityInfo targetQuantityInfo = Density.Info; + Density expectedQuantity = Density.Info.ConvertFrom(valueToConvert, fromUnitInfo); + + var success = converter.TryConvertTo(valueToConvert, fromUnit, targetQuantityInfo, out IQuantity? convertedQuantity); + + Assert.True(success); + Assert.IsType(convertedQuantity); + Assert.Equal(expectedQuantity, convertedQuantity); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertTo_TargetQuantityInfo_WithCustomConversionExpression_ShouldConvertQuantityToTargetQuantity(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + DensityUnit customDensityUnit = DensityUnit.MicrogramPerLiter; + SpecificVolumeUnit customSpecificVolumeUnit = SpecificVolumeUnit.CubicFootPerPound; + var customConversionFromDensity = new ConversionExpression(new QuantityValue(-1, 2)); + var customConversionFromSpecificVolume = new ConversionExpression(-2); + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => + { + options.SetCustomConversion(customDensityUnit, customSpecificVolumeUnit, customConversionFromDensity); + options.SetCustomConversion(customSpecificVolumeUnit, customDensityUnit, customConversionFromSpecificVolume); + }); + var converter = UnitConverter.Create(new UnitParser([Density.Info, SpecificVolume.Info]), convertOptions); + + UnitInfo customDensityInfo = Density.Info[customDensityUnit]; + UnitInfo customSpecificVolumeInfo = SpecificVolume.Info[customSpecificVolumeUnit]; + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + // when the left unit is the customDensityInfo + DensityUnit fromUnit = customDensityInfo.Value; + // (123.45, customDensityInfo) => (-123.45/2, customSpecificVolumeInfo) => ConvertValue((-123.45/2, customSpecificVolumeInfo), toUnitInfo) + QuantityValue expectedValue = customSpecificVolumeInfo.GetValueFrom(customConversionFromDensity.Evaluate(valueToConvert), customSpecificVolumeInfo); + + SpecificVolume convertedQuantity = converter.ConvertTo(valueToConvert, fromUnit, SpecificVolume.Info); + + Assert.Equal(customSpecificVolumeUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, + () => + { + // all other density units are also converted using our custom conversion expression (possibly resulting in a different unit) + Assert.All(Density.Info.UnitInfos.Where(info => info != customDensityInfo), fromUnitInfo => + { + DensityUnit fromUnit = fromUnitInfo.Value; + SpecificVolume expectedQuantity = customSpecificVolumeInfo.From(customConversionFromDensity.Evaluate(customDensityInfo.GetValueFrom(valueToConvert, fromUnitInfo))); + + SpecificVolume convertedQuantity = converter.ConvertTo(valueToConvert, fromUnit, SpecificVolume.Info); + + Assert.Equal(expectedQuantity, convertedQuantity); + }); + }, + () => + { + // when the left unit is the customSpecificVolumeInfo + SpecificVolumeUnit fromUnit = customSpecificVolumeInfo.Value; + // (123.45, customSpecificVolumeInfo) => (-123.45 * 2, customDensityInfo) => ConvertValue((-123.45 * 2, customDensityInfo), toUnitInfo) + QuantityValue expectedValue = customDensityInfo.GetValueFrom(customConversionFromSpecificVolume.Evaluate(valueToConvert), customDensityInfo); + + Density convertedQuantity = converter.ConvertTo(valueToConvert, fromUnit, Density.Info); + + Assert.Equal(customDensityUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, () => + { + // all other specific-volume units are also converted using our custom conversion expression (possibly resulting in a different unit) + Assert.All(SpecificVolume.Info.UnitInfos.Where(info => info != customSpecificVolumeInfo), fromUnitInfo => + { + SpecificVolumeUnit fromUnit = fromUnitInfo.Value; + Density expectedQuantity = customDensityInfo.From(customConversionFromSpecificVolume.Evaluate(customSpecificVolumeInfo.GetValueFrom(valueToConvert, fromUnitInfo))); + + Density convertedQuantity = converter.ConvertTo(valueToConvert, fromUnit, Density.Info); + + Assert.Equal(expectedQuantity, convertedQuantity); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void ConvertTo_TargetIQuantityInfo_WithCustomConversionExpression_ShouldConvertQuantityToTargetIQuantity(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + DensityUnit customDensityUnit = DensityUnit.MicrogramPerLiter; + SpecificVolumeUnit customSpecificVolumeUnit = SpecificVolumeUnit.CubicFootPerPound; + var customConversionFromDensity = new ConversionExpression(new QuantityValue(-1, 2)); + var customConversionFromSpecificVolume = new ConversionExpression(-2); + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => + { + options.SetCustomConversion(customDensityUnit, customSpecificVolumeUnit, customConversionFromDensity); + options.SetCustomConversion(customSpecificVolumeUnit, customDensityUnit, customConversionFromSpecificVolume); + }); + var converter = UnitConverter.Create(new UnitParser([Density.Info, SpecificVolume.Info]), convertOptions); + + UnitInfo customDensityInfo = Density.Info[customDensityUnit]; + UnitInfo customSpecificVolumeInfo = SpecificVolume.Info[customSpecificVolumeUnit]; + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + // when the left unit is the customDensityInfo + DensityUnit fromUnit = customDensityInfo.Value; + QuantityInfo targetQuantityInfo = SpecificVolume.Info; + // (123.45, customDensityInfo) => (-123.45/2, customSpecificVolumeInfo) => ConvertValue((-123.45/2, customSpecificVolumeInfo), toUnitInfo) + QuantityValue expectedValue = customSpecificVolumeInfo.GetValueFrom(customConversionFromDensity.Evaluate(valueToConvert), customSpecificVolumeInfo); + + IQuantity convertedQuantity = converter.ConvertTo(valueToConvert, fromUnit, targetQuantityInfo); + + Assert.IsType(convertedQuantity); + Assert.Equal(customSpecificVolumeUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, + () => + { + // all other density units are also converted using our custom conversion expression (possibly resulting in a different unit) + Assert.All(Density.Info.UnitInfos.Where(info => info != customDensityInfo), fromUnitInfo => + { + DensityUnit fromUnit = fromUnitInfo.Value; + QuantityInfo targetQuantityInfo = SpecificVolume.Info; + SpecificVolume expectedQuantity = customSpecificVolumeInfo.From(customConversionFromDensity.Evaluate(customDensityInfo.GetValueFrom(valueToConvert, fromUnitInfo))); + + IQuantity convertedQuantity = converter.ConvertTo(valueToConvert, fromUnit, targetQuantityInfo); + + Assert.IsType(convertedQuantity); + Assert.Equal(expectedQuantity, convertedQuantity); + }); + }, + () => + { + // when the left unit is the customSpecificVolumeInfo + SpecificVolumeUnit fromUnit = customSpecificVolumeInfo.Value; + QuantityInfo targetQuantityInfo = Density.Info; + // (123.45, customSpecificVolumeInfo) => (-123.45 * 2, customDensityInfo) => ConvertValue((-123.45 * 2, customDensityInfo), toUnitInfo) + QuantityValue expectedValue = customDensityInfo.GetValueFrom(customConversionFromSpecificVolume.Evaluate(valueToConvert), customDensityInfo); + + IQuantity convertedQuantity = converter.ConvertTo(valueToConvert, fromUnit, targetQuantityInfo); + + Assert.IsType(convertedQuantity); + Assert.Equal(customDensityUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, () => + { + // all other specific-volume units are also converted using our custom conversion expression (possibly resulting in a different unit) + Assert.All(SpecificVolume.Info.UnitInfos.Where(info => info != customSpecificVolumeInfo), fromUnitInfo => + { + SpecificVolumeUnit fromUnit = fromUnitInfo.Value; + QuantityInfo targetQuantityInfo = Density.Info; + Density expectedQuantity = customDensityInfo.From(customConversionFromSpecificVolume.Evaluate(customSpecificVolumeInfo.GetValueFrom(valueToConvert, fromUnitInfo))); + + IQuantity convertedQuantity = converter.ConvertTo(valueToConvert, fromUnit, targetQuantityInfo); + + Assert.IsType(convertedQuantity); + Assert.Equal(expectedQuantity, convertedQuantity); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_TargetQuantityInfo_WithCustomConversionExpression_ShouldConvertQuantityToTargetQuantity(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + DensityUnit customDensityUnit = DensityUnit.MicrogramPerLiter; + SpecificVolumeUnit customSpecificVolumeUnit = SpecificVolumeUnit.CubicFootPerPound; + var customConversionFromDensity = new ConversionExpression(new QuantityValue(-1, 2)); + var customConversionFromSpecificVolume = new ConversionExpression(-2); + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => + { + options.SetCustomConversion(customDensityUnit, customSpecificVolumeUnit, customConversionFromDensity); + options.SetCustomConversion(customSpecificVolumeUnit, customDensityUnit, customConversionFromSpecificVolume); + }); + var converter = UnitConverter.Create(new UnitParser([Density.Info, SpecificVolume.Info]), convertOptions); + + UnitInfo customDensityInfo = Density.Info[customDensityUnit]; + UnitInfo customSpecificVolumeInfo = SpecificVolume.Info[customSpecificVolumeUnit]; + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + // when the left unit is the customDensityInfo + DensityUnit fromUnit = customDensityInfo.Value; + // (123.45, customDensityInfo) => (-123.45/2, customSpecificVolumeInfo) => ConvertValue((-123.45/2, customSpecificVolumeInfo), toUnitInfo) + QuantityValue expectedValue = customSpecificVolumeInfo.GetValueFrom(customConversionFromDensity.Evaluate(valueToConvert), customSpecificVolumeInfo); + + var success = converter.TryConvertTo(valueToConvert, fromUnit, SpecificVolume.Info, out SpecificVolume convertedQuantity); + + Assert.True(success); + Assert.Equal(customSpecificVolumeUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, + () => + { + // all other density units are also converted using our custom conversion expression (possibly resulting in a different unit) + Assert.All(Density.Info.UnitInfos.Where(info => info != customDensityInfo), fromUnitInfo => + { + DensityUnit fromUnit = fromUnitInfo.Value; + SpecificVolume expectedQuantity = customSpecificVolumeInfo.From(customConversionFromDensity.Evaluate(customDensityInfo.GetValueFrom(valueToConvert, fromUnitInfo))); + + var success = converter.TryConvertTo(valueToConvert, fromUnit, SpecificVolume.Info, out SpecificVolume convertedQuantity); + + Assert.True(success); + Assert.Equal(expectedQuantity, convertedQuantity); + }); + }, + () => + { + // when the left unit is the customSpecificVolumeInfo + SpecificVolumeUnit fromUnit = customSpecificVolumeInfo.Value; + // (123.45, customSpecificVolumeInfo) => (-123.45 * 2, customDensityInfo) => ConvertValue((-123.45 * 2, customDensityInfo), toUnitInfo) + QuantityValue expectedValue = customDensityInfo.GetValueFrom(customConversionFromSpecificVolume.Evaluate(valueToConvert), customDensityInfo); + + var success = converter.TryConvertTo(valueToConvert, fromUnit, Density.Info, out Density convertedQuantity); + + Assert.True(success); + Assert.Equal(customDensityUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, () => + { + // all other specific-volume units are also converted using our custom conversion expression (possibly resulting in a different unit) + Assert.All(SpecificVolume.Info.UnitInfos.Where(info => info != customSpecificVolumeInfo), fromUnitInfo => + { + SpecificVolumeUnit fromUnit = fromUnitInfo.Value; + Density expectedQuantity = customDensityInfo.From(customConversionFromSpecificVolume.Evaluate(customSpecificVolumeInfo.GetValueFrom(valueToConvert, fromUnitInfo))); + + var success = converter.TryConvertTo(valueToConvert, fromUnit, Density.Info, out Density convertedQuantity); + + Assert.True(success); + Assert.Equal(expectedQuantity, convertedQuantity); + }); + }); + } + + [Theory] + [MemberData(nameof(ConverterTestOptions))] + public void TryConvertTo_TargetIQuantityInfo_WithCustomConversionExpression_ShouldConvertQuantityToTargetIQuantity(bool freeze, ConversionCachingMode cachingMode, + bool reduceConstants) + { + DensityUnit customDensityUnit = DensityUnit.MicrogramPerLiter; + SpecificVolumeUnit customSpecificVolumeUnit = SpecificVolumeUnit.CubicFootPerPound; + var customConversionFromDensity = new ConversionExpression(new QuantityValue(-1, 2)); + var customConversionFromSpecificVolume = new ConversionExpression(-2); + QuantityConverterBuildOptions convertOptions = new QuantityConverterBuildOptions(freeze, cachingMode, reduceConstants) + .WithImplicitConversionOptions(options => + { + options.SetCustomConversion(customDensityUnit, customSpecificVolumeUnit, customConversionFromDensity); + options.SetCustomConversion(customSpecificVolumeUnit, customDensityUnit, customConversionFromSpecificVolume); + }); + var converter = UnitConverter.Create(new UnitParser([Density.Info, SpecificVolume.Info]), convertOptions); + + UnitInfo customDensityInfo = Density.Info[customDensityUnit]; + UnitInfo customSpecificVolumeInfo = SpecificVolume.Info[customSpecificVolumeUnit]; + QuantityValue valueToConvert = 123.45m; + Assert.Multiple(() => + { + // when the left unit is the customDensityInfo + DensityUnit fromUnit = customDensityInfo.Value; + QuantityInfo targetQuantityInfo = SpecificVolume.Info; + // (123.45, customDensityInfo) => (-123.45/2, customSpecificVolumeInfo) => ConvertValue((-123.45/2, customSpecificVolumeInfo), toUnitInfo) + QuantityValue expectedValue = customSpecificVolumeInfo.GetValueFrom(customConversionFromDensity.Evaluate(valueToConvert), customSpecificVolumeInfo); + + var success = converter.TryConvertTo(valueToConvert, fromUnit, targetQuantityInfo, out IQuantity? convertedQuantity); + + Assert.True(success); + Assert.IsType(convertedQuantity); + Assert.Equal(customSpecificVolumeUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, + () => + { + // all other density units are also converted using our custom conversion expression (possibly resulting in a different unit) + Assert.All(Density.Info.UnitInfos.Where(info => info != customDensityInfo), fromUnitInfo => + { + DensityUnit fromUnit = fromUnitInfo.Value; + QuantityInfo targetQuantityInfo = SpecificVolume.Info; + SpecificVolume expectedQuantity = customSpecificVolumeInfo.From(customConversionFromDensity.Evaluate(customDensityInfo.GetValueFrom(valueToConvert, fromUnitInfo))); + + var success = converter.TryConvertTo(valueToConvert, fromUnit, targetQuantityInfo, out IQuantity? convertedQuantity); + + Assert.True(success); + Assert.IsType(convertedQuantity); + Assert.Equal(expectedQuantity, convertedQuantity); + }); + }, + () => + { + // when the left unit is the customSpecificVolumeInfo + SpecificVolumeUnit fromUnit = customSpecificVolumeInfo.Value; + QuantityInfo targetQuantityInfo = Density.Info; + // (123.45, customSpecificVolumeInfo) => (-123.45 * 2, customDensityInfo) => ConvertValue((-123.45 * 2, customDensityInfo), toUnitInfo) + QuantityValue expectedValue = customDensityInfo.GetValueFrom(customConversionFromSpecificVolume.Evaluate(valueToConvert), customDensityInfo); + + var success = converter.TryConvertTo(valueToConvert, fromUnit, targetQuantityInfo, out IQuantity? convertedQuantity); + + Assert.True(success); + Assert.IsType(convertedQuantity); + Assert.Equal(customDensityUnit, convertedQuantity.Unit); + Assert.Equal(expectedValue, convertedQuantity.Value); + }, () => + { + // all other specific-volume units are also converted using our custom conversion expression (possibly resulting in a different unit) + Assert.All(SpecificVolume.Info.UnitInfos.Where(info => info != customSpecificVolumeInfo), fromUnitInfo => + { + SpecificVolumeUnit fromUnit = fromUnitInfo.Value; + QuantityInfo targetQuantityInfo = Density.Info; + Density expectedQuantity = customDensityInfo.From(customConversionFromSpecificVolume.Evaluate(customSpecificVolumeInfo.GetValueFrom(valueToConvert, fromUnitInfo))); + + var success = converter.TryConvertTo(valueToConvert, fromUnit, targetQuantityInfo, out IQuantity? convertedQuantity); + + Assert.True(success); + Assert.IsType(convertedQuantity); + Assert.Equal(expectedQuantity, convertedQuantity); + }); + }); + } } } diff --git a/UnitsNet.Tests/UnitDefinitionTest.cs b/UnitsNet.Tests/UnitDefinitionTest.cs new file mode 100644 index 0000000000..6def6d6daa --- /dev/null +++ b/UnitsNet.Tests/UnitDefinitionTest.cs @@ -0,0 +1,107 @@ +// 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 UnitsNet.Units; +using Xunit; + +namespace UnitsNet.Tests; + +public class UnitDefinitionTest +{ + [Theory] + [InlineData(LengthUnit.Meter, "Meters")] + [InlineData(LengthUnit.Centimeter, "Centimeters")] + [InlineData(LengthUnit.Millimeter, "Millimeters")] + public void Constructor_BaseUnit_InitializesWithoutConversionOrSingularName(LengthUnit value, string pluralName) + { + var baseUnits = new BaseUnits(value); + var unitDefinition = new UnitDefinition(value, pluralName, baseUnits); + + Assert.Equal(value, unitDefinition.Value); + Assert.Equal(value.ToString(), unitDefinition.Name); + Assert.Equal(pluralName, unitDefinition.PluralName); + Assert.Equal(baseUnits, unitDefinition.BaseUnits); + Assert.Equal(QuantityValue.One, unitDefinition.ConversionFromBase.Evaluate(1)); + Assert.Equal(QuantityValue.One, unitDefinition.ConversionToBase.Evaluate(1)); + } + + [Theory] + [InlineData(LengthUnit.Meter, "Meter", "Meters")] + [InlineData(LengthUnit.Centimeter, "Centimeter", "Centimeters")] + [InlineData(LengthUnit.Millimeter, "Millimeter", "Millimeters")] + public void Constructor_BaseUnit_InitializesWithoutConversion(LengthUnit value, string singularName, string pluralName) + { + var baseUnits = new BaseUnits(value); + var unitDefinition = new UnitDefinition(value, singularName, pluralName, baseUnits); + + Assert.Equal(value, unitDefinition.Value); + Assert.Equal(singularName, unitDefinition.Name); + Assert.Equal(pluralName, unitDefinition.PluralName); + Assert.Equal(baseUnits, unitDefinition.BaseUnits); + Assert.Equal(QuantityValue.One, unitDefinition.ConversionFromBase.Evaluate(1)); + Assert.Equal(QuantityValue.One, unitDefinition.ConversionToBase.Evaluate(1)); + } + + [Theory] + [InlineData(LengthUnit.Meter, "Meters", 1.0, 1.0)] + [InlineData(LengthUnit.Centimeter, "Centimeters", 0.01, 100.0)] + [InlineData(LengthUnit.Millimeter, "Millimeters", 0.001, 1000.0)] + public void Constructor_WithConversionValues_InitializesCorrectly(LengthUnit value, string pluralName, double conversionCoefficientFromBase, + double conversionCoefficientToBase) + { + var baseUnits = new BaseUnits(); + QuantityValue conversionFromBase = conversionCoefficientFromBase; + QuantityValue conversionToBase = conversionCoefficientToBase; + + var unitDefinition = new UnitDefinition(value, pluralName, baseUnits, conversionFromBase, conversionToBase); + + Assert.Equal(value, unitDefinition.Value); + Assert.Equal(value.ToString(), unitDefinition.Name); + Assert.Equal(pluralName, unitDefinition.PluralName); + Assert.Equal(baseUnits, unitDefinition.BaseUnits); + Assert.Equal(conversionFromBase, unitDefinition.ConversionFromBase.Evaluate(QuantityValue.One)); + Assert.Equal(conversionToBase, unitDefinition.ConversionToBase.Evaluate(QuantityValue.One)); + } + + + [Theory] + [InlineData(LengthUnit.Meter, "Meter", "Meters", 1.0, 1.0)] + [InlineData(LengthUnit.Centimeter, "Centimeter", "Centimeters", 0.01, 100.0)] + [InlineData(LengthUnit.Millimeter, "Millimeter", "Millimeters", 0.001, 1000.0)] + public void Constructor_WithSingularNameAndConversionValues_InitializesCorrectly(LengthUnit value, string singularName, string pluralName, + double conversionCoefficientFromBase, + double conversionCoefficientToBase) + { + var baseUnits = new BaseUnits(); + QuantityValue conversionFromBase = conversionCoefficientFromBase; + QuantityValue conversionToBase = conversionCoefficientToBase; + + var unitDefinition = new UnitDefinition(value, singularName, pluralName, baseUnits, conversionFromBase, conversionToBase); + + Assert.Equal(value, unitDefinition.Value); + Assert.Equal(singularName, unitDefinition.Name); + Assert.Equal(pluralName, unitDefinition.PluralName); + Assert.Equal(baseUnits, unitDefinition.BaseUnits); + Assert.Equal(conversionFromBase, unitDefinition.ConversionFromBase.Evaluate(QuantityValue.One)); + Assert.Equal(conversionToBase, unitDefinition.ConversionToBase.Evaluate(QuantityValue.One)); + } + + [Fact] + public void Constructor_WithNullSingularName_ThrowsArgumentNullException() + { + Assert.Throws(() => new UnitDefinition(LengthUnit.Meter, null!, "Meters", BaseUnits.Undefined)); + } + + [Fact] + public void Constructor_WithNullPluralName_ThrowsArgumentNullException() + { + Assert.Throws(() => new UnitDefinition(LengthUnit.Meter, "Meter", null!, BaseUnits.Undefined)); + } + + [Fact] + public void Constructor_WithNullBaseUnits_ThrowsArgumentNullException() + { + Assert.Throws(() => new UnitDefinition(LengthUnit.Meter, "Meter", "Meters", null!)); + } +} diff --git a/UnitsNet.Tests/UnitMathTests.cs b/UnitsNet.Tests/UnitMathTests.cs index 1972e6fdc5..368d4a03dc 100644 --- a/UnitsNet.Tests/UnitMathTests.cs +++ b/UnitsNet.Tests/UnitMathTests.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using UnitsNet.Units; using Xunit; @@ -56,7 +57,7 @@ public void AverageOfEmptySourceThrowsException() [Fact] public void AverageOfLengthsCalculatesCorrectly() { - var units = new[] {Length.FromMeters(1), Length.FromCentimeters(50)}; + var units = new[] { Length.FromMeters(1), Length.FromCentimeters(50) }; Length average = units.Average(LengthUnit.Centimeter); @@ -69,11 +70,10 @@ public void AverageOfLengthsWithNullSelectorThrowsException() { var units = new[] { - new KeyValuePair("1", Length.FromMeters(1)), - new KeyValuePair("2", Length.FromCentimeters(50)) + new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50)) }; - - Assert.Throws(() => units.Average((Func, Length>) null!, LengthUnit.Centimeter)); + + Assert.Throws(() => units.Average((Func, Length>)null!, LengthUnit.Centimeter)); } [Fact] @@ -81,8 +81,7 @@ public void AverageOfLengthsWithSelectorCalculatesCorrectly() { var units = new[] { - new KeyValuePair("1", Length.FromMeters(1)), - new KeyValuePair("2", Length.FromCentimeters(50)) + new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50)) }; Length average = units.Average(x => x.Value, LengthUnit.Centimeter); @@ -114,7 +113,7 @@ public void MaxOfEmptySourceThrowsException() [Fact] public void MaxOfLengthsCalculatesCorrectly() { - var units = new[] {Length.FromMeters(1), Length.FromCentimeters(50)}; + var units = new[] { Length.FromMeters(1), Length.FromCentimeters(50) }; Length max = units.Max(LengthUnit.Centimeter); @@ -127,11 +126,10 @@ public void MaxOfLengthsWithNullSelectorThrowsException() { var units = new[] { - new KeyValuePair("1", Length.FromMeters(1)), - new KeyValuePair("2", Length.FromCentimeters(50)) + new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50)) }; - Assert.Throws(() => units.Max((Func, Length>) null!, LengthUnit.Centimeter)); + Assert.Throws(() => units.Max((Func, Length>)null!, LengthUnit.Centimeter)); } [Fact] @@ -139,8 +137,7 @@ public void MaxOfLengthsWithSelectorCalculatesCorrectly() { var units = new[] { - new KeyValuePair("1", Length.FromMeters(1)), - new KeyValuePair("2", Length.FromCentimeters(50)) + new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50)) }; Length max = units.Max(x => x.Value, LengthUnit.Centimeter); @@ -172,7 +169,7 @@ public void MinOfEmptySourceThrowsException() [Fact] public void MinOfLengthsCalculatesCorrectly() { - var units = new[] {Length.FromMeters(1), Length.FromCentimeters(50)}; + var units = new[] { Length.FromMeters(1), Length.FromCentimeters(50) }; Length min = units.Min(LengthUnit.Centimeter); @@ -180,16 +177,26 @@ public void MinOfLengthsCalculatesCorrectly() Assert.Equal(LengthUnit.Centimeter, min.Unit); } + [Fact] + public void MinOfLengthsCalculatesCorrectlyWithLinq() + { + var units = new[] { Length.FromMeters(1), Length.FromCentimeters(50) }; + + Length min = units.Min(); + + Assert.Equal(50, min.Value); + Assert.Equal(LengthUnit.Centimeter, min.Unit); + } + [Fact] public void MinOfLengthsWithNullSelectorThrowsException() { var units = new[] { - new KeyValuePair("1", Length.FromMeters(1)), - new KeyValuePair("2", Length.FromCentimeters(50)) + new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50)) }; - Assert.Throws(() => units.Min((Func, Length>) null!, LengthUnit.Centimeter)); + Assert.Throws(() => units.Min((Func, Length>)null!, LengthUnit.Centimeter)); } [Fact] @@ -197,8 +204,7 @@ public void MinOfLengthsWithSelectorCalculatesCorrectly() { var units = new[] { - new KeyValuePair("1", Length.FromMeters(1)), - new KeyValuePair("2", Length.FromCentimeters(50)) + new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50)) }; Length min = units.Min(x => x.Value, LengthUnit.Centimeter); @@ -220,7 +226,7 @@ public void SumOfEmptySourceReturnsZero() [Fact] public void SumOfLengthsCalculatesCorrectly() { - var units = new[] {Length.FromMeters(1), Length.FromCentimeters(50)}; + var units = new[] { Length.FromMeters(1), Length.FromCentimeters(50) }; Length sum = units.Sum(LengthUnit.Centimeter); @@ -233,11 +239,10 @@ public void SumOfLengthsWithNullSelectorThrowsException() { var units = new[] { - new KeyValuePair("1", Length.FromMeters(1)), - new KeyValuePair("2", Length.FromCentimeters(50)) + new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50)) }; - Assert.Throws(() => units.Sum((Func, Length>) null!, LengthUnit.Centimeter)); + Assert.Throws(() => units.Sum((Func, Length>)null!, LengthUnit.Centimeter)); } [Fact] @@ -245,8 +250,7 @@ public void SumOfLengthsWithSelectorCalculatesCorrectly() { var units = new[] { - new KeyValuePair("1", Length.FromMeters(1)), - new KeyValuePair("2", Length.FromCentimeters(50)) + new KeyValuePair("1", Length.FromMeters(1)), new KeyValuePair("2", Length.FromCentimeters(50)) }; Length sum = units.Sum(x => x.Value, LengthUnit.Centimeter); diff --git a/UnitsNet.Tests/UnitSystemTests.cs b/UnitsNet.Tests/UnitSystemTests.cs index 4b21aac342..910d401589 100644 --- a/UnitsNet.Tests/UnitSystemTests.cs +++ b/UnitsNet.Tests/UnitSystemTests.cs @@ -34,11 +34,19 @@ public void ConstructorThrowsArgumentNullExceptionForNullBaseUnits() [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, null, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)] [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, null, LuminousIntensityUnit.Candela)] [InlineData(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, null)] - public void ConstructorThrowsArgumentExceptionWithUndefinedUnits(LengthUnit? length, MassUnit? mass, DurationUnit? time, ElectricCurrentUnit? current, + public void ConstructorSupportPartialDimensions(LengthUnit? length, MassUnit? mass, DurationUnit? time, ElectricCurrentUnit? current, TemperatureUnit? temperature, AmountOfSubstanceUnit? amount, LuminousIntensityUnit? luminousIntensity) { var baseUnits = new BaseUnits(length, mass, time, current, temperature, amount, luminousIntensity); - Assert.Throws(() => new UnitSystem(baseUnits)); + var unitSystem = new UnitSystem(baseUnits); + + Assert.Equal(unitSystem.BaseUnits, baseUnits); + } + + [Fact] + public void ConstructorThrowsArgumentExceptionWithUndefinedUnits() + { + Assert.Throws(() => new UnitSystem(BaseUnits.Undefined)); } [Fact] @@ -136,6 +144,20 @@ public void InequalityOperatorIsImplementedCorrectly() Assert.False(nullUnitSystem1 != nullUnitSystem2); } + [Fact] + public void GetHashCodeIsImplementedCorrectly() + { + var baseUnits1 = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, + AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); + var baseUnits2 = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, + AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); + + var unitSystem1 = new UnitSystem(baseUnits1); + var unitSystem2 = new UnitSystem(baseUnits2); + + Assert.Equal(unitSystem1.GetHashCode(), unitSystem2.GetHashCode()); + } + [Fact] public void SIUnitSystemHasCorrectBaseUnits() { diff --git a/UnitsNet.Tests/UnitsNet.Tests.csproj b/UnitsNet.Tests/UnitsNet.Tests.csproj index e7d635d49d..7acaa099f4 100644 --- a/UnitsNet.Tests/UnitsNet.Tests.csproj +++ b/UnitsNet.Tests/UnitsNet.Tests.csproj @@ -1,7 +1,7 @@  - net8.0;net9.0 + net48;net8.0;net9.0 latest enable true @@ -31,11 +31,17 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + + + + + + + diff --git a/UnitsNet.slnx b/UnitsNet.slnx index 25055fc949..b2540cbfdb 100644 --- a/UnitsNet.slnx +++ b/UnitsNet.slnx @@ -50,6 +50,8 @@ + + diff --git a/UnitsNet/Comparison.cs b/UnitsNet/Comparison.cs index 3c38a83672..07e84c0326 100644 --- a/UnitsNet/Comparison.cs +++ b/UnitsNet/Comparison.cs @@ -3,140 +3,138 @@ using System; -namespace UnitsNet +namespace UnitsNet; + +/// +/// Helper methods to perform relative and absolute comparison. +/// +public static class Comparison { /// - /// Helper methods to perform relative and absolute comparison. + /// + /// 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); + /// + /// + /// /// - public static class Comparison + /// + /// 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. + /// True if the two values are equal within the given tolerance, otherwise false. + /// Thrown when the is negative. + public static bool Equals(QuantityValue referenceValue, QuantityValue otherValue, QuantityValue tolerance, ComparisonType comparisonType) { - /// - /// - /// 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(double referenceValue, double otherValue, double tolerance, ComparisonType comparisonType) + return comparisonType switch { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0"); - - switch (comparisonType) - { - case ComparisonType.Relative: - return EqualsRelative(referenceValue, otherValue, tolerance); - case ComparisonType.Absolute: - return EqualsAbsolute(referenceValue, otherValue, tolerance); - default: - throw new InvalidOperationException("The given ComparisonType is not supported."); - } - } + ComparisonType.Relative => EqualsRelative(referenceValue, otherValue, tolerance), + ComparisonType.Absolute => EqualsAbsolute(referenceValue, otherValue, tolerance), + _ => throw new InvalidOperationException("The given ComparisonType is not supported.") + }; + } - /// - /// 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(double referenceValue, double otherValue, double tolerance) + /// + /// 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. + /// Thrown when the is negative. + public static bool EqualsRelative(QuantityValue referenceValue, QuantityValue otherValue, QuantityValue tolerance) + { + if (QuantityValue.IsNegative(tolerance)) { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0"); - - var maxVariation = Math.Abs(referenceValue * tolerance); - return Math.Abs(referenceValue - otherValue) <= maxVariation; + throw ExceptionHelper.CreateArgumentOutOfRangeExceptionForNegativeTolerance(nameof(tolerance)); } + + var maxVariation = QuantityValue.Abs(referenceValue) * tolerance; + return QuantityValue.Abs(referenceValue - otherValue) <= maxVariation; + } - /// - /// 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(double value1, double value2, double 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. + /// Thrown when the is negative. + public static bool EqualsAbsolute(QuantityValue value1, QuantityValue value2, QuantityValue tolerance) + { + if (QuantityValue.IsNegative(tolerance)) { - if (tolerance < 0) - throw new ArgumentOutOfRangeException(nameof(tolerance), "Tolerance must be greater than or equal to 0"); - - return Math.Abs(value1 - value2) <= tolerance; + throw ExceptionHelper.CreateArgumentOutOfRangeExceptionForNegativeTolerance(nameof(tolerance)); } - internal static int GetHashCode(TUnit unit, double value) - where TUnit : struct, Enum - { + return QuantityValue.Abs(value1 - value2) <= tolerance; + } + + internal static int GetHashCode(Type type, QuantityValue value) + { #if NET7_0_OR_GREATER - return HashCode.Combine(typeof(TUnit), unit, value); -#else - unchecked - { - var hash = 17; - hash = hash * 23 + typeof(TUnit).GetHashCode(); - hash = hash * 23 + unit.GetHashCode(); - hash = hash * 23 + value.GetHashCode(); - return hash; - } -#endif + return HashCode.Combine(type, value); + #else + unchecked + { + var hash = 17; + hash = hash * 23 + type.GetHashCode(); + hash = hash * 23 + value.GetHashCode(); + return hash; } +#endif } } diff --git a/UnitsNet/CompiledLambdas.cs b/UnitsNet/CompiledLambdas.cs index 56790cadaa..7d59bdd612 100644 --- a/UnitsNet/CompiledLambdas.cs +++ b/UnitsNet/CompiledLambdas.cs @@ -3,6 +3,7 @@ namespace UnitsNet { +#if COMPILED_LAMBDAS_ENABLED /// /// Compiled lambda expressions that can be invoked with generic run-time parameters. This is used for performance as /// it is far faster than reflection based alternatives. @@ -309,4 +310,5 @@ private static Func CreateBinaryFunction +/// Serves as a debug display proxy for a quantity, providing a convenient way to view various components of the +/// quantity during debugging. +/// +/// +/// This struct provides a structured view of a quantity's components such as abbreviation, unit, value, and convertor +/// during debugging. +/// Each component is represented by a nested struct, which can be expanded in the debugger to inspect its properties. +/// +public readonly struct QuantityDebugProxy: IFormattable +{ + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly IQuantity _quantity; + + /// + /// Serves as a debug display proxy for a quantity, providing a convenient way to view various components of the + /// quantity during debugging. + /// + /// + /// This struct provides a structured view of a quantity's components such as abbreviation, unit, value, and convertor + /// during debugging. + /// Each component is represented by a nested struct, which can be expanded in the debugger to inspect its properties. + /// + public QuantityDebugProxy(IQuantity quantity) + // we want to avoid initializing the default configuration from the debug proxy (e.g. when debugging the configuration initialization) + : this(quantity, GetConfiguration(quantity.QuantityInfo)) + { + } + + /// + /// Initializes a new instance of the class with the specified quantity and + /// configuration. + /// + /// The quantity to be displayed, providing value and unit information. + /// The configuration settings for formatting and displaying the quantity. + public QuantityDebugProxy(IQuantity quantity, UnitsNetSetup configuration) + { + _quantity = quantity; + Configuration = configuration; + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + internal UnitsNetSetup Configuration { get; } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + internal QuantityInfo QuantityInfo + { + get => _quantity.QuantityInfo; + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + internal UnitKey UnitKey + { + get => _quantity.UnitKey; + } + + internal QuantityDebugProxy ConvertTo(UnitInfo unit) + { + return new QuantityDebugProxy(ConvertToUnit(unit), Configuration); + } + + internal IQuantity ConvertToUnit(UnitInfo unit) + { + return Configuration.UnitConverter.ConvertTo(_quantity, unit.UnitKey); + } + + internal IQuantity ConvertToQuantity(QuantityInfo targetQuantity) + { + return Configuration.UnitConverter.ConvertTo(_quantity.Value, _quantity.UnitKey, targetQuantity); + } + + /// + /// Gets the quantity information, which includes details about the quantity's definition + /// and its associated configuration. + /// + /// + /// An instance of that provides metadata and context + /// for the quantity represented by this . + /// + public QuantityInformation Quantity + { + get => new(this); + } + + /// + /// Gets information about the unit associated with the quantity. + /// + /// + /// This property provides detailed information about the unit, including its name, abbreviation, and other metadata. + /// + public UnitInformation Unit + { + get => new(this, _quantity.QuantityInfo[_quantity.UnitKey]); + } + + /// + /// Gets the display representation of the unit abbreviation for the quantity. + /// + /// + /// This property provides a formatted display of the unit abbreviation based on the quantity and configuration. + /// + /// + /// An instance representing the unit abbreviation. + /// + public UnitAbbreviation UnitAbbreviation + { + get => new(this); + } + + /// + /// Gets the numeric value of the quantity represented by this instance. + /// + /// + /// This property retrieves the underlying numeric value of the quantity, + /// which is represented as a . It provides a way + /// to access the raw value of the quantity without any associated unit or formatting. + /// + /// + /// The numeric value of the quantity. + /// + public QuantityValue Value + { + get => _quantity.Value; + } + + /// + /// Gets the display formats for the value of the quantity. + /// + /// + /// This property provides access to various string formats that can be used to represent + /// the value of the quantity in different ways, depending on the configuration and context. + /// + public QuantityFormats ValueFormats => new(this); + + /// + /// Returns a string representation of the quantity using the configured formatter. + /// + /// + /// This method utilizes the to format the quantity. + /// The output is typically intended for debugging or display purposes and adheres to the + /// formatting rules defined in the current configuration. + /// + /// + /// A string representation of the quantity. + /// + public override string ToString() + { + return ToString(DefaultFormatSpecifier); + } + + /// + /// Returns a string representation of the quantity debug proxy, formatted according to the specified format string. + /// + /// + /// A format string that specifies how the quantity should be formatted. If null, the default format specifier + /// is used. + /// + /// + /// A string representation of the quantity debug proxy, formatted according to the specified format string. + /// + /// + /// This method provides a way to customize the string representation of the quantity debug proxy for debugging + /// purposes. + /// + public string ToString(string format) + { + return ToString(format, DefaultFormatProvider); + } + + /// + /// Converts the quantity to its string representation using the specified format and format provider. + /// + /// + /// A standard or custom format string that determines how the quantity is formatted. + /// If null, a default format is used. + /// + /// + /// An object that provides culture-specific formatting information. If null, the current culture is used. + /// + /// + /// A string representation of the quantity, formatted according to the specified format and format provider. + /// + /// + /// This method utilizes the to format the quantity. + /// The resulting string typically includes the quantity's value and its unit abbreviation. + /// + public string ToString(string? format, IFormatProvider? formatProvider) + { + return Configuration.Formatter.Format(_quantity, format, formatProvider); + } + + /// + /// The default display format string used for debugging quantities. + /// + /// + /// This constant defines the format string applied to quantities when displayed in the debugger. + /// It utilizes the to format the quantity's value and unit + /// in a concise and human-readable manner. + /// + public const string DisplayFormat = "{UnitsNet.Debug.QuantityDebugProxy.Format(this), nq}"; + + internal static UnitsNetSetup GetConfiguration(QuantityInfo quantityInfo) + { + if (UnitsNetSetup.DefaultConfiguration.IsValueCreated) + { + // we could check for UnitsNetSetup.Default.QuantityInfoLookup.ByName.ContainsKey(quantity.QuantityInfo.Name) + // but that would cause the initialization of the lazy dictionary and would hide potential issues with quantities that are not part of the default configuration + return UnitsNetSetup.Default; + } + + return UnitsNetSetup.Create(builder => builder.WithQuantities([quantityInfo])); + } + + /// + /// The default format string used for debugging representations of quantities. + /// + /// + /// This format string is applied when no specific format is provided during the formatting + /// of a quantity for debugging purposes. The default value is "G", which represents the general format. + /// + public static string DefaultFormatSpecifier = "G"; + + /// + /// Gets or sets the default format provider used for formatting quantities in debug scenarios. + /// + /// + /// This field determines the culture-specific formatting rules applied when formatting quantities. + /// If set to null, the default culture of the current thread is used. + /// + public static CultureInfo? DefaultFormatProvider = null; + + /// + /// Formats the specified quantity into its string representation using the provided format. + /// + /// + /// The quantity to be formatted. This includes its value and associated unit. + /// + /// + /// A standard or custom format string that determines how the quantity is formatted. + /// If null, a default format is used. + /// + /// + /// A string representation of the quantity, formatted according to the specified format. + /// + /// + /// This method creates a instance for the given quantity + /// and utilizes its method + /// to generate the formatted string. + /// + public static string Format(TQuantity quantity, string? format = null) + where TQuantity : IQuantity + { + try + { + UnitsNetSetup configuration = GetConfiguration(quantity.QuantityInfo); + return configuration.Formatter.Format(quantity, format ?? DefaultFormatSpecifier, DefaultFormatProvider); + } + catch (Exception) + { + // the debugger's inline evaluator sometimes fails when working with Type objects (specifically on the first call) + // see https://youtrack.jetbrains.com/issue/RSRP-499956/Local-Variable-Inline-Evaluation-Fails-for-System.Type + return $"{{{quantity.Value} {quantity.QuantityInfo[quantity.UnitKey].PluralName}}}"; + } + } +} diff --git a/UnitsNet/CustomCode/Debug/QuantityFormats.cs b/UnitsNet/CustomCode/Debug/QuantityFormats.cs new file mode 100644 index 0000000000..85d3ec9562 --- /dev/null +++ b/UnitsNet/CustomCode/Debug/QuantityFormats.cs @@ -0,0 +1,164 @@ +using System.ComponentModel; +using System.Diagnostics; + +namespace UnitsNet.Debug; + +/// +/// Represents a display of string formats for a quantity, providing formatted string representations +/// such as general and short formats. +/// +/// +/// This struct is used to format and display quantities in various string representations, +/// leveraging the configuration provided by . +/// +// [DebuggerDisplay("{GeneralFormat}")] +// [DebuggerDisplay("{ShortFormat}")] +[DebuggerDisplay("{ToString()}")] +[EditorBrowsable(EditorBrowsableState.Never)] +public readonly struct QuantityFormats +{ + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly QuantityDebugProxy _quantityProxy; + + internal QuantityFormats(QuantityDebugProxy quantityProxy) + { + _quantityProxy = quantityProxy; + } + + /// + /// Gets the general string representation of the quantity using the default general format specifier ("G"). + /// + /// + /// A string representing the quantity in a general format. + /// + /// + /// This property utilizes the to format the quantity + /// with the general format specifier defined by . + /// + public string GeneralFormat + { + get => _quantityProxy.ToString(GeneralFormatSpecifier); + } + + /// + /// Gets the scientific format representation of the quantity. + /// + /// + /// The scientific format uses the "E" format specifier, which represents the quantity + /// in exponential notation, suitable for displaying very large or very small values. + /// + public string ScientificFormat + { + get => _quantityProxy.ToString(ScientificFormatSpecifier); + } + + /// + /// Gets the fixed-point format representation of the quantity. + /// + /// + /// This property formats the quantity using the fixed-point format specifier ("F"). + /// It provides a string representation of the quantity with a fixed number of decimal places. + /// + /// + /// A string representing the quantity in fixed-point format. + /// + public string FixedPointFormat + { + get => _quantityProxy.ToString(FixedPointFormatSpecifier); + } + + /// + /// Gets the number format representation of the quantity. + /// + /// + /// This property formats the quantity using the "N" format specifier, which typically represents + /// a numeric format with thousands separators and a fixed number of decimal places, depending on + /// the current culture settings. + /// + /// + /// A string representing the quantity in the number format. + /// + public string NumberFormat + { + get => _quantityProxy.ToString(NumberFormatSpecifier); + } + + /// + /// Gets the short format string representation of the quantity. + /// + /// + /// The short format is typically a concise representation of the quantity, + /// formatted using the "s" format specifier. This is useful for scenarios + /// where a compact display of the quantity is required. + /// + /// + /// A string representing the quantity in its short format. + /// + public string ShortFormat + { + get => _quantityProxy.ToString(ShortFormatSpecifier); + } + + /// + public override string ToString() + { + return _quantityProxy.ToString(); + } + + /// + /// The default format specifier used for general formatting of quantities. + /// + /// + /// This field defines the format string "G", which represents the general format for quantities. + /// It is primarily used to provide a consistent and human-readable representation of quantities + /// when no specific format is explicitly provided. + /// + public static string GeneralFormatSpecifier = "G"; + + /// + /// The default format specifier used for scientific formatting of quantities. + /// + /// + /// This field defines the format string "E", which represents the scientific format for quantities. + /// It is primarily used to display quantities in exponential notation, providing a concise representation + /// of very large or very small values. + /// + public static string ScientificFormatSpecifier = "E"; + + /// + /// The default format specifier used for fixed-point formatting of quantities. + /// + /// + /// This field defines the format string "F", which represents the fixed-point format for quantities. + /// It is primarily used to display quantities with a fixed number of decimal places, ensuring precision + /// and consistency in numerical representation. + /// + public static string FixedPointFormatSpecifier = "F"; + + /// + /// The default format specifier used for fixed-point formatting of quantities. + /// + /// + /// This field defines the format string "F", which represents the fixed-point format for quantities. + /// It is primarily used to display quantities with a fixed number of decimal places, ensuring precision + /// and consistency in numerical representation. + /// + /// + /// The default format specifier used for numeric formatting of quantities. + /// + /// + /// This field defines the format string "N", which represents the numeric format for quantities. + /// It is used to display quantities with a standard numeric representation, including grouping + /// separators and a configurable number of decimal places. + /// + public static string NumberFormatSpecifier = "N"; + + /// + /// Specifies the format string used to represent a quantity in a short format. + /// + /// + /// The short format specifier is typically used to produce a concise representation + /// of a quantity, often including only the numerical value and a minimal unit abbreviation. + /// + public static string ShortFormatSpecifier = "S"; +} diff --git a/UnitsNet/CustomCode/Debug/QuantityInformation.cs b/UnitsNet/CustomCode/Debug/QuantityInformation.cs new file mode 100644 index 0000000000..2a8b3b7ec0 --- /dev/null +++ b/UnitsNet/CustomCode/Debug/QuantityInformation.cs @@ -0,0 +1,199 @@ +using System; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; + +namespace UnitsNet.Debug; + +/// +/// Represents detailed information about a quantity, including its definition, unit conversions, and quantity +/// conversions. +/// +/// +/// This struct is primarily used for debugging purposes to provide a comprehensive view of a quantity's components. +/// It includes the quantity's definition, available unit conversions, and possible quantity conversions. +/// +[DebuggerDisplay("{Definition.Name, nq}")] +[EditorBrowsable(EditorBrowsableState.Never)] +public readonly struct QuantityInformation +{ + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly QuantityDebugProxy _quantityProxy; + + internal QuantityInformation(QuantityDebugProxy quantityProxy) + { + _quantityProxy = quantityProxy; + Definition = quantityProxy.QuantityInfo; + } + + /// + /// Gets the definition of the quantity, which includes its name, base unit, and other metadata. + /// + /// + /// The provides detailed information about the quantity, + /// such as its name, available units, and base dimensions. This property is useful for understanding + /// the structure and characteristics of the quantity. + /// + // [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public QuantityInfo Definition { get; } + + /// + /// Gets the array of unit conversions available for the quantity. + /// + /// + /// Each element in the array represents a conversion of the quantity to a specific unit, + /// including its value in that unit, unit details, and formatted string representation. + /// This property provides a detailed view of how the quantity can be expressed in different units. + /// + public ConvertedQuantity[] UnitConversions + { + get + { + QuantityDebugProxy quantityProxy = _quantityProxy; + return Definition.UnitInfos.Select(unitInfo => new ConvertedQuantity(quantityProxy, unitInfo)).ToArray(); + } + } + + /// + /// Gets the array of quantity conversions available for the current quantity. + /// + /// + /// Each represents a possible transformation from the current quantity + /// to another quantity type, enabling conversions between different quantity types within the UnitsNet library. + /// + public QuantityConversion[] QuantityConversions + { + get + { + QuantityDebugProxy quantityProxy = _quantityProxy; + return _quantityProxy.Configuration.UnitConverter.QuantityConversions.GetConversionsFrom(Definition) + .Select(targetQuantity => new QuantityConversion(quantityProxy, targetQuantity)).ToArray(); + } + } + + /// + public override string ToString() + { + return Definition.Name; + } +} + +/// +/// Represents a converted quantity, which includes the value of the quantity in a specific unit, +/// its associated unit information, and its abbreviation display. +/// +/// +/// This struct is used to provide detailed information about a quantity converted to a specific unit, +/// including its value, unit details, and formatted string representation. +/// +[DebuggerDisplay("{ToString(), nq}")] +[EditorBrowsable(EditorBrowsableState.Never)] +public readonly struct ConvertedQuantity +{ + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly QuantityDebugProxy _quantityProxy; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly UnitInfo _targetUnit; + + internal ConvertedQuantity(QuantityDebugProxy quantityProxy, UnitInfo targetUnit) + { + _quantityProxy = quantityProxy; + _targetUnit = targetUnit; + } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private QuantityDebugProxy Converted + { + get => _quantityProxy.ConvertTo(_targetUnit); + } + + /// + /// Gets detailed information about the unit associated with the converted quantity. + /// + /// + /// This property provides metadata about the unit, including its definition and possible conversions. + /// It is useful for accessing unit-related details and performing operations within the context of the converted + /// quantity. + /// + public UnitInformation Unit + { + get => new(_quantityProxy, _targetUnit); + } + + /// + /// Gets the display information for the unit abbreviation of the converted quantity. + /// + /// + /// This property provides access to the default and parseable abbreviations for the unit of the converted quantity. + /// It allows for consistent and localized representation of unit abbreviations. + /// + public UnitAbbreviation UnitAbbreviation + { + get => new(Converted); + } + + /// + /// Gets the numerical value of the converted quantity in its specific unit. + /// + /// + /// This property provides the raw numerical representation of the quantity after it has been converted + /// to the specified unit. It is useful for calculations or comparisons involving the converted quantity. + /// + public QuantityValue Value + { + get => Converted.Value; + } + + /// + public override string ToString() + { + return Converted.ToString(); + } +} + +/// +/// Represents a conversion between two quantities, allowing for the transformation of a quantity's value +/// from one unit system to another. This struct is used to facilitate conversions between different +/// quantity types within the context of the UnitsNet library. +/// +[DebuggerDisplay("{ToString()}")] +[EditorBrowsable(EditorBrowsableState.Never)] +public readonly struct QuantityConversion +{ + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly QuantityDebugProxy _quantityProxy; + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly QuantityInfo _targetQuantity; + + internal QuantityConversion(QuantityDebugProxy quantityProxy, QuantityInfo targetQuantity) + { + _quantityProxy = quantityProxy; + _targetQuantity = targetQuantity; + } + + /// + /// Gets the converted quantity as an instance. + /// This property performs the conversion of the original quantity to the target quantity type + /// using the specified unit conversion logic. + /// + /// + /// The converted quantity represented as an . + /// + /// + /// This property utilizes the to transform the value and unit of the original quantity + /// into the corresponding representation in the target quantity type. + /// + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public IQuantity Quantity + { + get => _quantityProxy.ConvertToQuantity(_targetQuantity); + } + + /// + public override string ToString() + { + return _targetQuantity.ToString(); + } +} diff --git a/UnitsNet/CustomCode/Debug/UnitAbbreviation.cs b/UnitsNet/CustomCode/Debug/UnitAbbreviation.cs new file mode 100644 index 0000000000..efec5985e3 --- /dev/null +++ b/UnitsNet/CustomCode/Debug/UnitAbbreviation.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.Linq; + +namespace UnitsNet.Debug; + +/// +/// Represents the display information for unit abbreviations associated with a specific quantity. +/// +/// +/// This struct provides access to default and parseable abbreviations for units, as well as the default abbreviation +/// for the current unit of the quantity. +/// +[DebuggerDisplay("{DefaultAbbreviation}")] +[EditorBrowsable(EditorBrowsableState.Never)] +public readonly struct UnitAbbreviation +{ + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly QuantityDebugProxy _quantityProxy; + + internal UnitAbbreviation(QuantityDebugProxy quantityProxy) + { + _quantityProxy = quantityProxy; + Abbreviations = quantityProxy.Configuration.UnitAbbreviations.GetUnitAbbreviations(quantityProxy.UnitKey, QuantityDebugProxy.DefaultFormatProvider); + } + + /// + /// Gets the default abbreviation for the current unit of the quantity. + /// + /// + /// The default abbreviation is determined based on the unit key of the quantity and the configured unit abbreviations + /// cache. + /// + /// + /// A representing the default abbreviation for the current unit. + /// + /// + /// Thrown when no unit information is found for the specified unit key. + /// + /// + /// Thrown when no abbreviations are mapped for the specified unit. + /// + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public string DefaultAbbreviation + { + get => Abbreviations[0]; + } + + /// + /// Gets a read-only list of unit abbreviations associated with the current quantity. + /// + /// + /// This property provides all abbreviations that can represent the unit of the current quantity. + /// These abbreviations are culture-sensitive and may vary depending on the localization settings. + /// + /// + /// A read-only list of strings representing the unit abbreviations. + /// + /// + /// Thrown when no unit information is found for the specified unit key. + /// + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public IReadOnlyList Abbreviations { get; } + + /// + /// Gets the collection of parseable unit abbreviations for the associated quantity. + /// + /// + /// This property provides an array of objects, + /// each representing the abbreviations that can be parsed for a specific unit of the quantity. + /// + public UnitAbbreviations[] UnitAbbreviations + { + get + { + QuantityDebugProxy quantityProxy = _quantityProxy; + return quantityProxy.QuantityInfo.UnitInfos.Select(targetUnit => new UnitAbbreviations(quantityProxy, targetUnit)).ToArray(); + } + } + + /// + public override string ToString() + { + return DefaultAbbreviation; + } +} + +/// +/// Represents a collection of unit abbreviations for a specific unit of a quantity. +/// +/// +/// This struct provides access to the unit's abbreviations and allows conversion of the quantity to the specified +/// unit. +/// +[DebuggerDisplay("{ToString(), nq}")] +[EditorBrowsable(EditorBrowsableState.Never)] +public readonly struct UnitAbbreviations +{ + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private QuantityDebugProxy QuantityProxy { get; } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private UnitInfo TargetUnit { get; } + + internal UnitAbbreviations(QuantityDebugProxy quantityProxy, UnitInfo targetUnit) + { + QuantityProxy = quantityProxy; + TargetUnit = targetUnit; + } + + /// + /// Gets a debug proxy representation of the quantity associated with the current unit. + /// + /// + /// This property provides a converted view of the quantity in the context of the specified unit, + /// enabling detailed inspection of its components during debugging. + /// + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public QuantityDebugProxy Quantity + { + get => QuantityProxy.ConvertTo(TargetUnit); + } + + /// + /// Gets the list of abbreviations associated with the target unit. + /// + /// + /// The abbreviations are retrieved from the configured in the + /// . These abbreviations are culture-sensitive and may vary based on the + /// current culture or a fallback culture. + /// + /// + /// A read-only list of strings representing the abbreviations for the target unit. + /// + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + public IReadOnlyList Abbreviations + { + get => QuantityProxy.Configuration.UnitAbbreviations.GetAbbreviationsWithFallbackCulture(TargetUnit, QuantityDebugProxy.DefaultFormatProvider ?? CultureInfo.CurrentCulture); + } + + /// + public override string ToString() + { + return string.Join(", ", Abbreviations.Select(x => $"\"{x}\"")); + } +} diff --git a/UnitsNet/CustomCode/Debug/UnitInformation.cs b/UnitsNet/CustomCode/Debug/UnitInformation.cs new file mode 100644 index 0000000000..9f48f68a91 --- /dev/null +++ b/UnitsNet/CustomCode/Debug/UnitInformation.cs @@ -0,0 +1,107 @@ +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; + +namespace UnitsNet.Debug; + +/// +/// Represents information about a specific unit within a quantity. +/// +/// +/// This struct provides details about a unit, including its definition and possible conversions. +/// It is used to encapsulate unit-related metadata and operations within the context of a quantity. +/// +[DebuggerDisplay("{Definition.Name, nq}")] +[EditorBrowsable(EditorBrowsableState.Never)] +public readonly struct UnitInformation +{ + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private readonly QuantityDebugProxy _quantityProxy; + + internal UnitInformation(QuantityDebugProxy quantityProxy, UnitInfo unitInfo) + { + _quantityProxy = quantityProxy; + Definition = unitInfo; + } + + /// + /// Gets the definition of the unit, including its metadata and associated details. + /// + /// + /// This property provides access to the unit's definition, which includes its name, value, and other metadata. + /// It is useful for retrieving information about the specific unit represented within the context of a quantity. + /// + // [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public UnitInfo Definition { get; } + + /// + /// Gets the collection of unit conversions associated with the current unit. + /// + /// + /// Each in the collection represents a possible conversion + /// from the current unit to another unit within the same quantity. + /// This property is useful for enumerating all available conversions for a unit. + /// + public UnitConversion[] UnitConversions + { + get + { + QuantityDebugProxy quantityProxy = _quantityProxy; + return quantityProxy.QuantityInfo.UnitInfos.Select(unit => new UnitConversion(quantityProxy, unit)).ToArray(); + } + } + + /// + public override string ToString() + { + return Definition.ToString(); + } +} + +/// +/// Represents a unit conversion for a specific quantity and unit type. +/// +/// +/// This struct provides functionality to convert a quantity to a specific unit and retrieve its display +/// representation. +/// It is primarily used internally within the struct. +/// +[DebuggerDisplay("{TargetUnit.Value, nq}")] +[EditorBrowsable(EditorBrowsableState.Never)] +public readonly struct UnitConversion +{ + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private QuantityDebugProxy QuantityProxy { get; } + + [DebuggerBrowsable(DebuggerBrowsableState.Never)] + private UnitInfo TargetUnit { get; } + + internal UnitConversion(QuantityDebugProxy quantityProxy, UnitInfo targetUnit) + { + QuantityProxy = quantityProxy; + TargetUnit = targetUnit; + } + + /// + /// Gets the quantity representation after converting to the specified unit. + /// + /// + /// This property provides a instance that represents the quantity + /// converted to the unit specified by the . + /// It utilizes the for the conversion process. + /// + /// + /// A instance representing the converted quantity. + /// + [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] + public QuantityDebugProxy Quantity + { + get => QuantityProxy.ConvertTo(TargetUnit); + } + + /// + public override string ToString() + { + return TargetUnit.ToString(); + } +} diff --git a/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs b/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs index 83b85777cf..7dd045910f 100644 --- a/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs +++ b/UnitsNet/CustomCode/Quantities/AmountOfSubstance.extra.cs @@ -22,16 +22,15 @@ public partial struct AmountOfSubstance /// is planned to take effect on 20 May 2019. The value of the constant will be fixed to exactly 6.02214076×1023 mol−1. /// See here: https://www.bipm.org/utils/common/pdf/CGPM-2018/26th-CGPM-Resolutions.pdf /// - public static double AvogadroConstant { get; } = 6.02214076e23; + public static QuantityValue AvogadroConstant { get; } = 6.02214076e23m; /// /// Calculates the number of particles (atoms or molecules) in this amount of substance using the . /// /// The number of particles (atoms or molecules) in this amount of substance. - public double NumberOfParticles() + public QuantityValue NumberOfParticles() { - var moles = ToUnit(AmountOfSubstanceUnit.Mole); - return AvogadroConstant * moles.Value; + return AvogadroConstant * this.As(AmountOfSubstanceUnit.Mole); } /// Get from and a given . diff --git a/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs b/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs index cc0a3cfcdf..2708b6144c 100644 --- a/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs +++ b/UnitsNet/CustomCode/Quantities/AmplitudeRatio.extra.cs @@ -15,43 +15,57 @@ public partial struct AmplitudeRatio /// resistance. /// /// The electric potential referenced to one volt. - public AmplitudeRatio(ElectricPotential voltage) + /// The number of significant digits to use in the calculation. Default is 15. + /// + /// Thrown when the number of significant digits is less than 1 or greater than 17. + /// + public AmplitudeRatio(ElectricPotential voltage, byte significantDigits = 15) : this() { - if (voltage.Volts <= 0) + if (!QuantityValue.IsPositive(voltage.Value)) + { throw new ArgumentOutOfRangeException( nameof(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 = voltage.Volts.ToLogSpace(LogarithmicScalingFactor, significantDigits); _unit = AmplitudeRatioUnit.DecibelVolt; } /// /// Gets an from this . /// + /// The number of significant digits to use in the calculation. Default is 15. + /// + /// Thrown when the number of significant digits is less than 1 or greater than 17. + /// /// /// Provides a nicer syntax for converting an amplitude ratio back to a voltage. /// /// var voltage = voltageRatio.ToElectricPotential(); /// /// - public ElectricPotential ToElectricPotential() + public ElectricPotential ToElectricPotential(byte significantDigits = 15) { // E(V) = 1V * 10^(E(dBV)/20) - return ElectricPotential.FromVolts( Math.Pow( 10, DecibelVolts / 20 ) ); + return ElectricPotential.FromVolts(DecibelVolts.ToLinearSpace(LogarithmicScalingFactor, significantDigits)); } /// /// Converts this to a . /// /// The input impedance of the load. This is usually 50, 75 or 600 ohms. + /// The number of significant digits to use in the calculation. Default is 15. + /// + /// Thrown when the number of significant digits is less than 1 or greater than 17. + /// /// http://www.maximintegrated.com/en/app-notes/index.mvp/id/808 - public PowerRatio ToPowerRatio( ElectricResistance impedance ) + public PowerRatio ToPowerRatio(ElectricResistance impedance, byte significantDigits = 15) { // P(dBW) = E(dBV) - 10*log10(Z(Ω)/1) - return PowerRatio.FromDecibelWatts( DecibelVolts - 10 * Math.Log10( impedance.Ohms / 1 ) ); + return PowerRatio.FromDecibelWatts(DecibelVolts - impedance.Ohms.ToLogSpace(LogarithmicScalingFactor / 2, significantDigits)); } #region Static Methods @@ -61,9 +75,13 @@ public PowerRatio ToPowerRatio( ElectricResistance impedance ) /// . /// /// The voltage (electric potential) relative to one volt RMS. - public static AmplitudeRatio FromElectricPotential(ElectricPotential voltage) + /// The number of significant digits to use in the calculation. Default is 15. + /// + /// Thrown when the number of significant digits is less than 1 or greater than 17. + /// + public static AmplitudeRatio FromElectricPotential(ElectricPotential voltage, byte significantDigits = 15) { - return new AmplitudeRatio(voltage); + return new AmplitudeRatio(voltage, significantDigits); } #endregion diff --git a/UnitsNet/CustomCode/Quantities/Area.extra.cs b/UnitsNet/CustomCode/Quantities/Area.extra.cs index 3a9d28e973..6fbe9158f7 100644 --- a/UnitsNet/CustomCode/Quantities/Area.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Area.extra.cs @@ -12,14 +12,14 @@ public partial struct Area /// Get circle area from a diameter. public static Area FromCircleDiameter(Length diameter) { - var radius = Length.FromMeters(diameter.Meters / 2d); + var radius = Length.FromMeters(diameter.Meters / 2); return FromCircleRadius(radius); } /// Get circle area from a radius. public static Area FromCircleRadius(Length radius) { - return FromSquareMeters(Math.PI * radius.Meters * radius.Meters); + return FromSquareMeters(QuantityValue.PI * radius.Meters * radius.Meters); } #endregion diff --git a/UnitsNet/CustomCode/Quantities/Duration.extra.cs b/UnitsNet/CustomCode/Quantities/Duration.extra.cs index b72b51285a..dbfdb9abd7 100644 --- a/UnitsNet/CustomCode/Quantities/Duration.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Duration.extra.cs @@ -2,101 +2,107 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; -using UnitsNet.Units; +using System.Numerics; -namespace UnitsNet +namespace UnitsNet; + +public partial struct Duration { - public partial struct Duration + /// + /// Convert a Duration to a TimeSpan. + /// + /// + /// Throws if the duration exceeds the . or + /// , which would cause it to roll over from positive to negative and vice versa. + /// + /// The TimeSpan with the same time as the duration + public TimeSpan ToTimeSpan() { - /// - /// Convert a Duration to a TimeSpan. - /// - /// - /// Throws if the duration exceeds the . or - /// , which would cause it to roll over from positive to negative and vice versa. - /// - /// The TimeSpan with the same time as the duration - public TimeSpan ToTimeSpan() + var ticks = (BigInteger)(Seconds * TimeSpan.TicksPerSecond); + if (ticks > TimeSpan.MaxValue.Ticks) { - if (Seconds > TimeSpan.MaxValue.TotalSeconds) throw new ArgumentOutOfRangeException(nameof(Seconds), - "The duration is too large for a TimeSpan, which would roll over from positive to negative."); - - if (Seconds < TimeSpan.MinValue.TotalSeconds) throw new ArgumentOutOfRangeException(nameof(Seconds), - "The duration is too small for a TimeSpan, which would roll over from negative to positive."); - - return TimeSpan.FromTicks((long)(Seconds * TimeSpan.TicksPerSecond)); + throw new ArgumentOutOfRangeException(nameof(ticks), + "The duration is too large for a TimeSpan, which would roll over from positive to negative."); } - /// Get from plus . - public static DateTime operator +(DateTime time, Duration duration) + if (ticks < TimeSpan.MinValue.Ticks) { - return time.AddSeconds(duration.Seconds); + throw new ArgumentOutOfRangeException(nameof(ticks), + "The duration is too small for a TimeSpan, which would roll over from negative to positive."); } - /// Get from minus . - public static DateTime operator -(DateTime time, Duration duration) - { - return time.AddSeconds(-duration.Seconds); - } + return TimeSpan.FromTicks((long)ticks); + } - /// Implicitly cast to . - public static implicit operator TimeSpan(Duration duration) - { - return duration.ToTimeSpan(); - } + /// Get from plus . + public static DateTime operator +(DateTime time, Duration duration) + { + return time + duration.ToTimeSpan(); + } - /// Implicitly cast to . - public static implicit operator Duration(TimeSpan duration) - { - return FromSeconds(duration.TotalSeconds); - } + /// Get from minus . + public static DateTime operator -(DateTime time, Duration duration) + { + return time - duration.ToTimeSpan(); + } - /// True if is less than . - public static bool operator <(Duration duration, TimeSpan timeSpan) - { - return duration.Seconds < timeSpan.TotalSeconds; - } + /// Implicitly cast to . + public static implicit operator TimeSpan(Duration duration) + { + return duration.ToTimeSpan(); + } - /// True if is greater than . - public static bool operator >(Duration duration, TimeSpan timeSpan) - { - return duration.Seconds > timeSpan.TotalSeconds; - } + /// Implicitly cast to . + public static implicit operator Duration(TimeSpan duration) + { + return FromSeconds(new QuantityValue(duration.Ticks, TimeSpan.TicksPerSecond)); + } - /// True if is less than or equal to . - public static bool operator <=(Duration duration, TimeSpan timeSpan) - { - return duration.Seconds <= timeSpan.TotalSeconds; - } + /// True if is less than . + public static bool operator <(Duration duration, TimeSpan timeSpan) + { + return duration.Seconds * TimeSpan.TicksPerSecond < timeSpan.Ticks; + } - /// True if is greater than or equal to . - public static bool operator >=(Duration duration, TimeSpan timeSpan) - { - return duration.Seconds >= timeSpan.TotalSeconds; - } + /// True if is greater than . + public static bool operator >(Duration duration, TimeSpan timeSpan) + { + return duration.Seconds * TimeSpan.TicksPerSecond > timeSpan.Ticks; + } - /// True if is less than . - public static bool operator <(TimeSpan timeSpan, Duration duration) - { - return timeSpan.TotalSeconds < duration.Seconds; - } + /// True if is less than or equal to . + public static bool operator <=(Duration duration, TimeSpan timeSpan) + { + return duration.Seconds * TimeSpan.TicksPerSecond <= timeSpan.Ticks; + } - /// True if is greater than . - public static bool operator >(TimeSpan timeSpan, Duration duration) - { - return timeSpan.TotalSeconds > duration.Seconds; - } + /// True if is greater than or equal to . + public static bool operator >=(Duration duration, TimeSpan timeSpan) + { + return duration.Seconds * TimeSpan.TicksPerSecond >= timeSpan.Ticks; + } - /// True if is less than or equal to . - public static bool operator <=(TimeSpan timeSpan, Duration duration) - { - return timeSpan.TotalSeconds <= duration.Seconds; - } + /// True if is less than . + public static bool operator <(TimeSpan timeSpan, Duration duration) + { + return timeSpan.Ticks < duration.Seconds * TimeSpan.TicksPerSecond; + } - /// True if is greater than or equal to . - public static bool operator >=(TimeSpan timeSpan, Duration duration) - { - return timeSpan.TotalSeconds >= duration.Seconds; - } + /// True if is greater than . + public static bool operator >(TimeSpan timeSpan, Duration duration) + { + return timeSpan.Ticks > duration.Seconds * TimeSpan.TicksPerSecond; + } + + /// True if is less than or equal to . + public static bool operator <=(TimeSpan timeSpan, Duration duration) + { + return timeSpan.Ticks <= duration.Seconds * TimeSpan.TicksPerSecond; + } + + /// True if is greater than or equal to . + public static bool operator >=(TimeSpan timeSpan, Duration duration) + { + return timeSpan.Ticks >= duration.Seconds * TimeSpan.TicksPerSecond; } } diff --git a/UnitsNet/CustomCode/Quantities/EnergyDensity.extra.cs b/UnitsNet/CustomCode/Quantities/EnergyDensity.extra.cs index 811267d7f9..50a0ad1f5e 100644 --- a/UnitsNet/CustomCode/Quantities/EnergyDensity.extra.cs +++ b/UnitsNet/CustomCode/Quantities/EnergyDensity.extra.cs @@ -17,7 +17,7 @@ public partial struct EnergyDensity /// /// /// - /// The that specifies the ratio of a natural gas volume in the standard condition to the natural gas volume in the operating condition. + /// The that specifies the ratio of a natural gas volume in the standard condition to the natural gas volume in the operating condition. /// /// This value is normally shown on the invoice, otherwise it is to be requested from the supplier. For a rough approximation, a value of 100% for natural gas can be assumed. /// @@ -28,9 +28,9 @@ public partial struct EnergyDensity /// /// An that specifies the combustion energy of natural gas as consumed by the heating system. /// - public static Energy CombustionEnergy ( EnergyDensity energyDensity, Volume volume, Ratio conversionFactor ) + public static Energy CombustionEnergy(EnergyDensity energyDensity, Volume volume, Ratio conversionFactor) { - return Energy.FromJoules ( (energyDensity * volume).As ( EnergyUnit.Joule ) * conversionFactor.DecimalFractions ); + return Energy.FromJoules((energyDensity * volume).As(EnergyUnit.Joule) * conversionFactor.DecimalFractions); } } } diff --git a/UnitsNet/CustomCode/Quantities/Force.extra.cs b/UnitsNet/CustomCode/Quantities/Force.extra.cs index d729d18b18..1683ce5dc2 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; + QuantityValue 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 138d9e9f7f..147536cbf3 100644 --- a/UnitsNet/CustomCode/Quantities/Length.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Length.extra.cs @@ -3,6 +3,7 @@ using System; using System.Globalization; +using System.Numerics; using System.Text.RegularExpressions; using System.Threading; using UnitsNet.Units; @@ -11,7 +12,7 @@ namespace UnitsNet { public partial struct Length { - private const double InchesInOneFoot = 12; + private static readonly QuantityValue InchesInOneFoot = 12; /// /// Converts the length to a customary feet/inches combination. @@ -20,18 +21,15 @@ public FeetInches FeetInches { get { - var inInches = Inches; - var feet = Math.Truncate(inInches / InchesInOneFoot); - var inches = inInches % InchesInOneFoot; - - return new FeetInches(feet, inches); + QuantityValue totalInches = Inches; + return new FeetInches((BigInteger) (totalInches / InchesInOneFoot), totalInches % InchesInOneFoot); } } /// /// Get length from combination of feet and inches. /// - public static Length FromFeetInches(double feet, double inches) + public static Length FromFeetInches(QuantityValue feet, QuantityValue inches) { return FromInches(InchesInOneFoot*feet + inches); } @@ -82,7 +80,7 @@ public static bool TryParseFeetInches(string? str, out Length result, IFormatPro if (TryParse(str, formatProvider, out result)) return true; - var quantityParser = UnitsNetSetup.Default.QuantityParser; + QuantityParser quantityParser = QuantityParser.Default; string footRegex = quantityParser.CreateRegexPatternForUnit(LengthUnit.Foot, formatProvider, matchEntireString: false); string inchRegex = quantityParser.CreateRegexPatternForUnit(LengthUnit.Inch, formatProvider, matchEntireString: false); @@ -122,7 +120,7 @@ public sealed class FeetInches /// /// Construct from feet and inches. /// - public FeetInches(double feet, double inches) + public FeetInches(BigInteger feet, QuantityValue inches) { Feet = feet; Inches = inches; @@ -131,12 +129,12 @@ public FeetInches(double feet, double inches) /// /// The feet value it was constructed with. /// - public double Feet { get; } + public BigInteger Feet { get; } /// /// The inches value it was constructed with. /// - public double Inches { get; } + public QuantityValue Inches { get; } /// public override string ToString() @@ -154,14 +152,17 @@ public override string ToString() /// public string ToString(IFormatProvider? cultureInfo) { - cultureInfo = cultureInfo ?? CultureInfo.CurrentCulture; + if (cultureInfo is not CultureInfo unitLocalizationCulture) + { + cultureInfo = unitLocalizationCulture = CultureInfo.CurrentCulture; + } - var footUnit = Length.GetAbbreviation(LengthUnit.Foot, cultureInfo); - var inchUnit = Length.GetAbbreviation(LengthUnit.Inch, cultureInfo); + var footUnit = Length.GetAbbreviation(LengthUnit.Foot, unitLocalizationCulture); + var inchUnit = Length.GetAbbreviation(LengthUnit.Inch, unitLocalizationCulture); // Note that it isn't customary to use fractions - one wouldn't say "I am 5 feet and 4.5 inches". // So inches are rounded when converting from base units to feet/inches. - return string.Format(cultureInfo, "{0:n0} {1} {2:n0} {3}", Feet, footUnit, Math.Round(Inches), inchUnit); + return string.Format(cultureInfo, "{0:n0} {1} {2:n0} {3}", Feet, footUnit, Math.Round(Inches.ToDouble()), inchUnit); } /// @@ -189,9 +190,10 @@ public string ToArchitecturalString(int fractionDenominator) { throw new ArgumentOutOfRangeException(nameof(fractionDenominator), "Denominator for fractional inch must be greater than zero."); } - - var inchTrunc = (int)Math.Truncate(Inches); - var numerator = (int)Math.Round((Inches - inchTrunc) * fractionDenominator); + + // TODO this could probably be done better with the fractions + var inchTrunc = (int)Math.Truncate(Inches.ToDouble()); + var numerator = (int)Math.Round((Inches - inchTrunc).ToDouble() * fractionDenominator); if (numerator == fractionDenominator) { @@ -208,7 +210,7 @@ public string ToArchitecturalString(int fractionDenominator) if (numerator > 0) { - int GreatestCommonDivisor(int a, int b) + static int GreatestCommonDivisor(int a, int b) { while (a != 0 && b != 0) { diff --git a/UnitsNet/CustomCode/Quantities/Level.extra.cs b/UnitsNet/CustomCode/Quantities/Level.extra.cs index a7b1a82825..5ac9b518f4 100644 --- a/UnitsNet/CustomCode/Quantities/Level.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Level.extra.cs @@ -14,20 +14,26 @@ public partial struct Level /// /// The quantity. /// The reference value that is compared to. - public Level(double quantity, double reference) + /// The number of significant digits to use in the calculation. Default is 15. + /// + /// Thrown when the number of significant digits is less than 1 or greater than 17. + /// + public Level(double quantity, double reference, byte significantDigits = 15) : this() { - string errorMessage = - $"The base-10 logarithm of a number ≤ 0 is undefined ({quantity}/{reference})."; + var errorMessage = $"The base-10 logarithm of a number ≤ 0 is undefined ({quantity}/{reference})."; - // ReSharper disable CompareOfFloatsByEqualityOperator - if (quantity == 0 || quantity < 0 && reference > 0) + if (quantity == 0 || (quantity < 0 && reference > 0)) + { throw new ArgumentOutOfRangeException(nameof(quantity), errorMessage); - if (reference == 0 || quantity > 0 && reference < 0) + } + + if (reference == 0 || (quantity > 0 && reference < 0)) + { throw new ArgumentOutOfRangeException(nameof(reference), errorMessage); - // ReSharper restore CompareOfFloatsByEqualityOperator + } - _value = 10*Math.Log10(quantity/reference); + _value = QuantityValue.FromDoubleRounded(10 * Math.Log10(quantity / reference), significantDigits); _unit = LevelUnit.Decibel; } } diff --git a/UnitsNet/CustomCode/Quantities/Mass.extra.cs b/UnitsNet/CustomCode/Quantities/Mass.extra.cs index 906feca314..cf4e4e9cd4 100644 --- a/UnitsNet/CustomCode/Quantities/Mass.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Mass.extra.cs @@ -4,7 +4,11 @@ using System; using System.Threading; using System.Globalization; +using System.Numerics; using UnitsNet.Units; +#if NET +using System.Text.Json.Serialization; +#endif namespace UnitsNet { @@ -20,19 +24,22 @@ public static Mass FromGravitationalForce(Force f) /// StonePounds related code makes it easier to work with Stone/Pound combination, which are customarily used in the UK /// to express body weight. For example, someone weighs 11 stone 4 pounds (about 72 kilograms). /// - private const double StonesInOnePound = 14.0; + private static readonly QuantityValue StonesInOnePound = 14; /// /// Converts the mass to a customary stone/pounds combination. /// +#if NET + [JsonIgnore] +#endif public StonePounds StonePounds { get { - var inPounds = Pounds; + QuantityValue inPounds = Pounds; - var stones = Math.Truncate(inPounds / StonesInOnePound); - var pounds = inPounds % StonesInOnePound; + var stones = (BigInteger)(inPounds / StonesInOnePound); // BigInteger division returns the quotient (equivalent to Math.Truncate) + QuantityValue pounds = inPounds % StonesInOnePound; return new StonePounds(stones, pounds); } @@ -41,7 +48,7 @@ public StonePounds StonePounds /// /// Get Mass from combination of stone and pounds. /// - public static Mass FromStonePounds(double stone, double pounds) + public static Mass FromStonePounds(QuantityValue stone, QuantityValue pounds) { return FromPounds(StonesInOnePound*stone + pounds); } @@ -56,7 +63,7 @@ public sealed class StonePounds /// /// Construct from stone and pounds. /// - public StonePounds(double stone, double pounds) + public StonePounds(QuantityValue stone, QuantityValue pounds) { Stone = stone; Pounds = pounds; @@ -65,12 +72,12 @@ public StonePounds(double stone, double pounds) /// /// The stone value it was created with. /// - public double Stone { get; } + public QuantityValue Stone { get; } /// /// The pounds value it was created with. /// - public double Pounds { get; } + public QuantityValue Pounds { get; } /// public override string ToString() @@ -88,14 +95,17 @@ public override string ToString() /// public string ToString(IFormatProvider? cultureInfo) { - cultureInfo = cultureInfo ?? CultureInfo.CurrentCulture; + if (cultureInfo is not CultureInfo unitLocalizationCulture) + { + cultureInfo = unitLocalizationCulture = CultureInfo.CurrentCulture; + } - var stoneUnit = Mass.GetAbbreviation(MassUnit.Stone, cultureInfo); - var poundUnit = Mass.GetAbbreviation(MassUnit.Pound, cultureInfo); + var stoneUnit = Mass.GetAbbreviation(MassUnit.Stone, unitLocalizationCulture); + var poundUnit = Mass.GetAbbreviation(MassUnit.Pound, unitLocalizationCulture); // Note that it isn't customary to use fractions - one wouldn't say "I am 11 stone and 4.5 pounds". // So pounds are rounded here. - return string.Format(cultureInfo, "{0:n0} {1} {2:n0} {3}", Stone, stoneUnit, Math.Round(Pounds), poundUnit); + return string.Format(cultureInfo, "{0:n0} {1} {2:n0} {3}", Stone, stoneUnit, Math.Round(Pounds.ToDouble()), poundUnit); } } } diff --git a/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs b/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs index e4c4f07fe6..1f53f56c12 100644 --- a/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs +++ b/UnitsNet/CustomCode/Quantities/PowerRatio.extra.cs @@ -12,16 +12,21 @@ public partial struct PowerRatio /// Initializes a new instance of the struct from the specified power referenced to one watt. /// /// The power relative to one watt. - - public PowerRatio(Power power) + /// The number of significant digits to use in the calculation. Default is 15. + /// + /// Thrown when the number of significant digits is less than 1 or greater than 17. + /// + public PowerRatio(Power power, byte significantDigits = 15) : this() { - if (power.Watts <= 0) + if (!QuantityValue.IsPositive(power.Value)) + { throw new ArgumentOutOfRangeException( 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((double)power.Watts); + _value = power.Watts.ToLogSpace(LogarithmicScalingFactor, significantDigits); _unit = PowerRatioUnit.DecibelWatt; } @@ -34,20 +39,24 @@ public PowerRatio(Power power) /// var power = powerRatio.ToPower(); /// /// - public Power ToPower() + public Power ToPower(byte significantDigits = 15) { // P(W) = 1W * 10^(P(dBW)/10) - return Power.FromWatts(Math.Pow(10, DecibelWatts / 10)); + return Power.FromWatts(DecibelWatts.ToLinearSpace(LogarithmicScalingFactor, significantDigits)); } /// /// Gets a from this . /// /// The input impedance of the load. This is usually 50, 75 or 600 ohms. - public AmplitudeRatio ToAmplitudeRatio(ElectricResistance impedance) + /// The number of significant digits to use in the calculation. Default is 15. + /// + /// Thrown when the number of significant digits is less than 1 or greater than 17. + /// + public AmplitudeRatio ToAmplitudeRatio(ElectricResistance impedance, byte significantDigits = 15) { // E(dBV) = 10*log10(Z(Ω)/1) + P(dBW) - return AmplitudeRatio.FromDecibelVolts(10 * Math.Log10(impedance.Ohms / 1) + DecibelWatts); + return AmplitudeRatio.FromDecibelVolts(impedance.Ohms.ToLogSpace(LogarithmicScalingFactor, significantDigits) + DecibelWatts); } #region Static Methods @@ -56,9 +65,13 @@ public AmplitudeRatio ToAmplitudeRatio(ElectricResistance impedance) /// Gets a from a relative to one watt. /// /// The power relative to one watt. - public static PowerRatio FromPower(Power power) + /// The number of significant digits to use in the calculation. Default is 15. + /// + /// Thrown when the number of significant digits is less than 1 or greater than 17. + /// + public static PowerRatio FromPower(Power power, byte significantDigits = 15) { - return new PowerRatio(power); + return new PowerRatio(power, significantDigits); } #endregion diff --git a/UnitsNet/CustomCode/Quantities/Pressure.extra.cs b/UnitsNet/CustomCode/Quantities/Pressure.extra.cs index 00bf97d060..d3d99cb5ab 100644 --- a/UnitsNet/CustomCode/Quantities/Pressure.extra.cs +++ b/UnitsNet/CustomCode/Quantities/Pressure.extra.cs @@ -1,5 +1,4 @@ -using System; -using UnitsNet.Units; +using UnitsNet.Units; namespace UnitsNet; @@ -9,28 +8,38 @@ public partial struct Pressure /// Calculates the pressure at a given elevation. /// /// The elevation for which to calculate the pressure. + /// The number of significant digits to use in the calculation. Default is 13. + /// + /// Thrown when the number of significant digits is less than 1 or greater than 17. + /// /// A Pressure struct representing the pressure at the given elevation. /// /// The calculation is based on the formula for pressure altitude from Wikipedia: /// https://en.wikipedia.org/wiki/Pressure_altitude /// - public static Pressure FromElevation(Length elevation) + public static Pressure FromElevation(Length elevation, byte significantDigits = 13) { // Millibars = 1013.25 * (1 - (Length (Feet) / 145366.45)) ^ (1 / 0.190284) - return new Pressure(1013.25 * Math.Pow(1 - elevation.Feet / 145366.45, 1 / 0.190284), PressureUnit.Millibar); + return new Pressure(QuantityValue.FromDoubleRounded(1013.25 * Math.Pow(1 - elevation.Feet.ToDouble() / 145366.45, 1 / 0.190284), significantDigits), + PressureUnit.Millibar); } /// /// Converts the pressure to an equivalent elevation or altitude. /// + /// The number of significant digits to round the result to. Default is 15. + /// + /// Thrown when the number of significant digits is less than 1 or greater than 17. + /// /// A object representing the equivalent elevation or altitude. /// /// The conversion is based on the formula for pressure altitude as described on Wikipedia /// (https://en.wikipedia.org/wiki/Pressure_altitude). /// - public Length ToElevation() + public Length ToElevation(byte significantDigits = 15) { // Length (Feet) = 145366.45 * (1 - (Millibars / 1013.25) ^ 0.190284) - return new Length(145366.45 * (1 - Math.Pow(Millibars / 1013.25, 0.190284)), LengthUnit.Foot); + return new Length(QuantityValue.FromDoubleRounded(145366.45 * (1 - Math.Pow(Millibars.ToDouble() / 1013.25, 0.190284)), significantDigits), + LengthUnit.Foot); } } diff --git a/UnitsNet/CustomCode/Quantity.cs b/UnitsNet/CustomCode/Quantity.cs index c2be09ea11..02084047fa 100644 --- a/UnitsNet/CustomCode/Quantity.cs +++ b/UnitsNet/CustomCode/Quantity.cs @@ -35,7 +35,7 @@ public static bool TryGetUnitInfo(UnitKey unitEnum, [NotNullWhen(true)] out Unit { return Quantities.TryGetUnitInfo(unitEnum, out unitInfo); } - + /// /// Dynamically constructs a quantity from a numeric value and a unit enum value. /// @@ -43,7 +43,7 @@ public static bool TryGetUnitInfo(UnitKey unitEnum, [NotNullWhen(true)] out Unit /// Unit enum value. /// An object. /// Unit value is not a known unit enum type. - public static IQuantity From(double value, UnitKey unit) + public static IQuantity From(QuantityValue value, UnitKey unit) { return Quantities.From(value, unit); } @@ -61,7 +61,7 @@ public static IQuantity From(double value, UnitKey unit) /// /// Thrown when no unit is found for the specified quantity name and unit name. /// - public static IQuantity From(double value, string quantityName, string unitName) + public static IQuantity From(QuantityValue value, string quantityName, string unitName) { return Quantities.GetUnitByName(quantityName, unitName).From(value); } @@ -74,14 +74,14 @@ public static IQuantity From(double value, string quantityName, string unitName) /// Unit abbreviation matching is case-insensitive.
///
/// This will fail if more than one unit across all quantities share the same unit abbreviation.
- /// Prefer or instead. + /// Prefer or instead. /// /// Numeric value. /// Unit abbreviation, such as "kg" for . /// An object. /// Unit abbreviation is not known. /// Multiple units found matching the given unit abbreviation. - public static IQuantity FromUnitAbbreviation(double value, string unitAbbreviation) => FromUnitAbbreviation(null, value, unitAbbreviation); + public static IQuantity FromUnitAbbreviation(QuantityValue value, string unitAbbreviation) => FromUnitAbbreviation(null, value, unitAbbreviation); /// /// Dynamically construct a quantity from a numeric value and a unit abbreviation. @@ -91,17 +91,17 @@ public static IQuantity From(double value, string quantityName, string unitName) /// Unit abbreviation matching is case-insensitive.
///
/// This will fail if more than one unit across all quantities share the same unit abbreviation.
- /// Prefer or instead. + /// Prefer or instead. /// - /// The format provider to use for lookup. Defaults to if null. + /// The localization culture. Defaults to if null. /// Numeric value. /// Unit abbreviation, such as "kg" for . /// An object. /// Unit abbreviation is not known. /// Multiple units found matching the given unit abbreviation. - public static IQuantity FromUnitAbbreviation(IFormatProvider? formatProvider, double value, string unitAbbreviation) + public static IQuantity FromUnitAbbreviation(IFormatProvider? culture, QuantityValue value, string unitAbbreviation) { - return UnitParser.FromUnitAbbreviation(value, unitAbbreviation, formatProvider); + return UnitParser.FromUnitAbbreviation(value, unitAbbreviation, culture); } /// @@ -112,7 +112,7 @@ public static IQuantity FromUnitAbbreviation(IFormatProvider? formatProvider, do /// The invariant quantity name, such as "Length". Does not support localization. /// The constructed quantity, if successful, otherwise null. /// True if successful with assigned the value, otherwise false. - public static bool TryFrom(double value, string quantityName, string unitName, [NotNullWhen(true)] out IQuantity? quantity) + public static bool TryFrom(QuantityValue value, string quantityName, string unitName, [NotNullWhen(true)] out IQuantity? quantity) { if (!Quantities.TryGetUnitByName(quantityName, unitName, out UnitInfo? unitInfo)) { @@ -136,7 +136,7 @@ public static bool TryFrom(double value, string quantityName, string unitName, [ /// /// true if the quantity was successfully created; otherwise, false. /// - public static bool TryFrom(double value, Enum? unit, [NotNullWhen(true)] out IQuantity? quantity) + public static bool TryFrom(QuantityValue value, Enum? unit, [NotNullWhen(true)] out IQuantity? quantity) { return Quantities.TryFrom(value, unit, out quantity); } @@ -149,14 +149,14 @@ public static bool TryFrom(double value, Enum? unit, [NotNullWhen(true)] out IQu /// Unit abbreviation matching is case-insensitive.
///
/// This will fail if more than one unit across all quantities share the same unit abbreviation.
- /// Prefer or instead. + /// Prefer or instead. /// /// Numeric value. /// Unit abbreviation, such as "kg" for . /// The quantity if successful, otherwise null. /// True if successful. /// Unit value is not a known unit enum type. - public static bool TryFromUnitAbbreviation(double value, string unitAbbreviation, [NotNullWhen(true)] out IQuantity? quantity) => + public static bool TryFromUnitAbbreviation(QuantityValue value, string unitAbbreviation, [NotNullWhen(true)] out IQuantity? quantity) => TryFromUnitAbbreviation(null, value, unitAbbreviation, out quantity); /// @@ -167,7 +167,7 @@ public static bool TryFromUnitAbbreviation(double value, string unitAbbreviation /// Unit abbreviation matching is case-insensitive.
///
/// This will fail if more than one unit across all quantities share the same unit abbreviation.
- /// Prefer or instead. + /// Prefer or instead. /// /// The format provider to use for lookup. Defaults to if null. /// Numeric value. @@ -175,7 +175,7 @@ public static bool TryFromUnitAbbreviation(double value, string unitAbbreviation /// The quantity if successful, otherwise null. /// True if successful. /// Unit value is not a known unit enum type. - public static bool TryFromUnitAbbreviation(IFormatProvider? formatProvider, double value, string unitAbbreviation, [NotNullWhen(true)] out IQuantity? quantity) + public static bool TryFromUnitAbbreviation(IFormatProvider? formatProvider, QuantityValue value, string unitAbbreviation, [NotNullWhen(true)] out IQuantity? quantity) { if (UnitParser.TryGetUnitFromAbbreviation(unitAbbreviation, formatProvider, out UnitInfo? unitInfo)) { diff --git a/UnitsNet/CustomCode/QuantityConverters/Builder/ConversionCacheOptions.cs b/UnitsNet/CustomCode/QuantityConverters/Builder/ConversionCacheOptions.cs new file mode 100644 index 0000000000..1078bc7166 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityConverters/Builder/ConversionCacheOptions.cs @@ -0,0 +1,41 @@ +// 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. + +namespace UnitsNet; + +/// +/// Provides options for configuring the caching behavior of unit conversions in the . +/// +public sealed record ConversionCacheOptions +{ + /// + /// Initializes a new instance of the class. + /// + /// + /// The caching mode to be used for unit conversions. Default is + /// . + /// + /// Indicates whether to reduce constants during conversions. Default is true. + public ConversionCacheOptions(ConversionCachingMode cachingMode = ConversionCachingMode.All, bool reduceConstants = true) + { + CachingMode = cachingMode; + ReduceConstants = reduceConstants; + } + + /// + /// Gets the caching mode for unit conversions with this quantity. + /// + /// + /// The caching mode determines how unit conversions are cached. + /// + public ConversionCachingMode CachingMode { get; } + + /// + /// Gets a value indicating whether constant values should be reduced when initializing the unit conversions. + /// + /// + /// When set to true, constant values in unit conversions are reduced to their simplest form. + /// This can help improve performance and reduce memory usage. + /// + public bool ReduceConstants { get; } +} diff --git a/UnitsNet/CustomCode/QuantityConverters/Builder/ConversionCachingMode.cs b/UnitsNet/CustomCode/QuantityConverters/Builder/ConversionCachingMode.cs new file mode 100644 index 0000000000..d01e6564cf --- /dev/null +++ b/UnitsNet/CustomCode/QuantityConverters/Builder/ConversionCachingMode.cs @@ -0,0 +1,34 @@ +// 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. + +namespace UnitsNet; + +/// +/// Specifies the caching modes available for unit conversions in the . +/// +/// +/// No caching is applied. +/// +/// +/// Only base unit conversions are cached. +/// +/// +/// All unit conversions are cached. +/// +public enum ConversionCachingMode +{ + /// + /// No caching is applied. + /// + None, + + /// + /// Only base unit conversions are cached. + /// + BaseOnly, + + /// + /// All unit conversions are cached. + /// + All +} diff --git a/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConversions/QuantityConversion.cs b/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConversions/QuantityConversion.cs new file mode 100644 index 0000000000..58355de3f5 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConversions/QuantityConversion.cs @@ -0,0 +1,56 @@ +// 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.Diagnostics; + +namespace UnitsNet; + +/// +/// Represents an implicit conversion between two quantity types. +/// +/// +/// This record is used to define implicit conversions between different quantity types in the UnitsNet library. +/// The conversion is considered commutative, meaning that a conversion from type A to type B is equivalent to a +/// conversion from type B to type A. +/// +[DebuggerDisplay("{LeftQuantity.Name,nq} <-> {RightQuantity.Name,nq}")] +internal readonly record struct QuantityConversion +{ + /// + /// Initializes a new instance of the struct. + /// + /// The quantity information for first quantity in the conversion. + /// The quantity information for the second quantity of the conversion. + /// + /// This constructor sets up the implicit conversion between two quantity types, + /// ensuring that the conversion is commutative. + /// + public QuantityConversion(QuantityInfo leftQuantity, QuantityInfo rightQuantity) + { + LeftQuantity = leftQuantity; + RightQuantity = rightQuantity; + } + + public QuantityInfo LeftQuantity { get; } + public QuantityInfo RightQuantity { get; } + + public bool Equals(QuantityConversion other) + { + return (LeftQuantity.Equals(other.LeftQuantity) && RightQuantity.Equals(other.RightQuantity)) || + (LeftQuantity.Equals(other.RightQuantity) && RightQuantity.Equals(other.LeftQuantity)); + } + + public override int GetHashCode() + { + var hash1 = LeftQuantity.GetHashCode(); + var hash2 = RightQuantity.GetHashCode(); + // Use a commutative hash code combination to ensure (X1, X2) and (X2, X1) produce the same hash code + return hash1 ^ hash2; + } + + public void Deconstruct(out QuantityInfo leftQuantity, out QuantityInfo rightQuantity) + { + leftQuantity = LeftQuantity; + rightQuantity = RightQuantity; + } +} diff --git a/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConversions/QuantityConversionMapping.cs b/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConversions/QuantityConversionMapping.cs new file mode 100644 index 0000000000..83df668a76 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConversions/QuantityConversionMapping.cs @@ -0,0 +1,66 @@ +// 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 System.Diagnostics; + +namespace UnitsNet; + +/// +/// Represents an implicit conversion between two quantity types, represented by their unique +/// . +/// +/// +/// This record is used to define implicit conversions between different quantity types in the UnitsNet library. +/// The conversion is considered commutative, meaning that a conversion from type A to type B is equivalent to a +/// conversion from type B to type A. +/// +[DebuggerDisplay("{FirstQuantityType.Name,nq} <-> {SecondQuantityType.Name,nq}")] +internal readonly record struct QuantityConversionMapping +{ + /// + /// Initializes a new instance of the struct, representing an implicit + /// conversion + /// between two quantity types. + /// + /// The type of the first quantity involved in the conversion. + /// The type of the second quantity involved in the conversion. + internal QuantityConversionMapping(Type firstQuantityType, Type secondQuantityType) + { + FirstQuantityType = firstQuantityType; + SecondQuantityType = secondQuantityType; + } + + public Type FirstQuantityType { get; } + public Type SecondQuantityType { get; } + + /// + /// Creates an implicit conversion between two quantity types. + /// + /// The type of the first quantity. + /// The type of the second quantity. + /// + /// An instance representing the conversion between the specified quantity + /// types. + /// + public static QuantityConversionMapping Create() + where TFirstQuantity : IQuantity + where TSecondQuantity : IQuantity + { + return new QuantityConversionMapping(typeof(TFirstQuantity), typeof(TSecondQuantity)); + } + + public bool Equals(QuantityConversionMapping other) + { + return (FirstQuantityType == other.FirstQuantityType && SecondQuantityType == other.SecondQuantityType) || + (FirstQuantityType == other.SecondQuantityType && SecondQuantityType == other.FirstQuantityType); + } + + public override int GetHashCode() + { + var hash1 = FirstQuantityType.GetHashCode(); + var hash2 = SecondQuantityType.GetHashCode(); + // Use a commutative hash code combination to ensure (X1, X2) and (X2, X1) produce the same hash code + return hash1 ^ hash2; + } +} diff --git a/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConversions/QuantityConversionOptions.cs b/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConversions/QuantityConversionOptions.cs new file mode 100644 index 0000000000..e2d66e1b53 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConversions/QuantityConversionOptions.cs @@ -0,0 +1,215 @@ +// 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 System.Collections.Generic; + +namespace UnitsNet; + +internal record CustomQuantityConversionUnitMapping +{ + public CustomQuantityConversionUnitMapping(UnitInfo sourceUnit, UnitInfo targetUnit) + { + SourceUnit = sourceUnit; + TargetUnit = targetUnit; + } + + public UnitInfo SourceUnit { get; } + public UnitInfo TargetUnit { get; } +} + +internal record CustomQuantityConversionExpressionMapping +{ + public CustomQuantityConversionExpressionMapping(UnitInfo sourceUnit, UnitInfo targetUnit, ConversionExpression conversionExpression) + { + TargetUnit = targetUnit; + ConversionExpression = conversionExpression; + SourceUnit = sourceUnit; + } + + public UnitInfo SourceUnit { get; } + public UnitInfo TargetUnit { get; } + public ConversionExpression ConversionExpression { get; } +} + +internal sealed class QuantityConversionMappingOptions +{ + internal Dictionary CustomUnitMappings { get; } = []; + internal Dictionary ConversionExpressions { get; } = []; +} + +/// +/// Represents options for configuring implicit conversions between different quantities and units. +/// This class allows the specification of custom conversions and conversion units to be used during implicit +/// conversions. +/// +public sealed class QuantityConversionOptions +{ + internal HashSet CustomConversions { get; } = []; + + internal HashSet ConversionUnits { get; } = []; + + internal Dictionary CustomConversionFunctions { get; } = new(); + + /// + /// Adds a custom conversion between two quantities to the implicit conversion options. + /// + /// The type of the quantity to convert from. + /// The type of the quantity to convert to. + /// + /// The current instance of with the specified custom conversion configured. + /// + /// + /// Thrown when attempting to map conversion units for different quantities using the same quantity type. + /// + /// + /// The association is created in both directions. + /// + public QuantityConversionOptions SetCustomConversion() + where TFromQuantity : IQuantity + where TToQuantity : IQuantity + { + if (typeof(TFromQuantity) == typeof(TToQuantity)) + { + throw new InvalidConversionException( + $"Mapping conversion units for different quantities using the same quantity type ({typeof(TFromQuantity).Name}) is not allowed."); + } + + CustomConversions.Add(QuantityConversionMapping.Create()); + return this; + } + + /// + /// Configures the implicit conversion options by specifying the units to be used for conversion. + /// + /// The type of the unit to convert from, which must be a struct and an enumeration. + /// The type of the unit to convert to, which must be a struct and an enumeration. + /// The unit to convert from. + /// The unit to convert to. + /// + /// A boolean value indicating whether the conversion should be bidirectional. If true, the conversion + /// will be configured in both directions. + /// + /// + /// The current instance of with the specified conversion units + /// configured. + /// + /// + /// Thrown when attempting to map conversion units for different quantities using the same unit type. + /// + public QuantityConversionOptions SetConversionUnits(TFromUnit fromUnit, TToUnit toUnit, bool mapBothDirections = false) + where TFromUnit : struct, Enum + where TToUnit : struct, Enum + { + if (typeof(TFromUnit) == typeof(TToUnit)) + { + throw new InvalidConversionException( + $"Mapping conversion units for different quantities using the same unit type ({typeof(TFromUnit).Name}) is not allowed."); + } + + var fromUnitConversionKey = UnitConversionMapping.Create(fromUnit, toUnit); + ConversionUnits.Add(fromUnitConversionKey); + if (mapBothDirections) + { + ConversionUnits.Add(new UnitConversionMapping(fromUnitConversionKey.ToUnitKey, fromUnitConversionKey.FromUnitKey)); + } + + return this; + } + + /// + /// Adds a custom conversion function between two specified units. + /// + /// The type of the source unit, which must be a struct and an enumeration. + /// The type of the target unit, which must be a struct and an enumeration. + /// The source unit to convert from. + /// The target unit to convert to. + /// The function that performs the conversion from the source unit to the target unit. + /// The current instance with the custom conversion added. + /// + /// Thrown when attempting to map conversion units for different quantities using the same unit type. + /// + /// + /// This method allows you to define a custom conversion function between two units, enabling precise control over the + /// conversion process. + /// + public QuantityConversionOptions SetCustomConversion(TFromUnit fromUnit, TToUnit toUnit, ConvertValueDelegate conversionFunction) + where TFromUnit : struct, Enum + where TToUnit : struct, Enum + { + return SetCustomConversion(fromUnit, toUnit, new ConversionExpression(QuantityValue.One, conversionFunction)); + } + + /// + /// Adds a custom conversion function between two specified units. + /// + /// The type of the source unit, which must be a struct and an enumeration. + /// The type of the target unit, which must be a struct and an enumeration. + /// The source unit to convert from. + /// The target unit to convert to. + /// The function that performs the conversion from the source unit to the target unit. + /// The current instance with the custom conversion added. + /// + /// Thrown when attempting to map conversion units for different quantities using the same unit type. + /// + /// + /// This method allows you to define a custom conversion function between two units, enabling precise control over the + /// conversion process. + /// + public QuantityConversionOptions SetCustomConversion(TFromUnit fromUnit, TToUnit toUnit, ConversionExpression conversionFunction) + where TFromUnit : struct, Enum + where TToUnit : struct, Enum + { + if (typeof(TFromUnit) == typeof(TToUnit)) + { + throw new InvalidConversionException( + $"Mapping conversion units for different quantities using the same unit type ({typeof(TFromUnit).Name}) is not allowed."); + } + + var fromUnitKey = UnitKey.ForUnit(fromUnit); + var toUnitKey = UnitKey.ForUnit(toUnit); + CustomConversionFunctions[new UnitConversionMapping(fromUnitKey, toUnitKey)] = conversionFunction; + return this; + } + + /// + /// Adds a custom conversion function between two specified units. + /// + /// The type of the source unit, which must be a struct and an enumeration. + /// The type of the target unit, which must be a struct and an enumeration. + /// The source unit to convert from. + /// The target unit to convert to. + /// The used to performs the conversion from the source unit to the target unit. + /// + /// A boolean value indicating whether the conversion should be bidirectional. If true, the conversion + /// will be configured in both directions, by creating an expression with the reciprocal coefficient. + /// + /// The current instance with the custom conversion added. + /// + /// Thrown when attempting to map conversion units for different quantities using the same unit type. + /// + /// + /// This method allows you to define a custom conversion function between two units, enabling precise control over the + /// conversion process. + /// + public QuantityConversionOptions SetCustomConversion(TFromUnit fromUnit, TToUnit toUnit, QuantityValue conversionCoefficient, bool mapBothDirections = false) + where TFromUnit : struct, Enum + where TToUnit : struct, Enum + { + if (typeof(TFromUnit) == typeof(TToUnit)) + { + throw new InvalidConversionException( + $"Mapping conversion units for different quantities using the same unit type ({typeof(TFromUnit).Name}) is not allowed."); + } + + var fromUnitKey = UnitKey.ForUnit(fromUnit); + var toUnitKey = UnitKey.ForUnit(toUnit); + CustomConversionFunctions[new UnitConversionMapping(fromUnitKey, toUnitKey)] = conversionCoefficient; + if (mapBothDirections) + { + CustomConversionFunctions[new UnitConversionMapping(toUnitKey, fromUnitKey)] = QuantityValue.Inverse(conversionCoefficient); + } + + return this; + } +} diff --git a/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConversions/QuantityConversionsBuilderExtensions.cs b/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConversions/QuantityConversionsBuilderExtensions.cs new file mode 100644 index 0000000000..1c131d8b94 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConversions/QuantityConversionsBuilderExtensions.cs @@ -0,0 +1,779 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Linq; + +using ConversionEntry = System.Collections.Generic.KeyValuePair; + +namespace UnitsNet; + +/// +/// Provides extension methods for building implicit conversions for quantities. +/// +internal static class QuantityConversionsBuilderExtensions +{ + /// + /// Retrieves a collection of quantity conversions based on the provided conversion mappings. + /// + /// The lookup containing quantity information. + /// The mappings defining the conversions between quantity types. + /// + /// An enumerable collection of representing the implicit conversions between + /// quantities. + /// + public static IEnumerable GetQuantityConversions(this QuantityInfoLookup quantities, + IEnumerable conversionMappings) + { + foreach (QuantityConversionMapping conversionMapping in conversionMappings) + { + if (quantities.TryGetQuantityInfo(conversionMapping.FirstQuantityType, out QuantityInfo? fromQuantity) && + quantities.TryGetQuantityInfo(conversionMapping.SecondQuantityType, out QuantityInfo? toQuantity)) + { + yield return new QuantityConversion(fromQuantity, toQuantity); + } + } + } + + /// + /// Retrieves a dictionary of custom quantity conversion mapping options based on the specified custom conversion + /// options. + /// + /// The lookup containing information about available quantities and their units. + /// The custom conversion options that define specific conversion functions and units. + /// + /// A dictionary where each key is a representing a conversion between two + /// quantities, + /// and each value is a containing the mapping options for that + /// conversion. + /// + /// + /// This method processes custom conversion functions and units specified in to build + /// a comprehensive set of conversion mappings. It ensures that only valid conversions, where both source and target + /// units + /// are recognized, are included in the resulting dictionary. + /// + internal static Dictionary GetQuantityConversionMappingOptions(this QuantityInfoLookup quantities, + QuantityConversionOptions customOptions) + { + var conversionOptions = new Dictionary(); + + foreach (KeyValuePair customConversion in customOptions.CustomConversionFunctions) + { + UnitConversionMapping unitConversionMapping = customConversion.Key; + if (!quantities.TryGetUnitInfo(unitConversionMapping.FromUnitKey, out UnitInfo? fromUnitInfo) || + !quantities.TryGetUnitInfo(unitConversionMapping.ToUnitKey, out UnitInfo? toUnitInfo)) + { + continue; + } + + var conversionMapping = new QuantityConversion(fromUnitInfo.QuantityInfo, toUnitInfo.QuantityInfo); + if (!conversionOptions.TryGetValue(conversionMapping, out QuantityConversionMappingOptions? conversionMappingOptions)) + { + conversionMappingOptions = conversionOptions[conversionMapping] = new QuantityConversionMappingOptions(); + } + + conversionMappingOptions.ConversionExpressions.Add(unitConversionMapping, + new CustomQuantityConversionExpressionMapping(fromUnitInfo, toUnitInfo, customConversion.Value)); + } + + foreach (UnitConversionMapping unitConversionMapping in customOptions.ConversionUnits) + { + if (!quantities.TryGetUnitInfo(unitConversionMapping.FromUnitKey, out UnitInfo? fromUnitInfo) || + !quantities.TryGetUnitInfo(unitConversionMapping.ToUnitKey, out UnitInfo? toUnitInfo)) + { + continue; + } + + var conversionMapping = new QuantityConversion(fromUnitInfo.QuantityInfo, toUnitInfo.QuantityInfo); + if (!conversionOptions.TryGetValue(conversionMapping, out QuantityConversionMappingOptions? conversionMappingOptions)) + { + conversionMappingOptions = conversionOptions[conversionMapping] = new QuantityConversionMappingOptions(); + conversionMappingOptions.CustomUnitMappings.Add(unitConversionMapping, new CustomQuantityConversionUnitMapping(fromUnitInfo, toUnitInfo)); + } + else if (!conversionMappingOptions.ConversionExpressions.ContainsKey(unitConversionMapping)) + { + conversionMappingOptions.CustomUnitMappings.Add(unitConversionMapping, new CustomQuantityConversionUnitMapping(fromUnitInfo, toUnitInfo)); + } + } + + return conversionOptions; + } + + /// + /// Retrieves conversion expressions for a collection of quantity conversions based on the specified caching mode and + /// constant reduction option. + /// + /// The collection of quantity conversions to process. + /// The caching mode to use for the conversions. + /// Indicates whether to reduce constants in the conversion expressions. + /// + /// An enumerable collection of key-value pairs, where the key is a and the + /// value is a . + /// + /// Thrown when an invalid caching mode is specified. + public static IEnumerable GetConversionFunctions(this IEnumerable conversions, + ConversionCachingMode cachingMode, bool reduceConstants = true) + { + return cachingMode switch + { + ConversionCachingMode.None => [], + ConversionCachingMode.BaseOnly => conversions.SelectMany(conversion => conversion.GetConversionsWithBaseUnits()), + ConversionCachingMode.All => conversions.SelectMany(conversion => conversion.GetConversionsWithAllUnits(reduceConstants)), + _ => throw new ArgumentOutOfRangeException() + }; + } + + /// + /// Retrieves conversion expressions for a given set of quantity conversions, applying custom caching options if + /// provided. + /// + /// The collection of quantity conversions to process. + /// The default caching mode to use if no custom options are specified. + /// Indicates whether to reduce constants by default. + /// A dictionary of custom caching options keyed by quantity type. + /// + /// An enumerable of key-value pairs, where the key is a and the value is a + /// . + /// + public static IEnumerable GetConversionFunctions(this IEnumerable conversions, + ConversionCachingMode defaultCachingMode, bool defaultConstantsReduction, + IReadOnlyDictionary customCachingOptions) + { + return customCachingOptions.Count == 0 + ? conversions.GetConversionFunctions(defaultCachingMode, defaultConstantsReduction) + : conversions.SelectMany(conversion => conversion.GetConversionFunctions(defaultCachingMode, defaultConstantsReduction, customCachingOptions)); + } + + private static IEnumerable GetConversionFunctions(this QuantityConversion conversion, ConversionCachingMode defaultCachingMode, bool defaultConstantsReduction, + IReadOnlyDictionary customCachingOptions) + { + (QuantityInfo leftQuantity, QuantityInfo rightQuantity) = conversion; + if (customCachingOptions.TryGetValue(leftQuantity.QuantityType, out ConversionCacheOptions? leftCacheOptions) && + (leftCacheOptions.CachingMode != defaultCachingMode || leftCacheOptions.ReduceConstants != defaultConstantsReduction)) + { + if (customCachingOptions.TryGetValue(rightQuantity.QuantityType, out ConversionCacheOptions? rightCacheOptions)) + { + return leftCacheOptions == rightCacheOptions + ? conversion.GetQuantityConversions(leftCacheOptions.CachingMode, leftCacheOptions.ReduceConstants) + : leftQuantity.GetConversionsTo(rightQuantity, leftCacheOptions.CachingMode, leftCacheOptions.ReduceConstants) + .Concat(rightQuantity.GetConversionsTo(leftQuantity, rightCacheOptions.CachingMode, rightCacheOptions.ReduceConstants)); + } + + return leftQuantity.GetConversionsTo(rightQuantity, leftCacheOptions.CachingMode, leftCacheOptions.ReduceConstants) + .Concat(rightQuantity.GetConversionsTo(leftQuantity, defaultCachingMode, defaultConstantsReduction)); + } + else if (customCachingOptions.TryGetValue(rightQuantity.QuantityType, out ConversionCacheOptions? rightCacheOptions) && + (rightCacheOptions.CachingMode != defaultCachingMode || rightCacheOptions.ReduceConstants != defaultConstantsReduction)) + { + return leftQuantity.GetConversionsTo(rightQuantity, defaultCachingMode, defaultConstantsReduction) + .Concat(rightQuantity.GetConversionsTo(leftQuantity, rightCacheOptions.CachingMode, rightCacheOptions.ReduceConstants)); + } + else // using the default options + { + return conversion.GetQuantityConversions(defaultCachingMode, defaultConstantsReduction); + } + } + + /// + /// Retrieves conversion expressions for a given set of quantity conversions. + /// + /// The collection of quantity conversions to process. + /// A dictionary containing custom unit conversions. + /// The default caching mode to use if no custom caching options are provided. + /// A flag indicating whether constants reduction should be applied by default. + /// A dictionary containing custom caching options for specific types. + /// + /// An enumerable collection of key-value pairs, where each key is a and each + /// value is a . + /// + public static IEnumerable GetConversionFunctions(this IEnumerable conversions, + IReadOnlyDictionary customUnitConversions, + ConversionCachingMode defaultCachingMode, bool defaultConstantsReduction, + IReadOnlyDictionary customCachingOptions) + { + if (customUnitConversions.Count == 0) + { + return conversions.GetConversionFunctions(defaultCachingMode, defaultConstantsReduction, customCachingOptions); + } + + return conversions.SelectMany(conversion => customUnitConversions.TryGetValue(conversion, out QuantityConversionMappingOptions? conversionMappingOptions) + ? conversion.GetConversionFunctions(conversionMappingOptions, defaultCachingMode, defaultConstantsReduction, customCachingOptions) + : conversion.GetConversionFunctions(defaultCachingMode, defaultConstantsReduction, customCachingOptions)); + } + + private static IEnumerable GetConversionFunctions(this QuantityConversion conversion, QuantityConversionMappingOptions customUnitConversions, + ConversionCachingMode defaultCachingMode, bool defaultConstantsReduction, IReadOnlyDictionary customCachingOptions) + { + (QuantityInfo leftQuantity, QuantityInfo rightQuantity) = conversion; + if (customCachingOptions.TryGetValue(leftQuantity.QuantityType, out ConversionCacheOptions? leftCacheOptions) && + (leftCacheOptions.CachingMode != defaultCachingMode || leftCacheOptions.ReduceConstants != defaultConstantsReduction)) + { + if (customCachingOptions.TryGetValue(rightQuantity.QuantityType, out ConversionCacheOptions? rightCacheOptions)) + { + return leftCacheOptions == rightCacheOptions + ? conversion.GetQuantityConversions(customUnitConversions, leftCacheOptions.CachingMode, leftCacheOptions.ReduceConstants) + : leftQuantity.GetConversionsTo(rightQuantity, customUnitConversions, leftCacheOptions.CachingMode, leftCacheOptions.ReduceConstants) + .Concat(rightQuantity.GetConversionsTo(leftQuantity, customUnitConversions, rightCacheOptions.CachingMode, + rightCacheOptions.ReduceConstants)); + } + + return leftQuantity.GetConversionsTo(rightQuantity, customUnitConversions, leftCacheOptions.CachingMode, leftCacheOptions.ReduceConstants) + .Concat(rightQuantity.GetConversionsTo(leftQuantity, customUnitConversions, defaultCachingMode, defaultConstantsReduction)); + } + else if (customCachingOptions.TryGetValue(rightQuantity.QuantityType, out ConversionCacheOptions? rightCacheOptions) && + (rightCacheOptions.CachingMode != defaultCachingMode || rightCacheOptions.ReduceConstants != defaultConstantsReduction)) + { + return leftQuantity.GetConversionsTo(rightQuantity, customUnitConversions, defaultCachingMode, defaultConstantsReduction) + .Concat(rightQuantity.GetConversionsTo(leftQuantity, customUnitConversions, rightCacheOptions.CachingMode, rightCacheOptions.ReduceConstants)); + } + else // using the default options + { + return conversion.GetQuantityConversions(customUnitConversions, defaultCachingMode, defaultConstantsReduction); + } + } + + private static IEnumerable GetQuantityConversions(this QuantityConversion conversion, ConversionCachingMode cachingMode, bool reduceConstants) + { + return cachingMode switch + { + ConversionCachingMode.None => [], + ConversionCachingMode.BaseOnly => conversion.GetConversionsWithBaseUnits(), + ConversionCachingMode.All => conversion.GetConversionsWithAllUnits(reduceConstants), + _ => throw new ArgumentOutOfRangeException() + }; + } + + private static IEnumerable GetConversionsTo(this QuantityInfo fromQuantity, QuantityInfo toQuantity, ConversionCachingMode cachingMode, bool reduceConstants) + { + return cachingMode switch + { + ConversionCachingMode.None => [], + ConversionCachingMode.BaseOnly => fromQuantity.GetConversionsWithBaseUnits(toQuantity), + ConversionCachingMode.All => fromQuantity.GetConversionsWithAllUnits(toQuantity, reduceConstants), + _ => throw new ArgumentOutOfRangeException() + }; + } + + private static IEnumerable GetQuantityConversions(this QuantityConversion conversion, QuantityConversionMappingOptions customUnitConversions, ConversionCachingMode cachingMode, bool reduceConstants) + { + return conversion.LeftQuantity.GetConversionsTo(conversion.RightQuantity, customUnitConversions, cachingMode, reduceConstants) + .Concat(conversion.RightQuantity.GetConversionsTo(conversion.LeftQuantity, customUnitConversions, cachingMode, reduceConstants)); + } + + private static IEnumerable GetConversionsTo(this QuantityInfo fromQuantity, QuantityInfo toQuantity, QuantityConversionMappingOptions customUnitConversions, + ConversionCachingMode cachingMode, bool reduceConstants) + { + // filter the customUnitConversions for specified conversion direction + Type sourceUnitType = fromQuantity.UnitType; + var unitMappings = customUnitConversions.CustomUnitMappings.Where(x => x.Key.FromUnitKey.UnitEnumType == sourceUnitType) + .ToDictionary(x => x.Key.FromUnitKey, pair => pair.Value); + var conversionExpressions = customUnitConversions.ConversionExpressions.Where(x => x.Key.FromUnitKey.UnitEnumType == sourceUnitType) + .ToDictionary(x => x.Key.FromUnitKey, pair => pair.Value); + // if there are any custom conversionExpressions we ignore the caching mode and calculate an expression for all units + if (conversionExpressions.Count != 0) + { + return fromQuantity.GetConversionsWithAllUnits(toQuantity, unitMappings, conversionExpressions, reduceConstants); + } + + return cachingMode switch + { + ConversionCachingMode.None => fromQuantity.GetConversionsWithCustomUnits(toQuantity, unitMappings, reduceConstants), + ConversionCachingMode.BaseOnly => fromQuantity.GetConversionsWithBaseUnits(toQuantity, unitMappings, reduceConstants), + ConversionCachingMode.All => fromQuantity.GetConversionsWithAllUnits(toQuantity, unitMappings, conversionExpressions, reduceConstants), + _ => throw new ArgumentOutOfRangeException() + }; + } + + private static IEnumerable GetConversionsWithBaseUnits(this QuantityConversion conversion) + { + (QuantityInfo leftQuantity, QuantityInfo rightQuantity) = conversion; + ConvertValueDelegate conversionDelegate = leftQuantity.BaseDimensions.GetConversionDelegate(rightQuantity.BaseDimensions); + return conversion.LeftQuantity.GetConversionsWithBaseUnits(conversion.RightQuantity, conversionDelegate) + .Concat(conversion.RightQuantity.GetConversionsWithBaseUnits(conversion.LeftQuantity, conversionDelegate)); + } + + private static IEnumerable GetConversionsWithBaseUnits(this QuantityInfo fromQuantity, QuantityInfo toQuantity) + { + return fromQuantity.GetConversionsWithBaseUnits(toQuantity, fromQuantity.BaseDimensions.GetConversionDelegate(toQuantity.BaseDimensions)); + } + + private static IEnumerable GetConversionsWithBaseUnits(this QuantityInfo fromQuantity, QuantityInfo toQuantity, ConvertValueDelegate conversionExpression) + { + foreach (UnitInfo fromUnit in fromQuantity.UnitInfos) + { + if (fromUnit.BaseUnits == BaseUnits.Undefined || !toQuantity.UnitInfos.TryGetUnitWithBase(fromUnit.BaseUnits, out UnitInfo? toUnit)) + { + continue; + } + + var conversionKey = new QuantityConversionKey(fromUnit.UnitKey, toQuantity.UnitType); + var conversionResult = new QuantityConversionFunction(conversionExpression, toUnit.UnitKey); + yield return new ConversionEntry(conversionKey, conversionResult); + } + } + + private static IEnumerable GetConversionsWithAllUnits(this QuantityConversion conversion, bool reduceConstants = true) + { + ConversionExpression conversionExpression = conversion.LeftQuantity.BaseDimensions.GetConversionExpression(conversion.RightQuantity.BaseDimensions); + + return conversion.LeftQuantity.GetConversionsWithAllUnits(conversion.RightQuantity, conversionExpression, reduceConstants) + .Concat(conversion.RightQuantity.GetConversionsWithAllUnits(conversion.LeftQuantity, conversionExpression, reduceConstants)); + } + + private static IEnumerable GetConversionsWithAllUnits(this QuantityInfo fromQuantity, QuantityInfo toQuantity, bool reduceConstants = true) + { + return fromQuantity.GetConversionsWithAllUnits(toQuantity, fromQuantity.BaseDimensions.GetConversionExpression(toQuantity.BaseDimensions), reduceConstants); + } + + private static IEnumerable GetConversionsWithAllUnits(this QuantityInfo fromQuantity, QuantityInfo toQuantity, ConversionExpression conversionExpression, + bool reduceConstants = true) + { + foreach (UnitInfo fromUnit in fromQuantity.UnitInfos) + { + if (toQuantity.TryGetConversionFrom(fromUnit, conversionExpression, reduceConstants, out QuantityConversionFunction conversionFunction)) + { + yield return new ConversionEntry(new QuantityConversionKey(fromUnit.UnitKey, conversionFunction.TargetUnit.UnitEnumType), conversionFunction); + } + else + { + throw InvalidConversionException.CreateIncompatibleUnitsException(fromUnit, toQuantity); + } + } + } + + private static IEnumerable GetConversionsWithCustomUnits(this QuantityInfo fromQuantity, QuantityInfo toQuantity, + Dictionary unitMappings, + bool reduceConstants) + { + Type targetUnitType = toQuantity.UnitType; + ConversionExpression conversionWithBaseUnits = fromQuantity.BaseDimensions.GetConversionExpression(toQuantity.BaseDimensions); + foreach (KeyValuePair unitMapping in unitMappings) + { + // a custom target unit was specified for the conversion (without specifying an expression) + UnitKey fromUnitKey = unitMapping.Key; + UnitInfo fromUnit = unitMapping.Value.SourceUnit; + UnitInfo targetUnit = unitMapping.Value.TargetUnit; + ConversionExpression expressionForUnits = conversionWithBaseUnits.GetExpressionForUnits(fromUnit, targetUnit, reduceConstants); + var conversionKey = new QuantityConversionKey(fromUnitKey, targetUnitType); + yield return new ConversionEntry(conversionKey, new QuantityConversionFunction(expressionForUnits, targetUnit.UnitKey)); + } + } + + private static IEnumerable GetConversionsWithBaseUnits(this QuantityInfo fromQuantity, QuantityInfo toQuantity, + Dictionary unitMappings, + bool reduceConstants) + { + // no conversion functions provided: constructing the expressions using the BaseDimensions + Type targetUnitType = toQuantity.UnitType; + ConversionExpression conversionWithBaseUnits = fromQuantity.BaseDimensions.GetConversionExpression(toQuantity.BaseDimensions); + IReadOnlyList unitInfos = fromQuantity.UnitInfos; + var nbUnits = unitInfos.Count; + for (var i = 0; i < nbUnits; i++) + { + UnitInfo fromUnit = unitInfos[i]; + var conversionKey = new QuantityConversionKey(fromUnit.UnitKey, targetUnitType); + if (unitMappings.TryGetValue(conversionKey.FromUnit, out CustomQuantityConversionUnitMapping? customQuantityConversion)) + { + // a custom target unit was specified for the conversion (without specifying an expression) + UnitInfo targetUnit = customQuantityConversion.TargetUnit; + ConversionExpression expressionForUnits = conversionWithBaseUnits.GetExpressionForUnits(fromUnit, targetUnit, reduceConstants); + yield return new ConversionEntry(conversionKey, new QuantityConversionFunction(expressionForUnits, targetUnit.UnitKey)); + } + else if (fromUnit.BaseUnits != BaseUnits.Undefined) + { + if (toQuantity.TryGetConversionFrom(fromUnit, conversionWithBaseUnits, reduceConstants, out QuantityConversionFunction conversionFunction)) + { + yield return new ConversionEntry(conversionKey, conversionFunction); + } + else + { + throw InvalidConversionException.CreateIncompatibleUnitsException(fromUnit, toQuantity); + } + } + } + } + + private static IEnumerable GetConversionsWithAllUnits(this QuantityInfo fromQuantity, QuantityInfo toQuantity, + Dictionary unitMappings, + Dictionary conversionExpressions, + bool reduceConstants) + { + // there are two supported scenarios: + // 1. the two quantities have compatible BaseDimensions (i.e. equal or inverse) and there are units with compatible BaseUnits + // 2. the conversionOptions provide at least one conversion expression that can be used as the "conversion base" for the rest of the units + IReadOnlyList fromQuantityUnits = fromQuantity.UnitInfos; + var fromQuantityUnitsCount = fromQuantityUnits.Count; + if (conversionExpressions.Count == 0) + { + // 1. no conversion functions provided: constructing the expressions using the BaseDimensions + ConversionExpression conversionWithBaseUnits = fromQuantity.BaseDimensions.GetConversionExpression(toQuantity.BaseDimensions); + for (var i = 0; i < fromQuantityUnitsCount; i++) + { + UnitInfo fromUnit = fromQuantityUnits[i]; + var conversionKey = new QuantityConversionKey(fromUnit.UnitKey, toQuantity.UnitType); + if (unitMappings.TryGetValue(conversionKey.FromUnit, out CustomQuantityConversionUnitMapping? customQuantityConversion)) + { + // a custom target unit was specified for the conversion (without specifying an expression) + UnitInfo targetUnit = customQuantityConversion.TargetUnit; + ConversionExpression expressionForUnits = conversionWithBaseUnits.GetExpressionForUnits(fromUnit, targetUnit, reduceConstants); + yield return new ConversionEntry(conversionKey, new QuantityConversionFunction(expressionForUnits, targetUnit.UnitKey)); + } + else if (toQuantity.TryGetConversionFrom(fromUnit, conversionWithBaseUnits, reduceConstants, out QuantityConversionFunction conversionFunction)) + { + yield return new ConversionEntry(conversionKey, conversionFunction); + } + else + { + throw InvalidConversionException.CreateIncompatibleUnitsException(fromUnit, toQuantity); + } + } + } + else + { + // 2. an explicit conversion function was provided and will be used as the base for the rest of the units + CustomQuantityConversionExpressionMapping customConversion = conversionExpressions.First().Value; + UnitInfo sourceConversionBase = customConversion.SourceUnit; + UnitInfo targetConversionBase = customConversion.TargetUnit; + ConversionExpression conversionWithBase = customConversion.ConversionExpression; + for (var i = 0; i < fromQuantityUnitsCount; i++) + { + UnitInfo fromUnit = fromQuantityUnits[i]; + var conversionKey = new QuantityConversionKey(fromUnit.UnitKey, toQuantity.UnitType); + if (unitMappings.TryGetValue(conversionKey.FromUnit, out CustomQuantityConversionUnitMapping? unitMapping)) + { + // a custom target unit was specified for the conversion (without specifying an expression) + ConversionExpression conversionToSourceBase = fromUnit.GetUnitConversionExpressionTo(sourceConversionBase, false); + ConversionExpression conversionToTargetBase = conversionWithBase.Evaluate(conversionToSourceBase); + ConversionExpression conversionToTargetUnit = targetConversionBase.GetUnitConversionExpressionTo(unitMapping.TargetUnit, false); + ConversionExpression conversionToTarget = conversionToTargetUnit.Evaluate(conversionToTargetBase, reduceConstants); + yield return new ConversionEntry(conversionKey, new QuantityConversionFunction(conversionToTarget, unitMapping.TargetUnit.UnitKey)); + } + else if (conversionExpressions.TryGetValue(conversionKey.FromUnit, out CustomQuantityConversionExpressionMapping? expressionMapping)) + { + // a custom target unit was specified for the conversion (including the corresponding expression) + var conversionFunction = new QuantityConversionFunction(expressionMapping.ConversionExpression, expressionMapping.TargetUnit.UnitKey); + yield return new ConversionEntry(conversionKey, conversionFunction); + } + else + { + // nothing was specified for the conversion: automatically select the target unit + ConversionExpression conversionToSourceBase = fromUnit.GetUnitConversionExpressionTo(sourceConversionBase, false); + ConversionExpression conversionToTargetBase = conversionWithBase.Evaluate(conversionToSourceBase, reduceConstants); + QuantityConversionFunction conversion = toQuantity.GetConversionWithBase(targetConversionBase, conversionToTargetBase, reduceConstants); + yield return new ConversionEntry(conversionKey, conversion); + } + } + } + } + + private static ConversionExpression GetConversionExpression(this BaseDimensions fromDimensions, BaseDimensions toDimensions) + { + if (fromDimensions.IsInverseOf(toDimensions)) + { + return new ConversionExpression(1, null, -1); + } + + if (fromDimensions == toDimensions) + { + return QuantityValue.One; + } + + // note: technically we could to attempt to work with the powers, but currently there aren't any such cases + throw InvalidConversionException.CreateIncompatibleDimensionsException(fromDimensions, toDimensions); + } + + private static bool TryGetConversionExpression(this BaseDimensions fromDimensions, BaseDimensions toDimensions, out ConversionExpression conversionExpression) + { + if (fromDimensions.IsInverseOf(toDimensions)) + { + conversionExpression = new ConversionExpression(1, null, -1); + return true; + } + + if (fromDimensions == toDimensions) + { + conversionExpression = QuantityValue.One; + return true; + } + + // note: technically we could to attempt to work with the powers, but currently there aren't any such cases + conversionExpression = default; + return false; + } + + private static ConvertValueDelegate GetConversionDelegate(this BaseDimensions fromDimensions, BaseDimensions toDimensions) + { + if (fromDimensions.IsInverseOf(toDimensions)) + { + return QuantityValue.Inverse; + } + + if (fromDimensions == toDimensions) + { + return value => value; + } + + // note: technically we could to attempt to work with the powers, but currently there aren't any such cases + throw InvalidConversionException.CreateIncompatibleDimensionsException(fromDimensions, toDimensions); + } + + /// + /// Retrieves a conversion expression for converting to a target quantity from the unit of another quantity type. + /// + /// The target quantity information. + /// The source unit information. + /// Indicates whether to reduce constants in the conversion expression. Default is true. + /// A representing the conversion expression and the target unit key. + /// Thrown when no matching base units are found for the conversion operation. + /// + /// This method is optimized for selecting the target unit that is closest in magnitude to the + /// . + /// + public static QuantityConversionFunction GetQuantityConversionFrom(this QuantityInfo toQuantity, UnitInfo fromUnit, bool reduceConstants = true) + { + QuantityInfo fromQuantityInfo = fromUnit.QuantityInfo; + ConversionExpression conversionExpression = fromQuantityInfo.BaseDimensions.GetConversionExpression(toQuantity.BaseDimensions); + + if (toQuantity.TryGetConversionFrom(fromUnit, conversionExpression, reduceConstants, out QuantityConversionFunction conversionFunction)) + { + return conversionFunction; + } + + throw InvalidConversionException.CreateIncompatibleUnitsException(fromUnit, toQuantity); + } + + /// + /// Attempts to get a quantity conversion expression from the specified unit to the target quantity. + /// + /// The target quantity information. + /// The source unit information. + /// Indicates whether to reduce constants in the conversion expression. + /// + /// When this method returns, contains the quantity conversion function if the conversion was successful; otherwise, + /// null. + /// This parameter is passed uninitialized. + /// + /// true if the conversion expression was successfully retrieved; otherwise, false. + public static bool TryGetQuantityConversionFrom(this QuantityInfo toQuantity, UnitInfo fromUnit, bool reduceConstants, + out QuantityConversionFunction conversionFunction) + { + if (fromUnit.QuantityInfo.BaseDimensions.TryGetConversionExpression(toQuantity.BaseDimensions, out ConversionExpression conversionExpression)) + { + return toQuantity.TryGetConversionFrom(fromUnit, conversionExpression, reduceConstants, out conversionFunction); + } + + conversionFunction = default; + return false; + } + + private static bool TryGetConversionFrom(this QuantityInfo toQuantity, UnitInfo fromUnit, ConversionExpression conversionWithBase, bool reduceConstants, + out QuantityConversionFunction conversionFunction) + { + QuantityInfo fromQuantityInfo = fromUnit.QuantityInfo; + if (fromUnit.BaseUnits != BaseUnits.Undefined) + { + if (toQuantity.UnitInfos.TryGetUnitWithBase(fromUnit.BaseUnits, out UnitInfo? matchingBaseUnit)) + { + conversionFunction = new QuantityConversionFunction(conversionWithBase, matchingBaseUnit.UnitKey); + return true; + } + } + + if (fromQuantityInfo.TryGetSIBaseUnit(out UnitInfo? sourceSI) && toQuantity.TryGetSIBaseUnit(out UnitInfo? targetSI)) + { + ConversionExpression conversionToSI = fromUnit.GetUnitConversionExpressionTo(sourceSI, false); + ConversionExpression fromUnitToTargetSI = conversionWithBase.Evaluate(conversionToSI, reduceConstants); + conversionFunction = toQuantity.GetConversionWithBase(targetSI, fromUnitToTargetSI, reduceConstants); + return true; + } + + // one of the quantities doesn't have any SI units: attempt find an exactly matching base + IReadOnlyList fromQuantityUnits = fromQuantityInfo.UnitInfos; + var fromQuantityUnitsCount = fromQuantityUnits.Count; + for (var i = 0; i < fromQuantityUnitsCount; i++) + { + UnitInfo sourceUnit = fromQuantityUnits[i]; + if (sourceUnit.BaseUnits == BaseUnits.Undefined || sourceUnit.BaseUnits == fromUnit.BaseUnits) + { + continue; + } + + if (!toQuantity.UnitInfos.TryGetUnitWithBase(sourceUnit.BaseUnits, out UnitInfo? matchingUnit)) + { + continue; + } + + ConversionExpression conversionToUnit = fromUnit.GetUnitConversionExpressionTo(sourceUnit, false); + ConversionExpression fromUnitToMatchingUnit = conversionWithBase.Evaluate(conversionToUnit, reduceConstants); + conversionFunction = toQuantity.GetConversionWithBase(matchingUnit, fromUnitToMatchingUnit, reduceConstants); + return true; + } + + conversionFunction = default; + return false; + } + + private static QuantityConversionFunction GetConversionWithBase(this QuantityInfo quantity, UnitInfo baseUnit, ConversionExpression conversionToBase, + bool reduceConstants) + { + UnitInfo currentlySelectedUnit = baseUnit; + ConversionExpression conversionToSelectedUnit = conversionToBase; + QuantityValue currentFactor = GetFactorMagnitude(conversionToBase.Coefficient); + if (currentFactor == QuantityValue.One) + { + return new QuantityConversionFunction(conversionToBase, baseUnit.UnitKey); + } + + IReadOnlyList unitInfos = quantity.UnitInfos; + var nbUnits = unitInfos.Count; + for (var i = 0; i < nbUnits; i++) + { + UnitInfo toUnitInfo = unitInfos[i]; + if (toUnitInfo == baseUnit) + { + continue; + } + + ConversionExpression fromBaseToUnitConversion = baseUnit.GetUnitConversionExpressionTo(toUnitInfo, false); + ConversionExpression expressionToUnit = fromBaseToUnitConversion.Evaluate(conversionToBase, reduceConstants); + QuantityValue expressionFactor = GetFactorMagnitude(expressionToUnit.Coefficient); + if (expressionFactor >= currentFactor) + { + continue; + } + + currentlySelectedUnit = toUnitInfo; + conversionToSelectedUnit = expressionToUnit; + currentFactor = expressionFactor; + if (currentFactor == QuantityValue.One) + { + break; // found the best possible option + } + } + + return new QuantityConversionFunction(conversionToSelectedUnit, currentlySelectedUnit.UnitKey); + + static QuantityValue GetFactorMagnitude(QuantityValue conversionFactor) + { + conversionFactor = QuantityValue.Abs(conversionFactor); + return conversionFactor < QuantityValue.One ? QuantityValue.Inverse(conversionFactor) : conversionFactor; + } + } + + /// + /// Gets the conversion expression to convert a quantity from the specified unit of the source quantity type to the + /// specified unit of the target quantity type. + /// + /// The unit information of the source quantity type. + /// The unit information of the target quantity type. + /// + /// A boolean value indicating whether to reduce constants in the conversion expression. + /// Default is true. + /// + /// + /// A representing the conversion from the specified unit of the source quantity + /// type to the specified unit of the target quantity type. + /// + /// Thrown when no matching base units are found for the conversion operation. + public static ConversionExpression GetQuantityConversionExpressionTo(this UnitInfo fromUnitInfo, UnitInfo toUnitInfo, bool reduceConstants = true) + { + ConversionExpression conversionWithBaseUnits = fromUnitInfo.QuantityInfo.BaseDimensions.GetConversionExpression(toUnitInfo.QuantityInfo.BaseDimensions); + return conversionWithBaseUnits.GetExpressionForUnits(fromUnitInfo, toUnitInfo, reduceConstants); + } + + private static ConversionExpression GetExpressionForUnits(this ConversionExpression conversionWithBaseUnits, UnitInfo fromUnitInfo, UnitInfo toUnitInfo, + bool reduceConstants) + { + if (fromUnitInfo.BaseUnits != BaseUnits.Undefined && fromUnitInfo.BaseUnits == toUnitInfo.BaseUnits) + { + return conversionWithBaseUnits; + } + + QuantityInfo fromQuantityInfo = fromUnitInfo.QuantityInfo; + QuantityInfo toQuantityInfo = toUnitInfo.QuantityInfo; + if (fromQuantityInfo.TryGetSIBaseUnit(out UnitInfo? sourceSI) && toQuantityInfo.TryGetSIBaseUnit(out UnitInfo? targetSI)) + { + ConversionExpression fromUnitToTargetSI = conversionWithBaseUnits.Evaluate(fromUnitInfo.GetUnitConversionExpressionTo(sourceSI)); + ConversionExpression fromUnitToTargetUnit = targetSI.GetUnitConversionExpressionTo(toUnitInfo).Evaluate(fromUnitToTargetSI, reduceConstants); + return fromUnitToTargetUnit; + } + + IReadOnlyList fromQuantityUnits = fromQuantityInfo.UnitInfos; + var fromQuantityUnitsCount = fromQuantityUnits.Count; + for (var i = 0; i < fromQuantityUnitsCount; i++) + { + UnitInfo sourceUnit = fromQuantityUnits[i]; + if (sourceUnit.BaseUnits == BaseUnits.Undefined || !toQuantityInfo.UnitInfos.TryGetUnitWithBase(sourceUnit.BaseUnits, out UnitInfo? matchingUnit)) + { + continue; + } + + ConversionExpression fromUnitToMatchingUnit = conversionWithBaseUnits.Evaluate(fromUnitInfo.GetUnitConversionExpressionTo(sourceUnit, false)); + ConversionExpression fromUnitToTargetUnit = matchingUnit.GetUnitConversionExpressionTo(toUnitInfo, false).Evaluate(fromUnitToMatchingUnit, true); + return fromUnitToTargetUnit; + } + + throw InvalidConversionException.CreateIncompatibleUnitsException(fromUnitInfo, toQuantityInfo); + } + + /// + /// Attempts to get the conversion expression to convert a quantity from the specified unit of the source quantity type + /// to the specified unit of the target quantity type. + /// + /// The unit information of the source quantity type. + /// The unit information of the target quantity type. + /// + /// A boolean value indicating whether to reduce constants in the conversion expression. + /// Default is true. + /// + /// + /// When this method returns, contains the conversion expression from the specified unit of the source quantity type + /// to the specified unit of the target quantity type, if the conversion is successful; otherwise, null. + /// + /// + /// true if the conversion expression was successfully retrieved; otherwise, false. + /// + /// Thrown when no matching base units are found for the conversion operation. + public static bool TryGetQuantityConversionExpressionTo(this UnitInfo fromUnitInfo, UnitInfo toUnitInfo, bool reduceConstants, [NotNullWhen(true)] out ConversionExpression? conversionExpression) + { + QuantityInfo fromQuantityInfo = fromUnitInfo.QuantityInfo; + QuantityInfo toQuantityInfo = toUnitInfo.QuantityInfo; + + if (!fromQuantityInfo.BaseDimensions.TryGetConversionExpression(toQuantityInfo.BaseDimensions, out ConversionExpression quantityConversionExpression)) + { + conversionExpression = null; + return false; + } + + if (fromUnitInfo.BaseUnits != BaseUnits.Undefined && fromUnitInfo.BaseUnits == toUnitInfo.BaseUnits) + { + conversionExpression = quantityConversionExpression; + return true; + } + + if (fromQuantityInfo.TryGetSIBaseUnit(out UnitInfo? sourceSI) && toQuantityInfo.TryGetSIBaseUnit(out UnitInfo? targetSI)) + { + ConversionExpression fromUnitToTargetSI = quantityConversionExpression.Evaluate(fromUnitInfo.GetUnitConversionExpressionTo(sourceSI)); + conversionExpression = targetSI.GetUnitConversionExpressionTo(toUnitInfo).Evaluate(fromUnitToTargetSI, reduceConstants); + return true; + } + + IReadOnlyList fromQuantityUnits = fromQuantityInfo.UnitInfos; + var fromQuantityUnitsCount = fromQuantityUnits.Count; + for (var i = 0; i < fromQuantityUnitsCount; i++) + { + UnitInfo sourceUnit = fromQuantityUnits[i]; + if (sourceUnit.BaseUnits == BaseUnits.Undefined || !toQuantityInfo.UnitInfos.TryGetUnitWithBase(sourceUnit.BaseUnits, out UnitInfo? matchingUnit)) + { + continue; + } + + ConversionExpression fromUnitToMatchingUnit = quantityConversionExpression.Evaluate(fromUnitInfo.GetUnitConversionExpressionTo(sourceUnit, false)); + conversionExpression = matchingUnit.GetUnitConversionExpressionTo(toUnitInfo, false).Evaluate(fromUnitToMatchingUnit, true); + return true; + } + + conversionExpression = null; + return false; + } +} diff --git a/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConversions/UnitConversionMapping.cs b/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConversions/UnitConversionMapping.cs new file mode 100644 index 0000000000..5c55f5c9b0 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConversions/UnitConversionMapping.cs @@ -0,0 +1,47 @@ +// 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 System.Diagnostics; + +namespace UnitsNet; + +/// +/// Represents the mapping-key used for converting between the units of two different quantities. +/// +[DebuggerDisplay("{FromUnitKey,nq} -> {ToUnitKey,nq}")] +internal readonly record struct UnitConversionMapping +{ + /// + /// Initializes a new instance of the struct with the specified source and target + /// unit keys. + /// + /// The key representing the source unit for the conversion. + /// The key representing the target unit for the conversion. + public UnitConversionMapping(UnitKey FromUnitKey, UnitKey ToUnitKey) + { + this.FromUnitKey = FromUnitKey; + this.ToUnitKey = ToUnitKey; + } + + public UnitKey FromUnitKey { get; } + public UnitKey ToUnitKey { get; } + + /// + /// Creates a new instance of using the specified units. + /// + /// The type of the source units, which must be a struct and an enum + /// The type of the target units, which must be a struct and an enum. + /// The unit of the quantity to convert from. + /// The unit to convert to. + /// + /// A new representing the conversion from to + /// . + /// + public static UnitConversionMapping Create(TSourceUnit fromUnit, TTargetUnit toUnit) + where TSourceUnit : struct, Enum + where TTargetUnit : struct, Enum + { + return new UnitConversionMapping(UnitKey.ForUnit(fromUnit), UnitKey.ForUnit(toUnit)); + } +} diff --git a/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConverterBuildOptions.cs b/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConverterBuildOptions.cs new file mode 100644 index 0000000000..b671c81ecd --- /dev/null +++ b/UnitsNet/CustomCode/QuantityConverters/Builder/QuantityConverterBuildOptions.cs @@ -0,0 +1,165 @@ +// 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 System.Collections.Generic; + +namespace UnitsNet; + +/// +/// Provides options for building a instance. +/// +/// +/// This class allows configuring various settings related to unit conversion, such as caching modes, +/// constant reduction, and custom caching options for specific quantity types. +/// +public sealed class QuantityConverterBuildOptions +{ + private readonly Dictionary _customQuantityOptions = []; + + /// + /// Initializes a new instance of the class. + /// + /// Indicates whether the build options should be frozen, preventing further modifications. + /// Specifies the default caching mode for unit conversions. + /// Indicates whether constant reduction should be applied during unit conversions. + public QuantityConverterBuildOptions(bool freeze = false, ConversionCachingMode defaultCachingMode = ConversionCachingMode.None, + bool reduceConstants = true) + { + Freeze = freeze; + DefaultCachingMode = defaultCachingMode; + ReduceConstants = reduceConstants; + } + + /// + /// Gets a value indicating whether the quantity converter is frozen, preventing any further modifications. + /// + public bool Freeze { get; private set; } + + /// + /// Gets the default caching mode for unit conversions. + /// + /// + /// The default caching mode, which determines how unit conversions are cached. + /// + public ConversionCachingMode DefaultCachingMode { get; private set; } + + /// + /// Gets a value indicating whether constant values should be reduced during unit conversions. + /// + /// + /// When set to true, constant values in unit conversions are reduced to their simplest form. + /// This can help improve performance and reduce memory usage. + /// + public bool ReduceConstants { get; private set; } + + internal IReadOnlyDictionary CustomQuantityOptions + { + get => _customQuantityOptions; + } + + internal QuantityConversionOptions? QuantityConversionOptions { get; private set; } + +#if OPTIONS_ACCEPTED +// TODO add tests for these + /// + /// Enables or disables dynamic caching for unit conversions. + /// + /// If set to true, dynamic caching is enabled; otherwise, it is disabled. + /// + /// The current instance with the updated dynamic + /// caching setting. + /// + public QuantityConverterBuildOptions WithDynamicCachingEnabled(bool dynamicCachingEnabled = true) + { + Freeze = !dynamicCachingEnabled; + return this; + } + + /// + /// Sets the default caching mode for unit conversions. + /// + /// The default caching mode to be used for unit conversions. + /// + /// The current instance with the updated default + /// caching mode. + /// + public QuantityConverterBuildOptions WithDefaultCachingMode(ConversionCachingMode defaultCachingMode) + { + DefaultCachingMode = defaultCachingMode; + return this; + } + + /// + /// Enables or disables the reduction of constants during unit conversions. + /// + /// + /// If set to true, constants will be reduced during conversions; otherwise, they will + /// not be reduced. + /// + /// + /// The current instance with the updated constant + /// reduction setting. + /// + public QuantityConverterBuildOptions WithConstantsReduction(bool reduceConstants = true) + { + ReduceConstants = reduceConstants; + return this; + } +#endif + + /// + /// Configures custom caching options for a specific quantity type. + /// + /// The type of the quantity for which to set custom caching options. + /// The caching options to be applied to the specified quantity type. + /// + /// The current instance with the updated custom + /// caching options. + /// + public QuantityConverterBuildOptions WithCustomCachingOptions(ConversionCacheOptions quantityCacheOptions) + where TQuantity : IQuantity + { + _customQuantityOptions.Add(typeof(TQuantity), quantityCacheOptions); + return this; + } + + /// + /// Configures the implicit conversion options for the instance. + /// + /// + /// The instance that specifies the implicit conversion settings. + /// + /// + /// The current instance with the updated implicit conversion options. + /// + /// + /// This method allows setting custom implicit conversion rules and units to be used during quantity conversions. + /// + public QuantityConverterBuildOptions WithImplicitConversionOptions(QuantityConversionOptions quantityConversionOptions) + { + QuantityConversionOptions = quantityConversionOptions; + return this; + } + + /// + /// Configures implicit conversion options for the . + /// + /// + /// An action to configure the . + /// + /// + /// The current instance of with the updated implicit conversion options. + /// + /// + /// This method allows you to specify custom implicit conversions between different quantities and units. + /// It initializes the if it is not already set and applies the provided + /// configuration action to it. + /// + public QuantityConverterBuildOptions WithImplicitConversionOptions(Action implicitConversions) + { + QuantityConversionOptions ??= new QuantityConversionOptions(); + implicitConversions(QuantityConversionOptions); + return this; + } +} diff --git a/UnitsNet/CustomCode/QuantityConverters/Builder/UnitConversions/UnitConversionsBuilderExtensions.cs b/UnitsNet/CustomCode/QuantityConverters/Builder/UnitConversions/UnitConversionsBuilderExtensions.cs new file mode 100644 index 0000000000..f22148e276 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityConverters/Builder/UnitConversions/UnitConversionsBuilderExtensions.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace UnitsNet; + +internal static class UnitConversionsBuilderExtensions +{ + /// + /// Retrieves a collection of conversion expressions for the specified quantities. + /// + /// The collection of quantities for which to get conversion expressions. + /// The caching mode to use for the conversion expressions. + /// A boolean value indicating whether to reduce constants in the conversion expressions. Defaults to true. + /// An enumerable collection of key-value pairs where the key is a and the value is a representing the conversion expression. + /// Thrown when an invalid caching mode is specified. + public static IEnumerable> GetUnitConversionFunctions(this IEnumerable quantities, ConversionCachingMode cachingMode, bool reduceConstants = true) + { + return cachingMode switch + { + ConversionCachingMode.None => [], + ConversionCachingMode.BaseOnly => quantities.SelectMany(GetBaseConversions), + ConversionCachingMode.All => quantities.SelectMany(x => GetExpandedConversions(x, reduceConstants)), + _ => throw new ArgumentOutOfRangeException() + }; + } + + /// + /// Retrieves the conversion expressions for the specified quantities, considering the provided caching mode, + /// constant reduction option, and custom quantity options. + /// + /// The collection of quantity information objects. + /// The default caching mode to use if no custom options are specified. + /// Indicates whether to reduce constants by default. + /// A dictionary of custom quantity options, keyed by quantity type. + /// An enumerable of key-value pairs, where the key is a and the value is a . + /// Thrown when an invalid caching mode is encountered. + public static IEnumerable> GetUnitConversionFunctions(this IEnumerable quantities, ConversionCachingMode defaultCachingMode, bool defaultConstantsReduction, + IReadOnlyDictionary customQuantityOptions) + { + if (customQuantityOptions.Count == 0) + { + return quantities.GetUnitConversionFunctions(defaultCachingMode, defaultConstantsReduction); + } + + return quantities.SelectMany(quantityInfo => + customQuantityOptions.TryGetValue(quantityInfo.QuantityType, out ConversionCacheOptions? customCacheOptions) + ? customCacheOptions.CachingMode switch + { + ConversionCachingMode.None => [], + ConversionCachingMode.BaseOnly => GetBaseConversions(quantityInfo), + ConversionCachingMode.All => GetExpandedConversions(quantityInfo, customCacheOptions.ReduceConstants), + _ => throw new ArgumentOutOfRangeException() + } + : defaultCachingMode switch + { + ConversionCachingMode.None => [], + ConversionCachingMode.BaseOnly => GetBaseConversions(quantityInfo), + ConversionCachingMode.All => GetExpandedConversions(quantityInfo, defaultConstantsReduction), + _ => throw new ArgumentOutOfRangeException() + }); + } + + private static IEnumerable> GetExpandedConversions(QuantityInfo quantityInfo, bool reduceConstants) + { + UnitInfo baseUnit = quantityInfo.BaseUnitInfo; + UnitKey baseUnitKey = baseUnit.UnitKey; + IReadOnlyList unitInfos = quantityInfo.UnitInfos; + var nbUnits = unitInfos.Count; + for (var i = 0; i < nbUnits; i++) + { + UnitInfo fromUnit = unitInfos[i]; + if (fromUnit == baseUnit) + { + foreach (KeyValuePair keyValuePair in GetConversionsWithBase(quantityInfo, baseUnit, baseUnitKey)) + { + yield return keyValuePair; + } + } + else + { + UnitKey fromUnitKey = fromUnit.UnitKey; + // yield return new UnitConversionMapping(UnitConversionKey.ToSelf(fromUnitKey), value => value); + for (var p = 0; p < nbUnits; p++) + { + if (i == p) continue; + UnitInfo toUnit = unitInfos[p]; + if (toUnit == baseUnit) + { + continue; + } + + var conversionKey = UnitConversionKey.Create(fromUnitKey, toUnit.UnitKey); + ConversionExpression conversion = toUnit.ConversionFromBase.Evaluate(fromUnit.ConversionToBase, reduceConstants); + yield return new KeyValuePair(conversionKey, conversion); + } + } + } + } + + private static IEnumerable> GetBaseConversions(QuantityInfo quantityInfo) + { + return GetConversionsWithBase(quantityInfo, quantityInfo.BaseUnitInfo, quantityInfo.BaseUnitInfo.UnitKey); + } + + private static IEnumerable> GetConversionsWithBase(QuantityInfo quantityInfo, UnitInfo baseUnit, UnitKey baseUnitKey) + { + IReadOnlyList unitInfos = quantityInfo.UnitInfos; + var nbUnits = unitInfos.Count; + for (var i = 0; i < nbUnits; i++) + { + UnitInfo unit = unitInfos[i]; + if (unit == baseUnit) + { + continue; // yield return new UnitConversionMapping(UnitConversionKey.ToSelf(baseUnitKey), value => value); + } + + UnitKey unitKey = unit.UnitKey; + yield return new KeyValuePair(UnitConversionKey.Create(baseUnitKey, unitKey), unit.ConversionFromBase); + yield return new KeyValuePair(UnitConversionKey.Create(unitKey, baseUnitKey), unit.ConversionToBase); + } + } + + /// + /// Gets the conversion expression between two units. + /// + /// The unit information of the source unit. + /// The unit information of the target unit. + /// + /// Indicates whether to reduce constants in the conversion expression. Defaults to + /// true. + /// + /// A representing the conversion from the source unit to the target unit. + /// + /// If the source unit is the base unit, the conversion from the base unit to the target unit is returned. + /// If the target unit is the base unit, the conversion from the source unit to the base unit is returned. + /// Otherwise, the conversion is evaluated using the conversion expressions from the source unit to the base unit and + /// from the base unit to the target unit. + /// + internal static ConversionExpression GetUnitConversionExpressionTo(this UnitInfo fromUnitInfo, UnitInfo toUnitInfo, bool reduceConstants = true) + { + // if we're here, then units are very likely to be different + UnitInfo baseUnit = fromUnitInfo.QuantityInfo.BaseUnitInfo; + if (fromUnitInfo == baseUnit) + { + return toUnitInfo.ConversionFromBase; + } + + if (toUnitInfo == baseUnit) + { + return fromUnitInfo.ConversionToBase; + } + + return toUnitInfo.ConversionFromBase.Evaluate(fromUnitInfo.ConversionToBase, reduceConstants); + } +} diff --git a/UnitsNet/CustomCode/QuantityConverters/DynamicQuantityConverter.cs b/UnitsNet/CustomCode/QuantityConverters/DynamicQuantityConverter.cs new file mode 100644 index 0000000000..58c0f0bea0 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityConverters/DynamicQuantityConverter.cs @@ -0,0 +1,462 @@ +// 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 System.Collections.Concurrent; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace UnitsNet; + +internal sealed class DynamicQuantityConverter : UnitConverter +{ + private readonly ConcurrentDictionary _unitConversions; + private readonly ConcurrentDictionary _quantityConversions; + private readonly Func _unitConversionExpressionFactory; + private readonly bool _reduceConstants; + + public DynamicQuantityConverter(UnitParser unitParser, + IEnumerable quantityConversions, + IEnumerable> unitConversionFunctions, + IEnumerable> quantityConversionFunctions, bool reduceConstants) + : base(unitParser, quantityConversions) + { + _reduceConstants = reduceConstants; + _unitConversions = new ConcurrentDictionary(unitConversionFunctions); + _quantityConversions = new ConcurrentDictionary(quantityConversionFunctions); + _unitConversionExpressionFactory = GetConversionExpression; + } + + public override bool TryConvertValue(QuantityValue value, TUnit fromUnit, TUnit toUnit, out QuantityValue convertedValue) + { + return TryConvertValue(value, UnitConversionKey.Create(fromUnit, toUnit), out convertedValue); + } + + public override bool TryConvertValue(QuantityValue value, UnitKey fromUnitKey, UnitKey toUnitKey, out QuantityValue convertedValue) + { + return fromUnitKey.UnitEnumType == toUnitKey.UnitEnumType + ? TryConvertValue(value, UnitConversionKey.Create(fromUnitKey, toUnitKey), out convertedValue) + : TryConvertValueFromOneQuantityToAnother(value, fromUnitKey, toUnitKey, out convertedValue); + } + + private bool TryConvertValue(QuantityValue value, UnitConversionKey conversionKey, out QuantityValue convertedValue) + { + if (conversionKey.HasSameUnits) + { + convertedValue = value; + return true; + } + + if (_unitConversions.TryGetValue(conversionKey, out ConvertValueDelegate? cachedConversion)) + { + convertedValue = cachedConversion(value); + return true; + } + + if (TryGetUnitInfo(conversionKey.FromUnitKey, out UnitInfo? fromUnitInfo) && + TryGetUnitInfo(new UnitKey(conversionKey.FromUnitKey.UnitEnumType, conversionKey.ToUnitValue), out UnitInfo? toUnitInfo)) + // TryGetUnitInfo(conversionKey.FromUnitKey with { UnitValue = conversionKey.ToUnitValue }, out UnitInfo? toUnitInfo)) + { + cachedConversion = _unitConversions.GetOrAdd(conversionKey, fromUnitInfo.GetUnitConversionExpressionTo(toUnitInfo, _reduceConstants)); + convertedValue = cachedConversion(value); + return true; + } + + convertedValue = default; + return false; + } + + private bool TryConvertValueFromOneQuantityToAnother(QuantityValue value, UnitKey fromUnitKey, UnitKey toUnitKey, out QuantityValue convertedValue) + { + var defaultConversionKey = new QuantityConversionKey(fromUnitKey, toUnitKey.UnitEnumType); + if (_quantityConversions.TryGetValue(defaultConversionKey, out QuantityConversionFunction conversionFunction)) + { + return TryConvertValue(conversionFunction.Convert(value), new UnitConversionKey(conversionFunction.TargetUnit, toUnitKey.UnitEnumValue), + out convertedValue); + } + + if (TryGetUnitInfo(fromUnitKey, out UnitInfo? fromUnitInfo) && TryGetUnitInfo(toUnitKey, out UnitInfo? toUnitInfo)) + { + return TryConvertValueFromOneQuantityToAnother(value, fromUnitInfo, toUnitInfo, out convertedValue); + } + + convertedValue = default; + return false; + } + + protected override bool TryConvertValueInternal(QuantityValue value, UnitInfo fromUnitInfo, UnitInfo toUnitInfo, out QuantityValue convertedValue) + { + if (fromUnitInfo == toUnitInfo) + { + // TODO see about this: the only possible route in is from TryConvertValueByName + convertedValue = value; + return true; + } + + UnitKey fromUnitKey = fromUnitInfo.UnitKey; + UnitKey toUnitKey = toUnitInfo.UnitKey; + if (fromUnitKey.UnitEnumType == toUnitKey.UnitEnumType) + { + ConvertValueDelegate conversionDelegate = GetOrAdd(UnitConversionKey.Create(fromUnitKey, toUnitKey), fromUnitInfo, toUnitInfo); + convertedValue = conversionDelegate(value); + return true; + } + + var defaultConversionKey = new QuantityConversionKey(fromUnitKey, toUnitKey.UnitEnumType); + if (!_quantityConversions.TryGetValue(defaultConversionKey, out QuantityConversionFunction conversionFunction)) + { + if (ConversionDefined(fromUnitInfo.QuantityInfo, toUnitInfo.QuantityInfo) && + fromUnitInfo.TryGetQuantityConversionExpressionTo(toUnitInfo, _reduceConstants, out ConversionExpression? conversionExpression)) + { + conversionFunction = _quantityConversions.GetOrAdd(defaultConversionKey, new QuantityConversionFunction(conversionExpression, toUnitKey)); + } + else + { + convertedValue = default; + return false; + } + } + + if (conversionFunction.TargetUnit == toUnitKey) + { + convertedValue = conversionFunction.Convert(value); + return true; + } + + ConvertValueDelegate targetToUnitConversion = GetOrAddConversionTo(UnitConversionKey.Create(conversionFunction.TargetUnit, toUnitKey), toUnitInfo); + convertedValue = targetToUnitConversion(conversionFunction.Convert(value)); + return true; + } + + public override QuantityValue ConvertValue(QuantityValue value, TUnit fromUnit, TUnit toUnit) + { + return ConvertValue(value, UnitConversionKey.Create(fromUnit, toUnit)); + } + + public override QuantityValue ConvertValue(QuantityValue value, UnitKey fromUnitKey, UnitKey toUnitKey) + { + return fromUnitKey.UnitEnumType == toUnitKey.UnitEnumType + ? ConvertValue(value, UnitConversionKey.Create(fromUnitKey, toUnitKey)) + : ConvertValueFromOneQuantityToAnother(value, fromUnitKey, toUnitKey); + } + + private QuantityValue ConvertValue(QuantityValue value, UnitConversionKey conversionKey) + { + if (conversionKey.HasSameUnits) + { + return value; + } + + ConvertValueDelegate conversion = _unitConversions.GetOrAdd(conversionKey, _unitConversionExpressionFactory); + return conversion(value); + } + + private QuantityValue ConvertValueFromOneQuantityToAnother(QuantityValue value, UnitKey fromUnitKey, UnitKey toUnitKey) + { + var defaultConversionKey = new QuantityConversionKey(fromUnitKey, toUnitKey.UnitEnumType); + if (_quantityConversions.TryGetValue(defaultConversionKey, out QuantityConversionFunction defaultConversion)) + { + return defaultConversion.TargetUnit.UnitEnumValue == toUnitKey.UnitEnumValue + ? defaultConversion.Convert(value) + : ConvertValue(defaultConversion.Convert(value), UnitConversionKey.Create(defaultConversion.TargetUnit, toUnitKey)); + } + + UnitInfo fromUnitInfo = GetUnitInfo(fromUnitKey); + UnitInfo toUnitInfo = GetUnitInfo(toUnitKey); + + ConvertValueDelegate conversionExpression = GetConversionFromOneQuantityToAnother(fromUnitInfo, toUnitInfo, _reduceConstants); + QuantityValue convertedValue = conversionExpression(value); + _quantityConversions.TryAdd(defaultConversionKey, new QuantityConversionFunction(conversionExpression, toUnitKey)); + return convertedValue; + } + + protected override QuantityValue ConvertValueInternal(QuantityValue value, UnitInfo fromUnitInfo, UnitInfo toUnitInfo) + { + if (fromUnitInfo == toUnitInfo) + { + return value; + } + + UnitKey fromUnitKey = fromUnitInfo.UnitKey; + UnitKey toUnitKey = toUnitInfo.UnitKey; + if (fromUnitKey.UnitEnumType == toUnitKey.UnitEnumType) + { + ConvertValueDelegate conversionDelegate = GetOrAdd(UnitConversionKey.Create(fromUnitKey, toUnitKey), fromUnitInfo, toUnitInfo); + return conversionDelegate(value); + } + + QuantityConversionFunction conversionFunction = GetOrAdd(new QuantityConversionKey(fromUnitKey, toUnitKey.UnitEnumType), fromUnitInfo, toUnitInfo); + if (conversionFunction.TargetUnit.UnitEnumValue == toUnitKey.UnitEnumValue) + { + return conversionFunction.Convert(value); + } + + ConvertValueDelegate targetToUnitConversion = GetOrAddConversionTo(UnitConversionKey.Create(conversionFunction.TargetUnit, toUnitKey), toUnitInfo); + return targetToUnitConversion(conversionFunction.Convert(value)); + } + + public override ConvertValueDelegate GetConversionFunction(UnitKey fromUnitKey, UnitKey toUnitKey) + { + if (fromUnitKey == toUnitKey) + { + return value => value; + } + + if (fromUnitKey.UnitEnumType == toUnitKey.UnitEnumType) + { + return _unitConversions.GetOrAdd(UnitConversionKey.Create(fromUnitKey, toUnitKey), _unitConversionExpressionFactory); + } + + UnitInfo fromUnitInfo = GetUnitInfo(fromUnitKey); + UnitInfo toUnitInfo = GetUnitInfo(toUnitKey); + var defaultConversionKey = new QuantityConversionKey(fromUnitKey, toUnitInfo.QuantityInfo.UnitType); + if (!_quantityConversions.TryGetValue(defaultConversionKey, out QuantityConversionFunction defaultConversion)) + { + return GetConversionFromOneQuantityToAnother(fromUnitInfo, toUnitInfo); + } + + if (defaultConversion.TargetUnit == toUnitKey) + { + return defaultConversion.Convert; + } + + // TODO should we be caching the result? (GetOrAddConversionTo) + // TODO the resulting expression might not be fully reduced if _reduceConstants is false + if(!_unitConversions.TryGetValue(UnitConversionKey.Create(defaultConversion.TargetUnit, toUnitKey), out ConvertValueDelegate? conversionToTarget)) + { + conversionToTarget = GetUnitInfo(defaultConversion.TargetUnit).GetUnitConversionExpressionTo(toUnitInfo); + } + + return value => conversionToTarget(defaultConversion.Convert(value)); + } + + public override bool TryGetConversionFunction(UnitKey fromUnitKey, UnitKey toUnitKey, [NotNullWhen(true)] out ConvertValueDelegate? conversionFunction) + { + if (fromUnitKey == toUnitKey) + { + conversionFunction = value => value; + return true; + } + + if (fromUnitKey.UnitEnumType == toUnitKey.UnitEnumType) + { + var conversionKey = UnitConversionKey.Create(fromUnitKey, toUnitKey); + if (_unitConversions.TryGetValue(conversionKey, out conversionFunction)) + { + return true; + } + + if (TryGetUnitInfo(fromUnitKey, out UnitInfo? fromUnitInfo) && TryGetUnitInfo(toUnitKey, out UnitInfo? toUnitInfo)) + { + conversionFunction = _unitConversions.GetOrAdd(conversionKey, fromUnitInfo.GetUnitConversionExpressionTo(toUnitInfo, _reduceConstants)); + return true; + } + } + else if (TryGetUnitInfo(fromUnitKey, out UnitInfo? fromUnitInfo) && TryGetUnitInfo(toUnitKey, out UnitInfo? toUnitInfo)) + { + var defaultConversionKey = new QuantityConversionKey(fromUnitKey, toUnitInfo.QuantityInfo.UnitType); + if (!_quantityConversions.TryGetValue(defaultConversionKey, out QuantityConversionFunction defaultConversion)) + { + return TryGetConversionFromOneQuantityToAnother(fromUnitInfo, toUnitInfo, out conversionFunction); + } + + if (defaultConversion.TargetUnit == toUnitKey) + { + conversionFunction = defaultConversion.Convert; + return true; + } + + // TODO should we be caching the result? (GetOrAddConversionTo) + // TODO the resulting expression might not be fully reduced if _reduceConstants is false + if(!_unitConversions.TryGetValue(UnitConversionKey.Create(defaultConversion.TargetUnit, toUnitKey), out ConvertValueDelegate? conversionToTarget)) + { + conversionToTarget = GetUnitInfo(defaultConversion.TargetUnit).GetUnitConversionExpressionTo(toUnitInfo); + } + + conversionFunction = value => conversionToTarget(defaultConversion.Convert(value)); + return true; + } + + conversionFunction = null; + return false; + } + + public override bool TryConvertTo(QuantityValue value, TSourceUnit fromUnit, + QuantityInfo targetQuantityInfo, + [NotNullWhen(true)] out TTargetQuantity? convertedQuantity) + where TTargetQuantity : default + { + var conversionKey = QuantityConversionKey.Create(fromUnit); + if (_quantityConversions.TryGetValue(conversionKey, out QuantityConversionFunction conversionFunction)) + { + convertedQuantity = targetQuantityInfo.From(conversionFunction.Convert(value), conversionFunction.TargetUnit.ToUnit()); + return true; + } + + if (!TryGetUnitInfo(conversionKey.FromUnit, out UnitInfo? fromUnitInfo)) + { + convertedQuantity = default; + return false; + } + + if (ConversionDefined(fromUnitInfo.QuantityInfo, targetQuantityInfo) && + targetQuantityInfo.TryGetQuantityConversionFrom(fromUnitInfo, _reduceConstants, out QuantityConversionFunction conversionConstructed)) + { + conversionFunction = _quantityConversions.GetOrAdd(conversionKey, conversionConstructed); + convertedQuantity = targetQuantityInfo.From(conversionFunction.Convert(value), conversionFunction.TargetUnit.ToUnit()); + return true; + } + + convertedQuantity = default; + return false; + } + + public override bool TryConvertTo(QuantityValue value, UnitKey fromUnitKey, QuantityInfo targetQuantityInfo, + [NotNullWhen(true)] out IQuantity? convertedQuantity) + { + var conversionKey = new QuantityConversionKey(fromUnitKey, targetQuantityInfo.UnitType); + if (_quantityConversions.TryGetValue(conversionKey, out QuantityConversionFunction conversionFunction)) + { + convertedQuantity = targetQuantityInfo.From(conversionFunction.Convert(value), conversionFunction.TargetUnit); + return true; + } + + if (!TryGetUnitInfo(conversionKey.FromUnit, out UnitInfo? fromUnitInfo)) + { + convertedQuantity = null; + return false; + } + + if (ConversionDefined(fromUnitInfo.QuantityInfo, targetQuantityInfo) && + targetQuantityInfo.TryGetQuantityConversionFrom(fromUnitInfo, _reduceConstants, out QuantityConversionFunction conversionConstructed)) + { + conversionFunction = _quantityConversions.GetOrAdd(conversionKey, conversionConstructed); + convertedQuantity = targetQuantityInfo.From(conversionFunction.Convert(value), conversionFunction.TargetUnit); + return true; + } + + convertedQuantity = null; + return false; + } + + public override TTargetQuantity ConvertTo(QuantityValue value, TSourceUnit fromUnit, + QuantityInfo targetQuantityInfo) + { + var conversionKey = QuantityConversionKey.Create(fromUnit); + QuantityConversionFunction conversionFunction = GetOrAdd(conversionKey, targetQuantityInfo); + // return targetQuantityInfo.Create(conversionFunction.Convert(value), conversionFunction.TargetUnit); + return targetQuantityInfo.From(conversionFunction.Convert(value), conversionFunction.TargetUnit.ToUnit()); + } + + public override IQuantity ConvertTo(QuantityValue value, UnitKey fromUnitKey, QuantityInfo targetQuantityInfo) + { + var conversionKey = new QuantityConversionKey(fromUnitKey, targetQuantityInfo.UnitType); + QuantityConversionFunction conversionFunction = GetOrAdd(conversionKey, targetQuantityInfo); + return targetQuantityInfo.From(conversionFunction.Convert(value), conversionFunction.TargetUnit); + } + + private ConvertValueDelegate GetConversionExpression(UnitConversionKey conversionKey) + { + UnitInfo fromUnitInfo = GetUnitInfo(conversionKey.FromUnitKey); + UnitInfo toUnitInfo = GetUnitInfo(new UnitKey(conversionKey.FromUnitKey.UnitEnumType, conversionKey.ToUnitValue)); + // UnitInfo toUnitInfo = GetUnitInfo(conversionKey.FromUnitKey with { UnitValue = conversionKey.ToUnitValue }); + return fromUnitInfo.GetUnitConversionExpressionTo(toUnitInfo, _reduceConstants); + } + + private ConvertValueDelegate GetOrAdd(UnitConversionKey conversionKey, UnitInfo fromUnitInfo, UnitInfo toUnitInfo) + { +#if NET + return _unitConversions.GetOrAdd(conversionKey, CreateConversionExpressionForUnits, (fromUnitInfo, toUnitInfo, _reduceConstants)); + static ConvertValueDelegate CreateConversionExpressionForUnits(UnitConversionKey key, ValueTuple conversion) + { + return conversion.Item1.GetUnitConversionExpressionTo(conversion.Item2, conversion.Item3); + } +#else + // intentionally not using the factory overload here, as it causes an extra allocation for the Func + return _unitConversions.TryGetValue(conversionKey, out ConvertValueDelegate? conversionFunction) + ? conversionFunction + : _unitConversions.GetOrAdd(conversionKey, fromUnitInfo.GetUnitConversionExpressionTo(toUnitInfo, _reduceConstants)); +#endif + } + + private ConvertValueDelegate GetOrAddConversionTo(UnitConversionKey conversionKey, UnitInfo toUnitInfo) + { +#if NET + return _unitConversions.GetOrAdd(conversionKey, CreateConversionExpressionForUnit, (this, toUnitInfo)); + static ConvertValueDelegate CreateConversionExpressionForUnit(UnitConversionKey key, ValueTuple conversion) + { + DynamicQuantityConverter converter = conversion.Item1; + UnitInfo fromUnitInfo = converter.GetUnitInfo(key.FromUnitKey); + UnitInfo toUnitInfo = conversion.Item2; + return fromUnitInfo.GetUnitConversionExpressionTo(toUnitInfo, converter._reduceConstants); + } +#else + // intentionally not using the factory overload here, as it causes an extra allocation for the Func + if (!_unitConversions.TryGetValue(conversionKey, out ConvertValueDelegate? targetToUnitConversion)) + { + UnitInfo fromUnitInfo = GetUnitInfo(conversionKey.FromUnitKey); + targetToUnitConversion = _unitConversions.GetOrAdd(conversionKey, fromUnitInfo.GetUnitConversionExpressionTo(toUnitInfo, _reduceConstants)); + } + + return targetToUnitConversion; +#endif + } + + private QuantityConversionFunction GetOrAdd(QuantityConversionKey conversionKey, UnitInfo fromUnitInfo, UnitInfo toUnitInfo) + { +#if NET + return _quantityConversions.GetOrAdd(conversionKey, CreateConversionExpressionForUnits, (fromUnitInfo, toUnitInfo, this)); + static QuantityConversionFunction CreateConversionExpressionForUnits(QuantityConversionKey key, ValueTuple conversion) + { + UnitInfo fromUnitInfo = conversion.Item1; + UnitInfo toUnitInfo = conversion.Item2; + DynamicQuantityConverter converter = conversion.Item3; + ConversionExpression conversionExpression = converter.GetConversionFromOneQuantityToAnother(fromUnitInfo, toUnitInfo, converter._reduceConstants); + return new QuantityConversionFunction(conversionExpression, toUnitInfo.UnitKey); + } +#else + // intentionally not using the factory overload here, as it causes an extra allocation for the Func + if (_quantityConversions.TryGetValue(conversionKey, out QuantityConversionFunction conversionFunction)) + { + return conversionFunction; + } + + ConversionExpression conversionExpression = GetConversionFromOneQuantityToAnother(fromUnitInfo, toUnitInfo, _reduceConstants); + return _quantityConversions.GetOrAdd(conversionKey, new QuantityConversionFunction(conversionExpression, toUnitInfo.UnitKey)); +#endif + } + + private QuantityConversionFunction GetOrAdd(QuantityConversionKey conversionKey, QuantityInfo targetQuantityInfo) + { +#if NET + return _quantityConversions.GetOrAdd(conversionKey, CreateConversionFunction, (this, targetQuantityInfo)); + static QuantityConversionFunction CreateConversionFunction(QuantityConversionKey key, ValueTuple conversion) + { + DynamicQuantityConverter converter = conversion.Item1; + QuantityInfo targetQuantityInfo = conversion.Item2; + UnitInfo fromUnitInfo = converter.GetUnitInfo(key.FromUnit); + if (!converter.ConversionDefined(fromUnitInfo.QuantityInfo, targetQuantityInfo)) + { + throw InvalidConversionException.CreateImplicitConversionException(fromUnitInfo.QuantityInfo, targetQuantityInfo); + } + + return targetQuantityInfo.GetQuantityConversionFrom(fromUnitInfo, converter._reduceConstants); + } +#else + // intentionally not using the factory overload here, as it causes an extra allocation for the Func + if (_quantityConversions.TryGetValue(conversionKey, out QuantityConversionFunction existingConversion)) + { + return existingConversion; + } + + UnitInfo fromUnitInfo = GetUnitInfo(conversionKey.FromUnit); + if (!ConversionDefined(fromUnitInfo.QuantityInfo, targetQuantityInfo)) + { + throw InvalidConversionException.CreateImplicitConversionException(fromUnitInfo.QuantityInfo, targetQuantityInfo); + } + + QuantityConversionFunction conversionFunction = targetQuantityInfo.GetQuantityConversionFrom(fromUnitInfo, _reduceConstants); + return _quantityConversions.GetOrAdd(conversionKey, conversionFunction); +#endif + } +} diff --git a/UnitsNet/CustomCode/QuantityConverters/FrozenQuantityConverter.cs b/UnitsNet/CustomCode/QuantityConverters/FrozenQuantityConverter.cs new file mode 100644 index 0000000000..3cdfe53a3f --- /dev/null +++ b/UnitsNet/CustomCode/QuantityConverters/FrozenQuantityConverter.cs @@ -0,0 +1,334 @@ +// 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. + +#if NET +using System.Collections.Frozen; +#else +using System.Linq; +#endif +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace UnitsNet; + +internal sealed class FrozenQuantityConverter : UnitConverter +{ +#if NET + private readonly FrozenDictionary _unitConversions; + private readonly FrozenDictionary _quantityConversions; +#else + private readonly Dictionary _unitConversions; + private readonly Dictionary _quantityConversions; +#endif + + public FrozenQuantityConverter(UnitParser unitParser, + IEnumerable quantityConversions, + IEnumerable> unitConversionFunctions, + IEnumerable> quantityConversionFunctions) + : base(unitParser, quantityConversions) + { +#if NET + _unitConversions = unitConversionFunctions.ToFrozenDictionary(); + _quantityConversions = quantityConversionFunctions.ToFrozenDictionary(); +#else + _unitConversions = unitConversionFunctions.ToDictionary(pair => pair.Key, pair => pair.Value); + _quantityConversions = quantityConversionFunctions.ToDictionary(pair => pair.Key, pair => pair.Value); +#endif + } + + public override bool TryConvertValue(QuantityValue value, TUnit fromUnit, TUnit toUnit, out QuantityValue convertedValue) + { + return TryConvertValue(value, UnitConversionKey.Create(fromUnit, toUnit), out convertedValue); + } + + public override bool TryConvertValue(QuantityValue value, UnitKey fromUnitKey, UnitKey toUnitKey, out QuantityValue convertedValue) + { + return fromUnitKey.UnitEnumType == toUnitKey.UnitEnumType + ? TryConvertValue(value, UnitConversionKey.Create(fromUnitKey, toUnitKey), out convertedValue) + : TryConvertValueFromOneQuantityToAnother(value, fromUnitKey, toUnitKey, out convertedValue); + } + + private bool TryConvertValue(QuantityValue value, UnitConversionKey conversionKey, out QuantityValue convertedValue) + { + if (conversionKey.HasSameUnits) + { + convertedValue = value; + return true; + } + + if (_unitConversions.TryGetValue(conversionKey, out ConvertValueDelegate? cachedConversion)) + { + convertedValue = cachedConversion(value); + return true; + } + + if (TryGetUnitInfo(conversionKey.FromUnitKey, out UnitInfo? fromUnitInfo) && + TryGetUnitInfo(new UnitKey(conversionKey.FromUnitKey.UnitEnumType, conversionKey.ToUnitValue), out UnitInfo? toUnitInfo)) + // TryGetUnitInfo(conversionKey.FromUnitKey with { UnitValue = conversionKey.ToUnitValue }, out UnitInfo? toUnitInfo)) + { + convertedValue = toUnitInfo.GetValueFrom(value, fromUnitInfo); + return true; + } + + convertedValue = default; + return false; + } + + private bool TryConvertValueFromOneQuantityToAnother(QuantityValue value, UnitKey fromUnitKey, UnitKey toUnitKey, out QuantityValue convertedValue) + { + var defaultConversionKey = new QuantityConversionKey(fromUnitKey, toUnitKey.UnitEnumType); + if (_quantityConversions.TryGetValue(defaultConversionKey, out QuantityConversionFunction conversionFunction)) + { + return TryConvertValue(conversionFunction.Convert(value), new UnitConversionKey(conversionFunction.TargetUnit, toUnitKey.UnitEnumValue), out convertedValue); + } + + if (TryGetUnitInfo(fromUnitKey, out UnitInfo? fromUnitInfo) && TryGetUnitInfo(toUnitKey, out UnitInfo? toUnitInfo)) + { + return TryConvertValueFromOneQuantityToAnother(value, fromUnitInfo, toUnitInfo, out convertedValue); + } + + convertedValue = default; + return false; + } + + protected override bool TryConvertValueInternal(QuantityValue value, UnitInfo fromUnitInfo, UnitInfo toUnitInfo, out QuantityValue convertedValue) + { + if (fromUnitInfo == toUnitInfo) + { + // TODO see about this: the only possible route in is from TryConvertValueByName + convertedValue = value; + return true; + } + + UnitKey fromUnitKey = fromUnitInfo.UnitKey; + UnitKey toUnitKey = toUnitInfo.UnitKey; + if (fromUnitKey.UnitEnumType == toUnitKey.UnitEnumType) + { + convertedValue = _unitConversions.TryGetValue(UnitConversionKey.Create(fromUnitKey, toUnitKey), out ConvertValueDelegate? cachedConversion) + ? cachedConversion(value) + : toUnitInfo.GetValueFrom(value, fromUnitInfo); + return true; + } + + var defaultConversionKey = new QuantityConversionKey(fromUnitKey, toUnitKey.UnitEnumType); + if (!_quantityConversions.TryGetValue(defaultConversionKey, out QuantityConversionFunction defaultConversion)) + { + return TryConvertValueFromOneQuantityToAnother(value, fromUnitInfo, toUnitInfo, out convertedValue); + } + + if (defaultConversion.TargetUnit == toUnitKey) + { + convertedValue = defaultConversion.Convert(value); + return true; + } + + QuantityValue valueInDefaultUnit = defaultConversion.Convert(value); + convertedValue = _unitConversions.TryGetValue(UnitConversionKey.Create(defaultConversion.TargetUnit, toUnitKey), out ConvertValueDelegate? toTargetUnitConversion) + ? toTargetUnitConversion(valueInDefaultUnit) + : toUnitInfo.GetValueFrom(valueInDefaultUnit, GetUnitInfo(defaultConversion.TargetUnit)); + return true; + } + + public override QuantityValue ConvertValue(QuantityValue value, TUnit fromUnit, TUnit toUnit) + { + var conversionKey = UnitConversionKey.Create(fromUnit, toUnit); + return ConvertValue(value, conversionKey); + } + + public override QuantityValue ConvertValue(QuantityValue value, UnitKey fromUnitKey, UnitKey toUnitKey) + { + return fromUnitKey.UnitEnumType == toUnitKey.UnitEnumType + ? ConvertValue(value, UnitConversionKey.Create(fromUnitKey, toUnitKey)) + : ConvertValueFromOneQuantityToAnother(value, fromUnitKey, toUnitKey); + } + + private QuantityValue ConvertValue(QuantityValue value, UnitConversionKey conversionKey) + { + if (conversionKey.HasSameUnits) + { + return value; + } + + if (_unitConversions.TryGetValue(conversionKey, out ConvertValueDelegate? cachedConversion)) + { + return cachedConversion(value); + } + + UnitInfo fromUnitInfo = GetUnitInfo(conversionKey.FromUnitKey); + UnitInfo toUnitInfo = GetUnitInfo(new UnitKey(conversionKey.FromUnitKey.UnitEnumType, conversionKey.ToUnitValue)); + // UnitInfo toUnitInfo = GetUnitInfo(conversionKey.FromUnitKey with { UnitValue = conversionKey.ToUnitValue }); + return toUnitInfo.GetValueFrom(value, fromUnitInfo); + } + + private QuantityValue ConvertValueFromOneQuantityToAnother(QuantityValue value, UnitKey fromUnitKey, UnitKey toUnitKey) + { + var defaultConversionKey = new QuantityConversionKey(fromUnitKey, toUnitKey.UnitEnumType); + return _quantityConversions.TryGetValue(defaultConversionKey, out QuantityConversionFunction defaultConversionFunction) + ? ConvertValue(defaultConversionFunction.Convert(value), new UnitConversionKey(defaultConversionFunction.TargetUnit, toUnitKey.UnitEnumValue)) + : ConvertValueFromOneQuantityToAnother(value, GetUnitInfo(fromUnitKey), GetUnitInfo(toUnitKey)); + } + + protected override QuantityValue ConvertValueInternal(QuantityValue value, UnitInfo fromUnitInfo, UnitInfo toUnitInfo) + { + if (fromUnitInfo == toUnitInfo) + { + return value; + } + + UnitKey fromUnitKey = fromUnitInfo.UnitKey; + UnitKey toUnitKey = toUnitInfo.UnitKey; + if (fromUnitKey.UnitEnumType == toUnitKey.UnitEnumType) + { + return _unitConversions.TryGetValue(UnitConversionKey.Create(fromUnitKey, toUnitKey), out ConvertValueDelegate? cachedConversion) + ? cachedConversion(value) + : toUnitInfo.GetValueFrom(value, fromUnitInfo); + } + + var defaultConversionKey = new QuantityConversionKey(fromUnitKey, toUnitInfo.QuantityInfo.UnitType); + if (!_quantityConversions.TryGetValue(defaultConversionKey, out QuantityConversionFunction defaultConversion)) + { + return ConvertValueFromOneQuantityToAnother(value, fromUnitInfo, toUnitInfo); + } + + if (defaultConversion.TargetUnit == toUnitKey) + { + return defaultConversion.Convert(value); + } + + QuantityValue valueInDefaultUnit = defaultConversion.Convert(value); + return _unitConversions.TryGetValue(UnitConversionKey.Create(defaultConversion.TargetUnit, toUnitKey), out ConvertValueDelegate? toTargetUnitConversion) + ? toTargetUnitConversion(valueInDefaultUnit) + : toUnitInfo.GetValueFrom(valueInDefaultUnit, GetUnitInfo(defaultConversion.TargetUnit)); + } + + public override ConvertValueDelegate GetConversionFunction(UnitKey fromUnitKey, UnitKey toUnitKey) + { + if (fromUnitKey == toUnitKey) + { + return value => value; + } + + if (fromUnitKey.UnitEnumType == toUnitKey.UnitEnumType) + { + return _unitConversions.TryGetValue(UnitConversionKey.Create(fromUnitKey, toUnitKey), out ConvertValueDelegate? conversionFunction) + ? conversionFunction + : GetUnitInfo(fromUnitKey).GetUnitConversionExpressionTo(GetUnitInfo(toUnitKey)); + } + + UnitInfo fromUnitInfo = GetUnitInfo(fromUnitKey); + UnitInfo toUnitInfo = GetUnitInfo(toUnitKey); + var defaultConversionKey = new QuantityConversionKey(fromUnitKey, toUnitInfo.QuantityInfo.UnitType); + if (_quantityConversions.TryGetValue(defaultConversionKey, out QuantityConversionFunction defaultConversion)) + { + if (defaultConversion.TargetUnit == toUnitKey) + { + return defaultConversion.Convert; + } + + ConvertValueDelegate conversionToTarget = + _unitConversions.TryGetValue(UnitConversionKey.Create(defaultConversion.TargetUnit, toUnitKey), out ConvertValueDelegate? conversionFunction) + ? conversionFunction + : GetUnitInfo(defaultConversion.TargetUnit).GetUnitConversionExpressionTo(toUnitInfo); + return value => conversionToTarget(defaultConversion.Convert(value)); + } + + return GetConversionFromOneQuantityToAnother(fromUnitInfo, toUnitInfo); + } + + public override bool TryGetConversionFunction(UnitKey fromUnitKey, UnitKey toUnitKey, [NotNullWhen(true)] out ConvertValueDelegate? conversionFunction) + { + if (fromUnitKey == toUnitKey) + { + conversionFunction = value => value; + return true; + } + + if (fromUnitKey.UnitEnumType == toUnitKey.UnitEnumType) + { + if (_unitConversions.TryGetValue(UnitConversionKey.Create(fromUnitKey, toUnitKey), out conversionFunction)) + { + return true; + } + + if (TryGetUnitInfo(fromUnitKey, out UnitInfo? fromUnitInfo) && TryGetUnitInfo(toUnitKey, out UnitInfo? toUnitInfo)) + { + conversionFunction = fromUnitInfo.GetUnitConversionExpressionTo(toUnitInfo); + return true; + } + } + else if (TryGetUnitInfo(fromUnitKey, out UnitInfo? fromUnitInfo) && TryGetUnitInfo(toUnitKey, out UnitInfo? toUnitInfo)) + { + var defaultConversionKey = new QuantityConversionKey(fromUnitKey, toUnitInfo.QuantityInfo.UnitType); + if (!_quantityConversions.TryGetValue(defaultConversionKey, out QuantityConversionFunction defaultConversion)) + { + return TryGetConversionFromOneQuantityToAnother(fromUnitInfo, toUnitInfo, out conversionFunction); + } + + if (defaultConversion.TargetUnit == toUnitKey) + { + conversionFunction = defaultConversion.Convert; + return true; + } + + ConvertValueDelegate conversionToTarget = + _unitConversions.TryGetValue(UnitConversionKey.Create(defaultConversion.TargetUnit, toUnitKey), out ConvertValueDelegate? conversion) + ? conversion + : GetUnitInfo(defaultConversion.TargetUnit).GetUnitConversionExpressionTo(toUnitInfo); + conversionFunction = value => conversionToTarget(defaultConversion.Convert(value)); + return true; + } + + conversionFunction = null; + return false; + } + + public override TTargetQuantity ConvertTo(QuantityValue value, TSourceUnit fromUnit, QuantityInfo targetQuantityInfo) + { + if (_quantityConversions.TryGetValue(QuantityConversionKey.Create(fromUnit), out QuantityConversionFunction conversionFunction)) + { + return targetQuantityInfo.From(conversionFunction.Convert(value), conversionFunction.TargetUnit.ToUnit()); + } + + return base.ConvertTo(value, fromUnit, targetQuantityInfo); + } + + public override IQuantity ConvertTo(QuantityValue value, UnitKey fromUnitKey, QuantityInfo targetQuantityInfo) + { + if (_quantityConversions.TryGetValue(new QuantityConversionKey(fromUnitKey, targetQuantityInfo.UnitType), + out QuantityConversionFunction conversionFunction)) + { + return targetQuantityInfo.From(conversionFunction.Convert(value), conversionFunction.TargetUnit); + } + + return base.ConvertTo(value, fromUnitKey, targetQuantityInfo); + } + + + public override bool TryConvertTo(QuantityValue value, TSourceUnit fromUnit, + QuantityInfo targetQuantityInfo, + [NotNullWhen(true)] out TTargetQuantity? convertedQuantity) + where TTargetQuantity : default + { + if (_quantityConversions.TryGetValue(QuantityConversionKey.Create(fromUnit), + out QuantityConversionFunction conversionFunction)) + { + convertedQuantity = targetQuantityInfo.From(conversionFunction.Convert(value), conversionFunction.TargetUnit.ToUnit()); + return true; + } + + return base.TryConvertTo(value, fromUnit, targetQuantityInfo, out convertedQuantity); + } + + public override bool TryConvertTo(QuantityValue value, UnitKey fromUnitKey, QuantityInfo targetQuantityInfo, + [NotNullWhen(true)] out IQuantity? convertedQuantity) + { + if (_quantityConversions.TryGetValue(new QuantityConversionKey(fromUnitKey, targetQuantityInfo.UnitType), + out QuantityConversionFunction conversionFunction)) + { + convertedQuantity = targetQuantityInfo.From(conversionFunction.Convert(value), conversionFunction.TargetUnit); + return true; + } + + return base.TryConvertTo(value, fromUnitKey, targetQuantityInfo, out convertedQuantity); + } +} diff --git a/UnitsNet/CustomCode/QuantityConverters/NoCachingConverter.cs b/UnitsNet/CustomCode/QuantityConverters/NoCachingConverter.cs new file mode 100644 index 0000000000..0961e44440 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityConverters/NoCachingConverter.cs @@ -0,0 +1,14 @@ +// 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. + +namespace UnitsNet; + +/// +public sealed class NoCachingConverter : UnitConverter +{ + /// + public NoCachingConverter(UnitParser unitParser) + : base(unitParser) + { + } +} diff --git a/UnitsNet/CustomCode/QuantityConverters/QuantityConversionFunction.cs b/UnitsNet/CustomCode/QuantityConverters/QuantityConversionFunction.cs new file mode 100644 index 0000000000..3bfe676245 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityConverters/QuantityConversionFunction.cs @@ -0,0 +1,30 @@ +// 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.Diagnostics; + +namespace UnitsNet; + +/// +/// Represents the result of a quantity conversion, including the conversion delegate and the target unit. +/// +[DebuggerDisplay("{TargetUnit.GetDebuggerDisplay(),nq}")] +internal readonly record struct QuantityConversionFunction +{ + /// + /// Initializes a new instance of the struct. + /// + /// The delegate that performs the conversion. + /// The unit to which the quantity is converted. + public QuantityConversionFunction(ConvertValueDelegate conversionFunction, UnitKey targetUnit) + { + Convert = conversionFunction; + TargetUnit = targetUnit; + } + + /// The delegate that performs the conversion. + public ConvertValueDelegate Convert { get; } + + /// The unit to which the quantity is converted. + public UnitKey TargetUnit { get; } +} diff --git a/UnitsNet/CustomCode/QuantityConverters/QuantityConversionKey.cs b/UnitsNet/CustomCode/QuantityConverters/QuantityConversionKey.cs new file mode 100644 index 0000000000..3d16edcbd3 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityConverters/QuantityConversionKey.cs @@ -0,0 +1,46 @@ +// 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 System.Diagnostics; + +namespace UnitsNet; + +/// +/// Represents the mapping-key used for converting between the units of two different quantities. +/// +[DebuggerDisplay("{FromUnit.GetDebuggerDisplay(),nq} -> {ResultType.Name,nq}")] +internal readonly record struct QuantityConversionKey +{ + /// + /// Initializes a new instance of the struct. + /// + /// The unit key representing the source unit of the conversion. + /// The type representing the target quantity of the conversion. + public QuantityConversionKey(UnitKey FromUnit, Type ResultType) + { + this.FromUnit = FromUnit; + this.ResultType = ResultType; + } + + public UnitKey FromUnit { get; } + public Type ResultType { get; } + + /// + /// Creates a new instance of using the specified source unit and target unit + /// type. + /// + /// The type of the source units, which must be a struct and an enum. + /// The type of the target units, which must be a struct and an enum. + /// The unit of the quantity to convert from. + /// + /// A new representing the conversion from to the + /// type . + /// + public static QuantityConversionKey Create(TSourceUnit fromUnit) + where TSourceUnit : struct, Enum + where TTargetUnit : struct, Enum + { + return new QuantityConversionKey(UnitKey.ForUnit(fromUnit), typeof(TTargetUnit)); + } +} diff --git a/UnitsNet/CustomCode/QuantityConverters/UnitConversionKey.cs b/UnitsNet/CustomCode/QuantityConverters/UnitConversionKey.cs new file mode 100644 index 0000000000..2c9feceb17 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityConverters/UnitConversionKey.cs @@ -0,0 +1,70 @@ +// 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 System.Runtime.CompilerServices; + +namespace UnitsNet; + +/// +/// Represents the mapping-key used for converting between the units of the same quantity. +/// +internal readonly record struct UnitConversionKey +{ + /// + /// Initializes a new instance of the struct with the specified source unit key and + /// target unit value. + /// + /// The key representing the source unit for the conversion. + /// The integer value representing the target unit for the conversion. + public UnitConversionKey(UnitKey FromUnitKey, int ToUnitValue) + { + this.FromUnitKey = FromUnitKey; + this.ToUnitValue = ToUnitValue; + } + + /// + /// Gets a value indicating whether the conversion is to the same unit. + /// + /// + /// true if the conversion is to the same unit; otherwise, false. + /// + public bool HasSameUnits + { + get => FromUnitKey.UnitEnumValue == ToUnitValue; + } + + public UnitKey FromUnitKey { get; } + public int ToUnitValue { get; } + + /// + /// Creates a new instance of using the specified units. + /// + /// The type of the units, which must be a struct and an enum. + /// The unit of the quantity to convert from. + /// The unit to convert to. + /// + /// A new representing the conversion from to + /// . + /// + public static UnitConversionKey Create(TUnit fromUnit, TUnit toUnit) + where TUnit : struct, Enum + { + return new UnitConversionKey(UnitKey.ForUnit(fromUnit), Unsafe.As(ref toUnit)); + } + + /// + /// Creates a new instance of using the specified units. + /// + /// The unit of the quantity to convert from. + /// The unit to convert to. + /// + /// A new representing the conversion from + /// to + /// . + /// + public static UnitConversionKey Create(UnitKey fromUnitKey, UnitKey toUnitKey) + { + return new UnitConversionKey(fromUnitKey, toUnitKey.UnitEnumValue); + } +} diff --git a/UnitsNet/CustomCode/QuantityInfo/Builder/IQuantityInfoBuilder.cs b/UnitsNet/CustomCode/QuantityInfo/Builder/IQuantityInfoBuilder.cs new file mode 100644 index 0000000000..5b3012652e --- /dev/null +++ b/UnitsNet/CustomCode/QuantityInfo/Builder/IQuantityInfoBuilder.cs @@ -0,0 +1,28 @@ +// 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. + +namespace UnitsNet; + +/// +/// Represents a builder interface for constructing instances of . +/// +/// +/// This interface defines a contract for creating objects, allowing for customization +/// and configuration of quantity metadata. It is primarily used in scenarios where quantity information needs to +/// be dynamically constructed or overridden. +/// +internal interface IQuantityInfoBuilder +{ + /// + /// Builds and returns an instance of . + /// + /// + /// A constructed instance containing metadata about a specific quantity. + /// + /// + /// This method is used to finalize the construction of a object, + /// encapsulating all configured properties and metadata. It is typically invoked after setting up + /// the desired configuration for a quantity. + /// + QuantityInfo Build(); +} diff --git a/UnitsNet/CustomCode/QuantityInfo/Builder/QuantitiesInfoBuilder.cs b/UnitsNet/CustomCode/QuantityInfo/Builder/QuantitiesInfoBuilder.cs new file mode 100644 index 0000000000..53232ac0f4 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityInfo/Builder/QuantitiesInfoBuilder.cs @@ -0,0 +1,106 @@ +// 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 System.Collections.Generic; + +namespace UnitsNet; + +/// +/// Represents a builder for configuring and creating custom quantity information. +/// +/// +/// This class provides methods to configure specific quantities with custom configurations +/// and to create or retrieve quantity information based on the provided configurations. +/// It is primarily used internally to manage and customize quantity information. +/// +internal sealed class QuantitiesInfoBuilder +{ + private readonly Dictionary _quantityCustomizations = new(); + + /// + /// Configures a custom quantity by associating it with a delegate that creates its custom configuration. + /// + /// + /// The type of the quantity to configure. Must implement + /// . + /// + /// The type of the unit associated with the quantity. Must be an enumeration. + /// + /// A delegate that creates and returns a custom configuration for the specified quantity. + /// + /// The current instance of to allow method chaining. + /// + /// This method is used to define custom configurations for specific quantities, enabling fine-grained control + /// over their behavior and properties. The provided delegate is invoked to generate the configuration. + /// + internal QuantitiesInfoBuilder ConfigureQuantity(Func> createCustomConfigurationDelegate) + where TQuantity : IQuantity + where TUnit : struct, Enum + { + _quantityCustomizations.Add(typeof(TQuantity), new QuantityInfoBuilder(createCustomConfigurationDelegate)); + return this; + } + + /// + /// Creates a instance based on the provided default configuration or returns the default + /// configuration + /// if no customizations are available for the specified quantity type. + /// + /// + /// The default configuration to use if no customizations are found. + /// + /// + /// A instance representing either the customized configuration or the provided default + /// configuration. + /// + /// + /// This method checks if a custom configuration exists for the quantity type specified in the + /// . + /// If a customization is found, it builds and returns the customized . + /// Otherwise, it returns the provided . + /// + public QuantityInfo CreateOrDefault(QuantityInfo defaultConfiguration) + { + return _quantityCustomizations.TryGetValue(defaultConfiguration.QuantityType, out IQuantityInfoBuilder? builder) + ? builder.Build() + : defaultConfiguration; + } + + /// + /// Creates or retrieves a instance based on the provided default + /// configuration + /// or any custom configuration previously defined for the specified quantity type. + /// + /// + /// The type of the quantity for which the is being created or retrieved. + /// + /// + /// The type of the unit associated with the quantity. Must be an enumeration. + /// + /// + /// A delegate that provides the default configuration for the + /// if no custom configuration is available. + /// + /// + /// A instance, either from a custom configuration if available, + /// or from the provided default configuration. + /// + /// + /// This method checks if a custom configuration exists for the specified quantity type. If found, it uses the custom + /// configuration to create the . Otherwise, it falls back to the + /// delegate to create the default configuration. + /// + public QuantityInfo CreateOrDefault(Func> defaultConfiguration) + where TQuantity : IQuantity + where TUnit : struct, Enum + { + if (_quantityCustomizations.TryGetValue(typeof(TQuantity), out IQuantityInfoBuilder? builder) && + builder is QuantityInfoBuilder specificBuilder) + { + return specificBuilder.Build(); + } + + return defaultConfiguration(); + } +} diff --git a/UnitsNet/CustomCode/QuantityInfo/Builder/QuantitiesSelector.cs b/UnitsNet/CustomCode/QuantityInfo/Builder/QuantitiesSelector.cs new file mode 100644 index 0000000000..3e93222643 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityInfo/Builder/QuantitiesSelector.cs @@ -0,0 +1,244 @@ +// 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 System.Collections.Generic; +using System.Linq; + +namespace UnitsNet; + +/// +/// Provides functionality to select and configure quantities for use within the UnitsNet library. +/// +/// +/// This class allows for the selection of default quantities, addition of custom quantities, and configuration of +/// specific quantities. +/// It supports lazy loading of quantities and can be used to build a collection of quantity information dynamically at +/// runtime. +/// +public sealed class QuantitiesSelector +{ + private readonly Func> _defaultQuantitiesSelection; + private IEnumerable? _additionalQuantities; + private QuantitiesInfoBuilder? _quantitiesInfoBuilder; + + internal QuantitiesSelector(Func> defaultQuantitiesSelection) + { + _defaultQuantitiesSelection = defaultQuantitiesSelection; + } + + // internal Lazy> QuantitiesSelected { get; } + + /// + /// Adds additional quantities to the current selection. + /// + /// The quantities to be added. + /// The current instance with the additional quantities included. + /// + /// This method allows for the dynamic addition of custom quantities to the existing selection of quantities. + /// + public QuantitiesSelector WithAdditionalQuantities(IEnumerable quantities) + { + _additionalQuantities = _additionalQuantities?.Concat(quantities) ?? quantities; + return this; + } + + /// + /// Configures a specific quantity with a custom configuration. + /// + /// The type of the quantity to configure. + /// The type of the unit associated with the quantity. + /// + /// A delegate that creates a custom configuration for the specified quantity. + /// + /// The current instance of to allow for method chaining. + /// + /// This method allows for the customization of a specific quantity by providing a delegate that creates + /// a custom configuration. It initializes the if it is not already initialized + /// and uses it to configure the quantity. + /// + public QuantitiesSelector Configure(Func> createCustomConfigurationDelegate) + where TQuantity : IQuantity + where TUnit : struct, Enum + { + _quantitiesInfoBuilder ??= new QuantitiesInfoBuilder(); + _quantitiesInfoBuilder.ConfigureQuantity(createCustomConfigurationDelegate); + return this; + } + + /// + /// Retrieves the selected collection of objects based on the current configuration. + /// + /// + /// This method combines the default quantities, any additional quantities, and applies custom configurations + /// if a is provided. + /// + /// + /// An of representing the selected quantities. + /// + internal IEnumerable GetQuantityInfos() + { + if (_quantitiesInfoBuilder is null && _additionalQuantities is null) + { + return _defaultQuantitiesSelection(); + } + + IEnumerable enumeration = _defaultQuantitiesSelection(); + if (_additionalQuantities is not null) + { + enumeration = enumeration.Concat(_additionalQuantities); + } + + if (_quantitiesInfoBuilder is not null) + { + enumeration = enumeration.Select(_quantitiesInfoBuilder.CreateOrDefault); + } + + return enumeration; + // return enumeration.ToList(); + } + + /// + /// Creates a quantity information instance using the provided default configuration or a custom configuration + /// if available. + /// + /// + /// The type of the quantity, which must implement . + /// + /// + /// The type of the unit, which must be a struct and an enumeration. + /// + /// + /// A delegate that provides the default configuration for creating the . + /// + /// + /// An instance of created using either the default configuration + /// or a custom configuration if available. + /// + /// + /// This method checks if a custom configuration is available through the . + /// If no custom configuration is available, it falls back to the provided default configuration. + /// + /// + /// Thrown if the is null. + /// + internal QuantityInfo CreateOrDefault(Func> defaultConfiguration) + where TQuantity : IQuantity + where TUnit : struct, Enum + { + return _quantitiesInfoBuilder is null ? defaultConfiguration() : _quantitiesInfoBuilder.CreateOrDefault(defaultConfiguration); + } +} + +// /// +// /// Provides functionality to select and configure quantities for use within the UnitsNet library. +// /// +// /// +// /// This class allows for the selection of default quantities, addition of custom quantities, and configuration of +// /// specific quantities. +// /// It supports lazy loading of quantities and can be used to build a collection of quantity information dynamically at +// /// runtime. +// /// +// public sealed class QuantitiesSelector +// { +// private readonly Func> _defaultQuantitiesSelection; +// private IEnumerable? _additionalQuantities; +// private QuantitiesInfoBuilder? _quantitiesInfoBuilder; +// +// internal QuantitiesSelector(Func> defaultQuantitiesSelection) +// { +// _defaultQuantitiesSelection = defaultQuantitiesSelection; +// QuantitiesSelected = new Lazy>(BuildSelection); +// } +// +// internal Lazy> QuantitiesSelected { get; } +// +// /// +// /// Adds additional quantities to the current selection. +// /// +// /// The quantities to be added. +// /// The current instance with the additional quantities included. +// /// +// /// This method allows for the dynamic addition of custom quantities to the existing selection of quantities. +// /// +// public QuantitiesSelector WithAdditionalQuantities(IEnumerable quantities) +// { +// _additionalQuantities = _additionalQuantities?.Concat(quantities) ?? quantities; +// return this; +// } +// +// /// +// /// Configures a specific quantity with a custom configuration. +// /// +// /// The type of the quantity to configure. +// /// The type of the unit associated with the quantity. +// /// +// /// A delegate that creates a custom configuration for the specified quantity. +// /// +// /// The current instance of to allow for method chaining. +// /// +// /// This method allows for the customization of a specific quantity by providing a delegate that creates +// /// a custom configuration. It initializes the if it is not already initialized +// /// and uses it to configure the quantity. +// /// +// public QuantitiesSelector Configure(Func> createCustomConfigurationDelegate) +// where TQuantity : IQuantity +// where TUnit : struct, Enum +// { +// _quantitiesInfoBuilder ??= new QuantitiesInfoBuilder(); +// _quantitiesInfoBuilder.ConfigureQuantity(createCustomConfigurationDelegate); +// return this; +// } +// +// private IReadOnlyCollection BuildSelection() +// { +// if (_quantitiesInfoBuilder is null && _additionalQuantities is null) +// { +// return _defaultQuantitiesSelection(); +// } +// +// IEnumerable enumeration = _defaultQuantitiesSelection(); +// if (_additionalQuantities is not null) +// { +// enumeration = enumeration.Concat(_additionalQuantities); +// } +// +// if (_quantitiesInfoBuilder is not null) +// { +// enumeration = enumeration.Select(_quantitiesInfoBuilder.CreateOrDefault); +// } +// +// return enumeration.ToList(); +// } +// +// /// +// /// Creates a quantity information instance using the provided default configuration or a custom configuration +// /// if available. +// /// +// /// +// /// The type of the quantity, which must implement . +// /// +// /// +// /// The type of the unit, which must be a struct and an enumeration. +// /// +// /// +// /// A delegate that provides the default configuration for creating the . +// /// +// /// +// /// An instance of created using either the default configuration +// /// or a custom configuration if available. +// /// +// /// +// /// This method checks if a custom configuration is available through the . +// /// If no custom configuration is available, it falls back to the provided default configuration. +// /// +// /// +// /// Thrown if the is null. +// /// +// internal QuantityInfo CreateOrDefault(Func> defaultConfiguration) +// where TQuantity : IQuantity +// where TUnit : struct, Enum +// { +// return _quantitiesInfoBuilder is null ? defaultConfiguration() : _quantitiesInfoBuilder.CreateOrDefault(defaultConfiguration); +// } +// } diff --git a/UnitsNet/CustomCode/QuantityInfo/Builder/QuantityInfoBuilder.cs b/UnitsNet/CustomCode/QuantityInfo/Builder/QuantityInfoBuilder.cs new file mode 100644 index 0000000000..2005f9a1fe --- /dev/null +++ b/UnitsNet/CustomCode/QuantityInfo/Builder/QuantityInfoBuilder.cs @@ -0,0 +1,55 @@ +// 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; + +namespace UnitsNet; + +/// +/// Represents a builder for creating instances of . +/// +/// +/// The type of the quantity being built, which must implement . +/// +/// +/// The type of the unit associated with the quantity, which must be an enumeration. +/// +/// +/// This class provides a mechanism to lazily construct a instance +/// using a factory method. It is primarily used to configure and retrieve quantity metadata. +/// +internal sealed class QuantityInfoBuilder : IQuantityInfoBuilder + where TQuantity : IQuantity + where TUnit : struct, Enum +{ + private readonly Lazy> _quantityInfo; + + /// + /// Initializes a new instance of the class. + /// + /// + /// A factory method that lazily creates an instance of . + /// + /// + /// Thrown if the parameter is null. + /// + /// + /// This constructor allows for the deferred creation of a instance, + /// enabling efficient configuration and retrieval of quantity metadata. + /// + public QuantityInfoBuilder(Func> factory) + { + _quantityInfo = new Lazy>(factory); + } + + QuantityInfo IQuantityInfoBuilder.Build() + { + return Build(); + } + + /// + public QuantityInfo Build() + { + return _quantityInfo.Value; + } +} diff --git a/UnitsNet/CustomCode/QuantityInfo/Builder/QuantityInfoBuilderExtensions.cs b/UnitsNet/CustomCode/QuantityInfo/Builder/QuantityInfoBuilderExtensions.cs new file mode 100644 index 0000000000..612e7424e9 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityInfo/Builder/QuantityInfoBuilderExtensions.cs @@ -0,0 +1,118 @@ +// 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.Linq; + +namespace UnitsNet; + +/// +/// Provides extension methods for building and configuring unit mappings within the UnitsNet library. +/// +public static class QuantityInfoBuilderExtensions +{ + /// + /// Filters the collection of unit mappings to include only the specified units. + /// + /// The type of the unit definition. + /// The type of the unit enumeration, such as . + /// The collection of unit mappings to filter, such as the ones provided by . + /// The units to include in the filtered collection. + /// An enumerable collection of unit definitions that includes only the specified units. + public static IEnumerable SelectUnits(this IEnumerable unitMappings, params IEnumerable units) + where TUnitDefinition : IUnitDefinition + where TUnit : struct, Enum + { + return unitMappings.Where(x => units.Contains(x.Value)); + } + + /// + /// Filters the collection of unit mappings to exclude the specified units. + /// + /// The type of the unit definition. + /// The type of the unit enumeration, such as . + /// The collection of unit mappings to filter, such as the ones provided by . + /// The units to exclude from the filtered collection. + /// An enumerable collection of unit definitions that excludes the specified units. + public static IEnumerable ExcludeUnits(this IEnumerable unitMappings, params IEnumerable units) + where TUnitDefinition : IUnitDefinition + where TUnit : struct, Enum + { + return unitMappings.Where(x => !units.Contains(x.Value)); + } + + /// + /// Configures a specific unit within a collection of unit mappings. + /// + /// The type of the unit enumeration. + /// + /// The collection of unit mappings to configure, such as the ones provided by . + /// The unit to configure, such as . + /// A function that defines the configuration for the specified unit. + /// An enumerable collection of unit definitions with the specified unit configured. + public static IEnumerable Configure(this IEnumerable unitMappings, TUnit unit, + Func unitConfiguration) + where TUnitDefinition : IUnitDefinition + where TUnit : struct, Enum + { + #if NET + EqualityComparer comparer = EqualityComparer.Default; + #else + UnitEqualityComparer comparer = UnitEqualityComparer.Default; + #endif + foreach (TUnitDefinition unitMapping in unitMappings) + { + if (comparer.Equals(unitMapping.Value, unit)) + { + yield return unitConfiguration(unitMapping); + } + else + { + yield return unitMapping; + } + } + } + + /// + /// Creates a new unit definition by specifying a new conversion factor from the base unit. + /// + /// The type of the unit enumeration, such as . + /// The unit definition to which the conversion factor will be added. + /// The conversion factor from the base unit to the specified unit. + /// A new instance with the specified conversion factor from the base unit. + public static UnitDefinition WithConversionFromBase(this IUnitDefinition unitDefinition, QuantityValue conversionFromBase) + where TUnit : struct, Enum + { + return new UnitDefinition(unitDefinition.Value, unitDefinition.Name, unitDefinition.PluralName, unitDefinition.BaseUnits, conversionFromBase); + } + + /// + /// Creates a new unit definition by specifying a new conversion factor to the base unit. + /// + /// The type of the unit enumeration. + /// The unit definition to which the conversion factor will be added. + /// The conversion factor to the base unit from the specified unit. + /// A new instance with the specified conversion factor to the base unit. + public static UnitDefinition WithConversionToBase(this IUnitDefinition unitDefinition, QuantityValue conversionToBase) + where TUnit : struct, Enum + { + return new UnitDefinition(unitDefinition.Value, unitDefinition.Name, unitDefinition.PluralName, unitDefinition.BaseUnits, + QuantityValue.Inverse(conversionToBase), conversionToBase); + } + + /// + /// Creates a new unit definition by specifying conversion expressions for both conversion from the base unit and + /// conversion to the base unit. + /// + /// The type of the unit enumeration. + /// The unit definition to which the conversion expressions will be added. + /// The conversion expression from the base unit to the specified unit. + /// The conversion expression from the specified unit to the base unit. + /// A new instance with the specified conversion expressions. + public static UnitDefinition WithConversionExpression(this IUnitDefinition unitDefinition, ConversionExpression conversionFromBase, + ConversionExpression conversionToBase) + where TUnit : struct, Enum + { + return new UnitDefinition(unitDefinition.Value, unitDefinition.Name, unitDefinition.PluralName, unitDefinition.BaseUnits, conversionFromBase, + conversionToBase); + } +} diff --git a/UnitsNet/CustomCode/QuantityInfo/QuantityInfoExtensions.cs b/UnitsNet/CustomCode/QuantityInfo/QuantityInfoExtensions.cs index e12ffc0226..7ec68a178e 100644 --- a/UnitsNet/CustomCode/QuantityInfo/QuantityInfoExtensions.cs +++ b/UnitsNet/CustomCode/QuantityInfo/QuantityInfoExtensions.cs @@ -1,5 +1,9 @@ -using System; +// 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 System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using UnitsNet.Units; @@ -29,19 +33,18 @@ public static IEnumerable GetQuantitiesWithBaseDimensions(this IEn /// /// Retrieves the default unit for a specified quantity and unit system. /// + /// The type of the quantity, which implements . /// The type of the unit, which is a value type and an enumeration. /// - /// The instance containing information about the + /// The instance containing information about the /// quantity. /// /// The for which the default unit is to be retrieved. /// The default unit of type for the specified quantity and unit system. /// Thrown when is null. /// Thrown when no units are found for the given . - /// - /// Length.Info.GetDefaultUnit(UnitSystem.SI) - /// - internal static TUnit GetDefaultUnit(this QuantityInfo quantityInfo, UnitSystem unitSystem) + internal static TUnit GetDefaultUnit(this QuantityInfo quantityInfo, UnitSystem unitSystem) + where TQuantity : IQuantity where TUnit : struct, Enum { if (unitSystem is null) @@ -54,9 +57,9 @@ internal static TUnit GetDefaultUnit(this QuantityInfo quantityInf return quantityInfo.BaseUnitInfo.Value; } - IEnumerable> unitInfos = quantityInfo.GetUnitInfosFor(unitSystem.BaseUnits); + IEnumerable> unitInfos = quantityInfo.GetUnitInfosFor(unitSystem.BaseUnits); - UnitInfo? firstUnitInfo = unitInfos.FirstOrDefault(); + UnitInfo? firstUnitInfo = unitInfos.FirstOrDefault(); if (firstUnitInfo == null) { throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); @@ -64,4 +67,461 @@ internal static TUnit GetDefaultUnit(this QuantityInfo quantityInf return firstUnitInfo.Value; } + + /// + /// Retrieves the default unit for a specified quantity and unit system. + /// + /// + /// The instance containing information about the + /// quantity. + /// + /// The for which the default unit is to be retrieved. + /// The default unit information for the specified quantity and unit system. + /// Thrown when is null. + /// Thrown when no units are found for the given . + internal static UnitInfo GetDefaultUnit(this QuantityInfo quantityInfo, UnitSystem unitSystem) + { + if (unitSystem is null) + { + throw new ArgumentNullException(nameof(unitSystem)); + } + + if (quantityInfo.BaseDimensions.IsDimensionless()) + { + return quantityInfo.BaseUnitInfo; + } + + IEnumerable unitInfos = quantityInfo.GetUnitInfosFor(unitSystem.BaseUnits); + + UnitInfo? firstUnitInfo = unitInfos.FirstOrDefault(); + if (firstUnitInfo == null) + { + throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); + } + + return firstUnitInfo; + } + + /// + /// Attempts to find a unit that matches the specified base units from a collection of units. + /// + /// The type of the unit information, which must implement . + /// The collection of units to search through. + /// The base units to match against. + /// + /// When this method returns, contains the unit that matches the specified base units, if found; + /// otherwise, the default value for the type of the parameter. + /// This parameter is passed uninitialized. + /// + /// true if a unit matching the specified base units is found; otherwise, false. + internal static bool TryGetUnitWithBase(this IReadOnlyList units, BaseUnits baseUnits, [NotNullWhen(true)] out TUnitInfo? matchingUnit) + where TUnitInfo : UnitInfo + { + var nbUnits = units.Count; + for (var i = 0; i < nbUnits; i++) + { + TUnitInfo unitInfo = units[i]; + if (unitInfo.BaseUnits == baseUnits) + { + matchingUnit = unitInfo; + return true; + } + } + + matchingUnit = null; + return false; + } + + /// + /// Converts a value from one unit to another unit within the same quantity. + /// + /// The target unit information to which the value will be converted. + /// The value to be converted. + /// The source unit information from which the value will be converted. + /// The converted value in the target unit. + /// + /// Since we cannot constrain the units to be of the same quantity, I think it is better to keep this overload + /// internal. + /// + internal static QuantityValue GetValueFrom(this UnitInfo toUnit, QuantityValue value, UnitInfo fromUnit) + { + if (fromUnit == toUnit) + { + return value; + } + + UnitInfo baseUnit = toUnit.QuantityInfo.BaseUnitInfo; + if (toUnit == baseUnit) + { + return fromUnit.ConversionToBase.Evaluate(value); + } + + if (fromUnit == baseUnit) + { + return toUnit.ConversionFromBase.Evaluate(value); + } + + QuantityValue valueInBase = fromUnit.ConversionToBase.Evaluate(value); + return toUnit.ConversionFromBase.Evaluate(valueInBase); + } + + /// + /// Converts a given value from a specified unit to the base unit of the quantity. + /// + /// The unit from which the value is to be converted. + /// The value to be converted. + /// The value converted to the base unit of the quantity. + internal static QuantityValue ConvertValueToBaseUnit(this UnitInfo fromUnit, QuantityValue value) + { + return fromUnit == fromUnit.QuantityInfo.BaseUnitInfo ? value : fromUnit.ConversionToBase.Evaluate(value); + } + + /// + /// Converts a value from the base unit to the specified unit. + /// + /// The unit to convert the value to. + /// The value in the base unit to be converted. + /// The converted value in the specified unit. + internal static QuantityValue ConvertValueFromBaseUnit(this UnitInfo toUnit, QuantityValue value) + { + return toUnit == toUnit.QuantityInfo.BaseUnitInfo ? value : toUnit.ConversionFromBase.Evaluate(value); + } + + /// + /// Retrieves the quantities that are connected to the specified + /// through the provided collection of instances. + /// + /// + /// The collection of instances to search for conversions. + /// + /// + /// The for which to find connected quantities. + /// + /// + /// An enumerable of instances that are connected to the specified + /// through the provided conversions. + /// + internal static IEnumerable GetConversionsFrom(this IEnumerable conversions, QuantityInfo quantityInfo) + { + foreach (QuantityConversion conversion in conversions) + { + if (conversion.LeftQuantity == quantityInfo) + { + yield return conversion.RightQuantity; + } + else if (conversion.RightQuantity == quantityInfo) + { + yield return conversion.LeftQuantity; + } + } + } + + /// + /// Attempts to retrieve the SI base unit for the specified quantity. + /// + /// The quantity information to search within. + /// + /// When this method returns, contains the SI base unit if found; otherwise, null. + /// + /// + /// true if the SI base unit is found; otherwise, false. + /// + internal static bool TryGetSIBaseUnit(this QuantityInfo quantityInfo, [NotNullWhen(true)] out UnitInfo? matchingUnitInfo) + { + if (quantityInfo.BaseDimensions.IsDimensionless() || + quantityInfo.BaseUnitInfo.BaseUnits.IsSubsetOf(UnitSystem.SI.BaseUnits)) // this should be the default case + { + matchingUnitInfo = quantityInfo.BaseUnitInfo; + return true; + } + + return quantityInfo.UnitInfos.TryGetUnitWithBase(UnitSystem.SI.BaseUnits, out matchingUnitInfo); + } + + /// + /// Attempts to convert a quantity value from a source unit to a target quantity type and unit. + /// + /// The target quantity type. + /// The target unit type. + /// The source unit information. + /// The source quantity value. + /// The target quantity information. + /// + /// When this method returns, contains the converted quantity value if the conversion succeeded, + /// or the default value of if the conversion failed. + /// + /// + /// true if the conversion succeeded; otherwise, false. + /// + internal static bool TryConvertFrom(this QuantityInfo targetQuantityInfo, + QuantityValue sourceValue, UnitInfo sourceUnit, [NotNullWhen(true)] out TTargetQuantity? result) + where TTargetQuantity : IQuantity + where TTargetUnit : struct, Enum + { + ConvertValueDelegate conversionExpression; + QuantityInfo sourceQuantityInfo = sourceUnit.QuantityInfo; + if (sourceQuantityInfo.BaseDimensions.IsInverseOf(targetQuantityInfo.BaseDimensions)) + { + conversionExpression = QuantityValue.Inverse; + } + else if (sourceQuantityInfo.BaseDimensions == targetQuantityInfo.BaseDimensions) + { + if (targetQuantityInfo.BaseDimensions.IsDimensionless()) + { + QuantityValue dimensionlessValue = sourceUnit.ConvertValueToBaseUnit(sourceValue); + result = targetQuantityInfo.From(dimensionlessValue, targetQuantityInfo.BaseUnitInfo.Value); + return true; + } + + conversionExpression = value => value; + } + else + { + result = default; + return false; + } + + UnitInfo sourceBaseUnit = sourceQuantityInfo.BaseUnitInfo; + if (sourceUnit.BaseUnits != BaseUnits.Undefined && sourceUnit.BaseUnits != sourceBaseUnit.BaseUnits) + { + if (targetQuantityInfo.UnitInfos.TryGetUnitWithBase(sourceUnit.BaseUnits, out UnitInfo? targetUnit)) + { + result = targetUnit.From(conversionExpression(sourceValue)); + return true; + } + } + + if (sourceBaseUnit.BaseUnits != BaseUnits.Undefined) + { + // attempt to convert via the base (typically SI) unit + if (targetQuantityInfo.BaseUnitInfo.BaseUnits == sourceBaseUnit.BaseUnits) + { + QuantityValue convertedValue = conversionExpression(sourceUnit.ConvertValueToBaseUnit(sourceValue)); + result = targetQuantityInfo.BaseUnitInfo.From(convertedValue); + return true; + } + + // attempt to find another unit that matches the source base + if (targetQuantityInfo.UnitInfos.TryGetUnitWithBase(sourceBaseUnit.BaseUnits, out UnitInfo? targetUnit)) + { + QuantityValue convertedValue = conversionExpression(sourceUnit.ConvertValueToBaseUnit(sourceValue)); + result = targetUnit.From(convertedValue); + return true; + } + } + + // no compatible units found with either the sourceUnit or the sourceBaseUnit: looking for intersections with any of the other units + IReadOnlyList sourceUnits = sourceQuantityInfo.UnitInfos; + var nbSourceUnits = sourceUnits.Count; + for (var i = 0; i < nbSourceUnits; i++) + { + UnitInfo otherUnit = sourceUnits[i]; + if (otherUnit.BaseUnits == BaseUnits.Undefined || + otherUnit.BaseUnits == sourceUnit.BaseUnits || + otherUnit.BaseUnits == sourceBaseUnit.BaseUnits) + { + continue; + } + + if (targetQuantityInfo.UnitInfos.TryGetUnitWithBase(otherUnit.BaseUnits, out UnitInfo? targetUnit)) + { + QuantityValue convertedValue = conversionExpression(otherUnit.GetValueFrom(sourceValue, sourceUnit)); + result = targetUnit.From(convertedValue); + return true; + } + } + + result = default; + return false; + } + + /// + /// Converts a quantity value from a source unit to a target quantity. + /// + /// The target quantity information. + /// The value of the source quantity. + /// The unit of the source quantity. + /// The converted quantity. + /// + /// Thrown when the dimensions of the source quantity are not compatible with the dimensions of the target quantity, + /// or when no compatible base units are found for the conversion. + /// + internal static TTargetQuantity ConvertFrom(this QuantityInfo targetQuantityInfo, QuantityValue sourceValue, UnitInfo sourceUnit) + where TTargetQuantity : IQuantity + where TTargetUnit : struct, Enum + { + if(targetQuantityInfo.TryConvertFrom(sourceValue, sourceUnit, out TTargetQuantity? convertedValue)) + { + return convertedValue; + } + + QuantityInfo sourceQuantityInfo = sourceUnit.QuantityInfo; + if (sourceQuantityInfo.BaseDimensions != targetQuantityInfo.BaseDimensions && + !sourceQuantityInfo.BaseDimensions.IsInverseOf(targetQuantityInfo.BaseDimensions)) + { + throw InvalidConversionException.CreateIncompatibleDimensionsException(sourceQuantityInfo, targetQuantityInfo); + } + + throw InvalidConversionException.CreateIncompatibleUnitsException(sourceUnit, targetQuantityInfo); + } + + /// + /// Attempts to convert a quantity value from one unit to another within the specified target quantity information. + /// + /// The source unit information. + /// The value in the source unit to be converted. + /// The target quantity information to which the value should be converted. + /// + /// When this method returns, contains the converted quantity if the conversion succeeded, or null if the + /// conversion failed. + /// This parameter is passed uninitialized. + /// + /// true if the conversion succeeded; otherwise, false. + internal static bool TryConvertFrom(this QuantityInfo targetQuantityInfo, QuantityValue sourceValue, + UnitInfo sourceUnit, [NotNullWhen(true)] out IQuantity? result) + { + ConvertValueDelegate conversionExpression; + QuantityInfo sourceQuantityInfo = sourceUnit.QuantityInfo; + if (sourceQuantityInfo.BaseDimensions.IsInverseOf(targetQuantityInfo.BaseDimensions)) + { + conversionExpression = QuantityValue.Inverse; + } + else if (sourceQuantityInfo.BaseDimensions == targetQuantityInfo.BaseDimensions) + { + if (targetQuantityInfo.BaseDimensions.IsDimensionless()) + { + QuantityValue dimensionlessValue = sourceUnit.ConvertValueToBaseUnit(sourceValue); + result = targetQuantityInfo.BaseUnitInfo.From(dimensionlessValue); + return true; + } + + conversionExpression = value => value; + } + else + { + result = null; + return false; + } + + UnitInfo sourceBaseUnit = sourceQuantityInfo.BaseUnitInfo; + if (sourceUnit.BaseUnits != BaseUnits.Undefined && sourceUnit.BaseUnits != sourceBaseUnit.BaseUnits) + { + if (targetQuantityInfo.UnitInfos.TryGetUnitWithBase(sourceUnit.BaseUnits, out UnitInfo? targetUnit)) + { + result = targetUnit.From(conversionExpression(sourceValue)); + return true; + } + } + + if (sourceBaseUnit.BaseUnits != BaseUnits.Undefined) + { + // attempt to convert via the base (typically SI) unit + if (targetQuantityInfo.BaseUnitInfo.BaseUnits == sourceBaseUnit.BaseUnits) + { + QuantityValue convertedValue = conversionExpression(sourceUnit.ConvertValueToBaseUnit(sourceValue)); + result = targetQuantityInfo.BaseUnitInfo.From(convertedValue); + return true; + } + + // attempt to find another unit that matches the source base + if (targetQuantityInfo.UnitInfos.TryGetUnitWithBase(sourceBaseUnit.BaseUnits, out UnitInfo? targetUnit)) + { + QuantityValue convertedValue = conversionExpression(sourceUnit.ConvertValueToBaseUnit(sourceValue)); + result = targetUnit.From(convertedValue); + return true; + } + } + + // no compatible units found with either the sourceUnit or the sourceBaseUnit: looking for intersections with any of the other units + IReadOnlyList sourceUnits = sourceQuantityInfo.UnitInfos; + var nbSourceUnits = sourceUnits.Count; + for (var i = 0; i < nbSourceUnits; i++) + { + UnitInfo otherUnit = sourceUnits[i]; + if (otherUnit.BaseUnits == BaseUnits.Undefined || + otherUnit.BaseUnits == sourceUnit.BaseUnits || + otherUnit.BaseUnits == sourceBaseUnit.BaseUnits) + { + continue; + } + + if (targetQuantityInfo.UnitInfos.TryGetUnitWithBase(otherUnit.BaseUnits, out UnitInfo? targetUnit)) + { + QuantityValue convertedValue = conversionExpression(otherUnit.GetValueFrom(sourceValue, sourceUnit)); + result = targetUnit.From(convertedValue); + return true; + } + } + + result = null; + return false; + } + + /// + /// Converts a quantity value from a source unit to a target quantity. + /// + /// The target quantity information. + /// The value of the source quantity. + /// The unit of the source quantity. + /// The converted quantity. + /// + /// Thrown when the dimensions of the source quantity are not compatible with the dimensions of the target quantity, + /// or when no compatible base units are found for the conversion. + /// + internal static IQuantity ConvertFrom(this QuantityInfo targetQuantityInfo, QuantityValue sourceValue, UnitInfo sourceUnit) + { + if(targetQuantityInfo.TryConvertFrom(sourceValue, sourceUnit, out IQuantity? convertedValue)) + { + return convertedValue; + } + + QuantityInfo sourceQuantityInfo = sourceUnit.QuantityInfo; + if (sourceQuantityInfo.BaseDimensions != targetQuantityInfo.BaseDimensions && + !sourceQuantityInfo.BaseDimensions.IsInverseOf(targetQuantityInfo.BaseDimensions)) + { + throw InvalidConversionException.CreateIncompatibleDimensionsException(sourceQuantityInfo, targetQuantityInfo); + } + + throw InvalidConversionException.CreateIncompatibleUnitsException(sourceUnit, targetQuantityInfo); + } + + internal static bool IsInverseOf(this BaseDimensions first, BaseDimensions second) + { + if (first.Amount != -second.Amount) + { + return false; + } + + if (first.Current != -second.Current) + { + return false; + } + + if (first.Length != -second.Length) + { + return false; + } + + if (first.Mass != -second.Mass) + { + return false; + } + + if (first.LuminousIntensity != -second.LuminousIntensity) + { + return false; + } + + if (first.Temperature != -second.Temperature) + { + return false; + } + + if (first.Time != -second.Time) + { + return false; + } + + return !first.IsDimensionless(); + } } diff --git a/UnitsNet/CustomCode/QuantityInfo/Units/ConversionExpression.cs b/UnitsNet/CustomCode/QuantityInfo/Units/ConversionExpression.cs new file mode 100644 index 0000000000..b8028f67c0 --- /dev/null +++ b/UnitsNet/CustomCode/QuantityInfo/Units/ConversionExpression.cs @@ -0,0 +1,395 @@ +// 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 System.Text; + +namespace UnitsNet; + +/// +/// Represents a method that converts a . +/// +/// The source value to be converted. +/// The converted . +public delegate QuantityValue ConvertValueDelegate(QuantityValue sourceValue); + +/// +/// Represents a conversion function, expressed as an equation of the form: +/// +/// f(x) = a * g(x)^n + b +/// +/// where: +/// a and b are constants of type . +/// g(x) is an optional custom function applied to the input x (of type ). +/// n is an integer exponent. +/// +/// +/// Note: In order for the equality contract to work properly, f(x) should be invertible. Irrational functions, +/// such as sqrt, should be handled with care, ensuring consistent rounding precision is used. +/// +/// For all quantities shipped with UnitsNet, g(x) defaults to x and the exponent n is either +/// 1 or -1. +/// +/// +/// Conversions from degrees to radians are currently handled using an approximation of PI to the 16th digit. +/// +/// +public readonly record struct ConversionExpression +{ + /// + /// Initializes a new instance of the struct. + /// + /// + /// The coefficient a in the conversion equation. + /// + /// + /// An optional custom function g(x) applied to the input. + /// + /// + /// The exponent n in the conversion equation. + /// + /// + /// The constant term b in the conversion equation. + /// + public ConversionExpression(QuantityValue coefficient, ConvertValueDelegate? nestedFunction = null, int exponent = 1, QuantityValue constantTerm = default) + { + Coefficient = coefficient; + Exponent = exponent; + ConstantTerm = constantTerm; + NestedFunction = nestedFunction; + } + + /// + /// Initializes a new instance of the struct with the specified + /// coefficient and constant term. + /// + /// The coefficient a in the conversion equation. + /// The constant term b in the conversion equation. + public ConversionExpression(QuantityValue coefficient, QuantityValue constantTerm) + : this(coefficient, null, 1, constantTerm) + { + } + + /// + /// Gets the coefficient a in the conversion expression. + /// + /// + /// The coefficient a of type . + /// + /// + /// This coefficient is used in the conversion function: + /// + /// f(x) = a * g(x)^n + b + /// + /// + public QuantityValue Coefficient { get; } + + /// + /// Gets an optional custom function applied to the input . + /// + /// + /// This function, if provided, is represented as g(x) in the conversion equation: + /// + /// f(x) = a * g(x)^n + b + /// + /// where a and b are constants, and n is an integer exponent. + /// If the function is not specified, g(x) defaults to x. + /// + public ConvertValueDelegate? NestedFunction { get; } + + /// + /// Gets the integer exponent n in the conversion function equation. + /// + /// + /// The exponent is used in the equation: + /// + /// f(x) = a * g(x)^n + b + /// + /// where n is the exponent applied to the optional custom function g(x). + /// + public int Exponent { get; } + + /// + /// Gets the constant term b in the conversion expression equation. + /// + /// + /// The constant term of type . + /// + /// + /// This term represents the constant offset added to the result of the conversion function. + /// + public QuantityValue ConstantTerm { get; } + + /// + /// Evaluates the conversion expression for a given input value. + /// + /// The input value to be converted. + /// The result of the conversion expression. + /// + /// The conversion expression is evaluated as: + /// + /// f(x) = a * g(x)^n + b + /// + /// where: + /// + /// + /// a is the . + /// + /// + /// + /// g(x) is the applied to the input + /// . + /// + /// + /// + /// n is the . + /// + /// + /// b is the . + /// + /// + /// If is null, g(x) defaults to . + /// + public QuantityValue Evaluate(QuantityValue value) + { + QuantityValue x = NestedFunction?.Invoke(value) ?? value; + return Exponent switch + { + 1 => Coefficient * x + ConstantTerm, + -1 => Coefficient * QuantityValue.Inverse(x) + ConstantTerm, + _ => Coefficient * QuantityValue.Pow(x, Exponent) + ConstantTerm + }; + } + + /// + /// Evaluates the current using the specified intermediate expression. + /// + /// The intermediate to be evaluated. + /// + /// A boolean value indicating whether to reduce constants during the evaluation. + /// If true, the constants in the expressions will be reduced. + /// + /// A new that represents the result of the evaluation. + /// + /// The evaluation combines the coefficients, constant terms, and exponents of the current and intermediate + /// expressions. + /// If either expression has a nested function, the resulting expression will include a nested function that combines + /// them. + /// + public ConversionExpression Evaluate(ConversionExpression intermediateExpression, bool reduceConstants = false) + { + if (NestedFunction is { } thisNestedFunction) + { + return new ConversionExpression(Coefficient, value => thisNestedFunction(intermediateExpression.Evaluate(value)), Exponent, ConstantTerm); + } + + if (reduceConstants) + { + return Exponent switch + { + 1 => new ConversionExpression(QuantityValue.Reduce(Coefficient * intermediateExpression.Coefficient), intermediateExpression.NestedFunction, + intermediateExpression.Exponent, QuantityValue.Reduce(ConstantTerm + Coefficient * intermediateExpression.ConstantTerm)), + -1 when intermediateExpression.ConstantTerm == QuantityValue.Zero => new ConversionExpression( + QuantityValue.Reduce(Coefficient * QuantityValue.Inverse(intermediateExpression.Coefficient)), intermediateExpression.NestedFunction, + -intermediateExpression.Exponent, + ConstantTerm), + _ => new ConversionExpression(Coefficient, intermediateExpression.Evaluate, Exponent, ConstantTerm) + }; + } + + return Exponent switch + { + 1 => new ConversionExpression(Coefficient * intermediateExpression.Coefficient, intermediateExpression.NestedFunction, + intermediateExpression.Exponent, ConstantTerm + Coefficient * intermediateExpression.ConstantTerm), + -1 when intermediateExpression.ConstantTerm == QuantityValue.Zero => new ConversionExpression( + Coefficient * QuantityValue.Inverse(intermediateExpression.Coefficient), intermediateExpression.NestedFunction, + -intermediateExpression.Exponent, + ConstantTerm), + _ => new ConversionExpression(Coefficient, intermediateExpression.Evaluate, Exponent, ConstantTerm) + }; + } + + /// + /// Implicitly converts a to a . + /// + /// The coefficient of type to be converted. + /// A new instance of initialized with the specified coefficient. + public static implicit operator ConversionExpression(QuantityValue coefficient) + { + return new ConversionExpression(coefficient); + } + + /// + /// Implicitly converts a to a . + /// + /// The coefficient of type to be converted. + /// A new instance of initialized with the specified coefficient. + public static implicit operator ConversionExpression(int coefficient) + { + return new ConversionExpression(coefficient); + } + + /// + /// Implicitly converts a to a . + /// + /// The coefficient of type to be converted. + /// A new instance of initialized with the specified coefficient. + public static implicit operator ConversionExpression(long coefficient) + { + return new ConversionExpression(coefficient); + } + + /// + /// Implicitly converts a to a . + /// + /// The to convert. + /// + /// A function that takes a and returns a based on the + /// conversion expression. + /// + public static implicit operator ConvertValueDelegate(ConversionExpression expression) + { + QuantityValue coefficient = expression.Coefficient; + var exponent = expression.Exponent; + ConvertValueDelegate? nestedFunction = expression.NestedFunction; + QuantityValue constantTerm = expression.ConstantTerm; + switch (exponent) + { + case 1: + { + if (nestedFunction is null) + { + if (coefficient == QuantityValue.One) + { + // scaleFunction = value => value; + return constantTerm == QuantityValue.Zero ? value => value : value => value + constantTerm; + } + + // scaleFunction = value => value * coefficient; + return constantTerm == QuantityValue.Zero + ? value => value * coefficient + : value => value * coefficient + constantTerm; + } + + if (coefficient == QuantityValue.One) + { + // scaleFunction = nestedFunction; + return constantTerm == QuantityValue.Zero + ? nestedFunction + : value => nestedFunction(value) + constantTerm; + } + + // scaleFunction = value => nestedFunction(value) * coefficient; + return constantTerm == QuantityValue.Zero + ? value => nestedFunction(value) * coefficient + : value => nestedFunction(value) * coefficient + constantTerm; + } + case -1: + { + if (nestedFunction is null) + { + if (coefficient == QuantityValue.One) + { + // scaleFunction = QuantityValue.Inverse; + return constantTerm == QuantityValue.Zero ? QuantityValue.Inverse : value => QuantityValue.Inverse(value) + constantTerm; + } + + // scaleFunction = value => QuantityValue.Inverse(value) * coefficient; + return constantTerm == QuantityValue.Zero + ? value => QuantityValue.Inverse(value) * coefficient + : value => QuantityValue.Inverse(value) * coefficient + constantTerm; + } + + if (coefficient == QuantityValue.One) + { + // scaleFunction = QuantityValue.Inverse(expression.NestedFunction); + return constantTerm == QuantityValue.Zero + ? value => QuantityValue.Inverse(nestedFunction(value)) + : value => QuantityValue.Inverse(nestedFunction(value)) + constantTerm; + } + + // scaleFunction = value => QuantityValue.Inverse(nestedFunction(value)) * coefficient; + return constantTerm == QuantityValue.Zero + ? value => QuantityValue.Inverse(nestedFunction(value)) * coefficient + : value => QuantityValue.Inverse(nestedFunction(value)) * coefficient + constantTerm; + } + default: + { + if (nestedFunction is null) + { + if (coefficient == QuantityValue.One) + { + // scaleFunction = value => QuantityValue.Pow(value, exponent); + return constantTerm == QuantityValue.Zero + ? value => QuantityValue.Pow(value, exponent) + : value => QuantityValue.Pow(value, exponent) + constantTerm; + } + + // scaleFunction = value => QuantityValue.Pow(value, exponent) * coefficient; + return constantTerm == QuantityValue.Zero + ? value => QuantityValue.Pow(value, exponent) * coefficient + : value => QuantityValue.Pow(value, exponent) * coefficient + constantTerm; + } + + if (coefficient == QuantityValue.One) + { + // scaleFunction = QuantityValue.Pow(nestedFunction, exponent); + return constantTerm == QuantityValue.Zero + ? value => QuantityValue.Pow(nestedFunction(value), exponent) + : value => QuantityValue.Pow(nestedFunction(value), exponent) + constantTerm; + } + + // scaleFunction = value => QuantityValue.Pow(nestedFunction(value), exponent) * coefficient; + return constantTerm == QuantityValue.Zero + ? value => QuantityValue.Pow(nestedFunction(value), exponent) * coefficient + : value => QuantityValue.Pow(nestedFunction(value), exponent) * coefficient + constantTerm; + } + } + } + + /// + /// Negates the given . + /// + /// The to negate. + /// A new with negated values. + public static ConversionExpression operator -(ConversionExpression expression) + { + return new ConversionExpression(-expression.Coefficient, expression.NestedFunction, expression.Exponent, -expression.ConstantTerm); + } + + #region ToString + + /// + public override string ToString() + { + var x = NestedFunction is null ? "x" : "g(x)"; + var firstTerm = Exponent switch + { + 1 => Coefficient == QuantityValue.One ? x : Coefficient == -1 ? $"-{x}" : $"{Coefficient} * {x}", + -1 => Coefficient == QuantityValue.One ? $"1 / {x}" : Coefficient == -1 ? $"-1 / {x}" : $"{Coefficient} / {x}", + _ => Coefficient == QuantityValue.One ? $"{x}^{Exponent}" : Coefficient == -1 ? $"-{x}^{Exponent}" : $"{Coefficient} * {x}^{Exponent}" + }; + + if (ConstantTerm == QuantityValue.Zero) + { + return firstTerm; + } + + return ConstantTerm > 0 ? firstTerm + " + " + ConstantTerm : firstTerm + " - " + -ConstantTerm; + } + + private bool PrintMembers(StringBuilder builder) + { + builder.Append($"Coefficient = {Coefficient}, "); + builder.Append($"Exponent = {Exponent}, "); + builder.Append($"ConstantTerm = {ConstantTerm}"); + if (NestedFunction != null) + { + builder.Append($", NestedFunction = {NestedFunction.Method.Name}"); + } + + return true; + } + + #endregion +} diff --git a/UnitsNet/CustomCode/QuantityInfo/Units/UnitDefinition.cs b/UnitsNet/CustomCode/QuantityInfo/Units/UnitDefinition.cs index 4919be5115..dfd23ad642 100644 --- a/UnitsNet/CustomCode/QuantityInfo/Units/UnitDefinition.cs +++ b/UnitsNet/CustomCode/QuantityInfo/Units/UnitDefinition.cs @@ -26,6 +26,33 @@ public UnitDefinition(TUnit value, string pluralName, BaseUnits baseUnits) /// /// Initializes a new instance of the class. /// + /// The enum value for this unit, for example . + /// The plural name of the unit, such as "Centimeters". + /// The for this unit. + /// The conversion expression from the base unit to this unit. + /// The conversion expression from this unit to the base unit. + public UnitDefinition(TUnit value, string pluralName, BaseUnits baseUnits, + ConversionExpression conversionFromBase, + ConversionExpression conversionToBase) + : this(value, value.ToString(), pluralName, baseUnits, conversionFromBase, conversionToBase) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The enum value for this unit, for example . + /// The plural name of the unit, such as "Centimeters". + /// The for this unit. + /// The conversion coefficient from the base unit to this unit. + public UnitDefinition(TUnit value, string pluralName, BaseUnits baseUnits, QuantityValue conversionFromBase) + : this(value, value.ToString(), pluralName, baseUnits, conversionFromBase) + { + } + + /// + /// Initializes a new instance of the class for the base unit. + /// /// The enum value representing the unit, for example . /// The singular name of the unit, such as "Centimeter". /// The plural name of the unit, such as "Centimeters". @@ -35,11 +62,50 @@ public UnitDefinition(TUnit value, string pluralName, BaseUnits baseUnits) /// is null. /// public UnitDefinition(TUnit value, string singularName, string pluralName, BaseUnits baseUnits) + : this(value, singularName, pluralName, baseUnits, QuantityValue.One, QuantityValue.One) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The enum value representing the unit, for example . + /// The singular name of the unit, such as "Centimeter". + /// The plural name of the unit, such as "Centimeters". + /// The associated with this unit. + /// The conversion coefficient from the base unit to this unit. + /// + /// Thrown when , , , or + /// is null. + /// + public UnitDefinition(TUnit value, string singularName, string pluralName, BaseUnits baseUnits, QuantityValue conversionFromBase) + : this(value, singularName, pluralName, baseUnits, conversionFromBase, QuantityValue.Inverse(conversionFromBase)) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The enum value representing the unit, for example . + /// The singular name of the unit, such as "Centimeter". + /// The plural name of the unit, such as "Centimeters". + /// The associated with this unit. + /// The conversion expression from the base unit to this unit. + /// The conversion expression from this unit to the base unit. + /// + /// Thrown when , , , or + /// is null. + /// + public UnitDefinition(TUnit value, string singularName, string pluralName, BaseUnits baseUnits, + ConversionExpression conversionFromBase, + ConversionExpression conversionToBase) { Value = value; Name = singularName ?? throw new ArgumentNullException(nameof(singularName)); PluralName = pluralName ?? throw new ArgumentNullException(nameof(pluralName)); BaseUnits = baseUnits ?? throw new ArgumentNullException(nameof(baseUnits)); + ConversionFromBase = conversionFromBase; + ConversionToBase = conversionToBase; } /// @@ -61,4 +127,10 @@ public UnitDefinition(TUnit value, string singularName, string pluralName, BaseU /// Gets the for this unit. /// public BaseUnits BaseUnits { get; } + + /// + public ConversionExpression ConversionFromBase { get; } + + /// + public ConversionExpression ConversionToBase { get; } } diff --git a/UnitsNet/CustomCode/QuantityParser.cs b/UnitsNet/CustomCode/QuantityParser.cs index d542a2e59f..e0af392c96 100644 --- a/UnitsNet/CustomCode/QuantityParser.cs +++ b/UnitsNet/CustomCode/QuantityParser.cs @@ -17,7 +17,7 @@ namespace UnitsNet; /// The type of unit enum that belongs to this quantity, such as for /// . /// -public delegate TQuantity QuantityFromDelegate(double value, TUnitType fromUnit) +public delegate TQuantity QuantityFromDelegate(QuantityValue value, TUnitType fromUnit) where TQuantity : IQuantity where TUnitType : struct, Enum; @@ -200,7 +200,7 @@ private TQuantity ParseWithRegex(string valueString, strin where TQuantity : IQuantity where TUnitType : struct, Enum { - var value = double.Parse(valueString, ParseNumberStyles, formatProvider); + var value = QuantityValue.Parse(valueString, ParseNumberStyles, formatProvider); TUnitType parsedUnit = _unitParser.Parse(unitString, formatProvider); return fromDelegate(value, parsedUnit); } @@ -211,7 +211,7 @@ private TQuantity ParseWithRegex(string valueString, strin /// Error parsing string. private IQuantity ParseWithRegex(string valueString, string unitString, IReadOnlyList units, IFormatProvider? formatProvider) { - var value = double.Parse(valueString, ParseNumberStyles, formatProvider); + var value = QuantityValue.Parse(valueString, ParseNumberStyles, formatProvider); UnitInfo unitInfo = _unitParser.Parse(unitString, units, formatProvider); return unitInfo.From(value); } @@ -227,7 +227,7 @@ private bool TryParseWithRegex(string? valueString, string { result = default; - if (!double.TryParse(valueString, ParseNumberStyles, formatProvider, out var value)) + if (!QuantityValue.TryParse(valueString, ParseNumberStyles, formatProvider, out QuantityValue value)) { return false; } @@ -250,7 +250,7 @@ private bool TryParseWithRegex(string? valueString, string? unitString, IReadOnl { result = null; - if (!double.TryParse(valueString, ParseNumberStyles, formatProvider, out var value)) + if (!QuantityValue.TryParse(valueString, ParseNumberStyles, formatProvider, out QuantityValue value)) { return false; } diff --git a/UnitsNet/CustomCode/UnitAbbreviationsCache.cs b/UnitsNet/CustomCode/UnitAbbreviationsCache.cs index 073cb50f03..a738c192e7 100644 --- a/UnitsNet/CustomCode/UnitAbbreviationsCache.cs +++ b/UnitsNet/CustomCode/UnitAbbreviationsCache.cs @@ -85,6 +85,30 @@ public static UnitAbbreviationsCache CreateDefault() return new UnitAbbreviationsCache(); } + /// + /// Creates an instance of that maps to the default quantities, with an option to + /// customize the selection. + /// + /// An action to configure the . + /// An instance of mapped to the default quantities. + public static UnitAbbreviationsCache CreateDefault(Action configureQuantities) + { + return Create(Quantity.DefaultProvider.Quantities, configureQuantities); + } + + /// + /// Creates an instance of the class with a specified selection of default + /// quantities + /// and an action to configure the quantities selector. + /// + /// The collection of default quantities to be used. + /// An action to configure the quantities selector. + /// A new instance of the class. + public static UnitAbbreviationsCache Create(IEnumerable defaultQuantities, Action configureQuantities) + { + return new UnitAbbreviationsCache(QuantityInfoLookup.Create(defaultQuantities, configureQuantities)); + } + #region MapUnitToAbbreviation overloads /// diff --git a/UnitsNet/CustomCode/UnitKey.cs b/UnitsNet/CustomCode/UnitKey.cs index 64079dcf24..7c02364822 100644 --- a/UnitsNet/CustomCode/UnitKey.cs +++ b/UnitsNet/CustomCode/UnitKey.cs @@ -105,7 +105,7 @@ public static UnitKey Create(Type unitType, int unitValue) if (!unitType.IsEnum) { - throw new ArgumentException($"Unit type must be an enumeration, but was {unitType.FullName}.", nameof(unitType)); + throw new ArgumentException($"Unit type must be an enumeration, but was {unitType.FullName}."); } return new UnitKey(unitType, unitValue); diff --git a/UnitsNet/CustomCode/UnitParser.cs b/UnitsNet/CustomCode/UnitParser.cs index b403d86782..37d06b5ca4 100644 --- a/UnitsNet/CustomCode/UnitParser.cs +++ b/UnitsNet/CustomCode/UnitParser.cs @@ -82,6 +82,59 @@ public static UnitParser CreateDefault() return new UnitParser(UnitAbbreviationsCache.CreateDefault()); } + /// + /// Creates an instance of with the default quantities. + /// + /// An action to configure the default quantities. + /// An instance of configured with the default quantities. + public static UnitParser CreateDefault(Action configureQuantities) + { + return new UnitParser(UnitAbbreviationsCache.CreateDefault(configureQuantities)); + } + + /// + /// Creates an instance of with the default quantities. + /// + /// An action to configure the default quantities. + /// + /// An action to configure the unit abbreviations. + /// + /// An instance of configured with the default quantities. + public static UnitParser CreateDefault(Action configureQuantities, Action configureAbbreviations) + { + var unitAbbreviationsCache = UnitAbbreviationsCache.CreateDefault(configureQuantities); + configureAbbreviations(unitAbbreviationsCache); + return new UnitParser(unitAbbreviationsCache); + } + + /// + /// Creates an instance of the class. + /// + /// A collection of default quantities to be used by the . + /// An action to configure the quantities using a . + /// A new instance of the class. + public static UnitParser Create(IEnumerable defaultQuantities, Action configureQuantities) + { + return new UnitParser(UnitAbbreviationsCache.Create(defaultQuantities, configureQuantities)); + } + + /// + /// Creates an instance of the class. + /// + /// A collection of default quantities to be used by the . + /// An action to configure the quantities using a . + /// + /// An action to configure the unit abbreviations. + /// + /// A new instance of the class. + public static UnitParser Create(IEnumerable defaultQuantities, Action configureQuantities, + Action configureAbbreviations) + { + var unitAbbreviationsCache = UnitAbbreviationsCache.Create(defaultQuantities, configureQuantities); + configureAbbreviations(unitAbbreviationsCache); + return new UnitParser(unitAbbreviationsCache); + } + /// /// Parses a unit abbreviation for a given unit enumeration type. /// Example: Parse<LengthUnit>("km") => LengthUnit.Kilometer @@ -725,7 +778,7 @@ public bool TryGetUnitFromAbbreviation([NotNullWhen(true)]string? unitAbbreviati /// An object. /// Unit abbreviation is not known. /// Multiple units found matching the given unit abbreviation. - internal IQuantity FromUnitAbbreviation(double value, string unitAbbreviation, IFormatProvider? formatProvider) + internal IQuantity FromUnitAbbreviation(QuantityValue value, string unitAbbreviation, IFormatProvider? formatProvider) { return GetUnitFromAbbreviation(unitAbbreviation, formatProvider).From(value); } diff --git a/UnitsNet/CustomCode/UnitsNetSetup.cs b/UnitsNet/CustomCode/UnitsNetSetup.cs index e524434b5d..db64138e81 100644 --- a/UnitsNet/CustomCode/UnitsNetSetup.cs +++ b/UnitsNet/CustomCode/UnitsNetSetup.cs @@ -14,32 +14,268 @@ namespace UnitsNet; /// public sealed class UnitsNetSetup { - static UnitsNetSetup() + private static readonly DefaultConfigurationBuilder ConfigurationBuilder = new(); + internal static readonly Lazy DefaultConfiguration = new(ConfigurationBuilder.Build); + + /// + /// Builder for configuring the default setup of UnitsNet, including quantities, units, unit abbreviations, and + /// conversion functions.
+ ///
+ /// This builder allows for customization of the default configuration by specifying which quantities to use, + /// adding additional quantities, and enabling or disabling the quantity converter feature.
+ ///
+ /// Once the configuration is built, it cannot be changed. + ///
+ public sealed class DefaultConfigurationBuilder { - IReadOnlyCollection quantityInfos = Quantity.DefaultProvider.Quantities; + private QuantitiesSelector? _quantitiesSelector; + + private QuantityConverterBuildOptions _quantityConverterOptions = new(); + + // TODO see about allowing eager loading + // private AbbreviationsCachingMode AbbreviationsCaching { get; set; } = AbbreviationsCachingMode.Lazy; + // TODO see about caching the regex associated with the UnitParser + // private UnitsCachingMode UnitParserCaching { get; set; } = UnitsCachingMode.Lazy; + + + /// + /// Specifies the quantities to be used in the default configuration. + /// + /// A collection of quantities to use. + /// The current instance of for method chaining. + /// Thrown if the list of quantities to use is already specified. + public DefaultConfigurationBuilder WithQuantities(IEnumerable quantities) + { + return WithQuantities(() => quantities); + } + + /// + /// Specifies the quantities to be used in the default configuration. + /// + /// A function that returns a collection of quantities to use. + /// The current instance of for method chaining. + /// Thrown if the list of quantities to use is already specified. + public DefaultConfigurationBuilder WithQuantities(Func> quantities) + { + if (_quantitiesSelector != null) + { + throw new InvalidOperationException("The list of quantities to use is already specified"); + } + + _quantitiesSelector = new QuantitiesSelector(quantities); + return this; + } + + /// + /// Specifies the quantities to be used in the default configuration and allows further configuration of these + /// quantities. + /// + /// A collection of quantities to use. + /// An action to configure the selected quantities. + /// The current instance of for method chaining. + /// Thrown if the list of quantities to use is already specified. + public DefaultConfigurationBuilder WithQuantities(IEnumerable quantities, Action configureQuantities) + { + return WithQuantities(() => quantities, configureQuantities); + } + + /// + /// Specifies the quantities to be used in the default configuration and allows further configuration of these + /// quantities. + /// + /// A collection of quantities to use. + /// An action to configure the selected quantities. + /// The current instance of for method chaining. + /// Thrown if the list of quantities to use is already specified. + public DefaultConfigurationBuilder WithQuantities(Func> quantities, Action configureQuantities) + { + if (_quantitiesSelector != null) + { + throw new InvalidOperationException("The list of quantities to use is already specified"); + } - // note: in order to support the ConvertByAbbreviation, the unit converter should require a UnitParser in the constructor - var unitConverter = UnitConverter.CreateDefault(); + _quantitiesSelector = new QuantitiesSelector(quantities); + configureQuantities(_quantitiesSelector); + return this; + } - Default = new UnitsNetSetup(quantityInfos, unitConverter); + /// + /// Appends the list of default quantities with a custom set of definitions. + /// Adds additional quantities to the default configuration. These quantities are not part of the library by default + /// and are appended to the default list of quantities. + /// + /// The quantities to add to the default configuration. + /// + /// The instance with the additional quantities + /// added. + /// + /// Thrown if the list of quantities to use is already specified. + public DefaultConfigurationBuilder WithAdditionalQuantities(IEnumerable quantities) + { + _quantitiesSelector ??= new QuantitiesSelector(() => Quantity.DefaultProvider.Quantities); + _quantitiesSelector.WithAdditionalQuantities(quantities); + return this; + } + + /// + /// Appends the list of default quantities with a custom set of definitions. + /// Adds additional quantities to the default configuration. These quantities are not part of the library by default + /// and are appended to the default list of quantities. + /// + /// The quantities to add to the default configuration. + /// An action to configure the selected quantities. + /// + /// The instance with the additional quantities + /// added. + /// + /// Thrown if the list of quantities to use is already specified. + public DefaultConfigurationBuilder WithAdditionalQuantities(IEnumerable quantities, Action configureQuantities) + { + _quantitiesSelector ??= new QuantitiesSelector(() => Quantity.DefaultProvider.Quantities); + configureQuantities(_quantitiesSelector.WithAdditionalQuantities(quantities)); + return this; + } + + /// + /// Configures a custom quantity for the default configuration. + /// + /// The type of the quantity to configure. + /// The type of the unit associated with the quantity, which must be an enumeration. + /// + /// A delegate that creates a custom configuration for the quantity. + /// + /// The current instance of for method chaining. + public DefaultConfigurationBuilder ConfigureQuantity(Func> createCustomConfigurationDelegate) + where TQuantity : IQuantity + where TUnit : struct, Enum + { + _quantitiesSelector ??= new QuantitiesSelector(() => Quantity.DefaultProvider.Quantities); + _quantitiesSelector.Configure(createCustomConfigurationDelegate); + return this; + } + + /// + /// Configures the quantity converter options for the UnitsNet setup. + /// + /// + /// The options to use for building the quantity converter, including settings for caching, + /// constants reduction, and custom quantity options. + /// + /// + /// The instance for chaining further configuration. + /// + public DefaultConfigurationBuilder WithConverterOptions(QuantityConverterBuildOptions converterBuildOptions) + { + _quantityConverterOptions = converterBuildOptions; + return this; + } + + internal QuantityInfo CreateQuantityInfoOrDefault(Func> defaultConfiguration) + where TQuantity : IQuantity + where TUnit : struct, Enum + { + return _quantitiesSelector is null ? defaultConfiguration() : _quantitiesSelector.CreateOrDefault(defaultConfiguration); + } + + internal UnitsNetSetup Build() + { + QuantityInfoLookup quantitiesLookup = _quantitiesSelector is null + ? new QuantityInfoLookup(Quantity.DefaultProvider.Quantities) + : QuantityInfoLookup.Create(_quantitiesSelector); + + var unitAbbreviations = new UnitAbbreviationsCache(quantitiesLookup); + var formatter = new QuantityFormatter(unitAbbreviations); + var unitParser = new UnitParser(unitAbbreviations); + var quantityParser = new QuantityParser(unitParser); + var unitConverter = UnitConverter.Create(unitParser, _quantityConverterOptions); + return new UnitsNetSetup(quantitiesLookup, unitAbbreviations, formatter, unitParser, quantityParser, unitConverter); + } } /// - /// Create a new UnitsNet setup with the given quantities, their units and unit conversion functions between units. + /// Initializes the default (static) quantity information, such as . + /// This method is only called by the static initializer of the generated quantities. + /// It allows for optional customizations to the default configuration. /// - /// The quantities and their units to support for unit conversions, Parse() and ToString(). - /// The unit converter instance. - public UnitsNetSetup(IEnumerable quantityInfos, UnitConverter unitConverter) + /// The type of the quantity. + /// The type of the unit, which must be a struct and an enumeration. + /// A function that returns the default configuration for the quantity info. + /// A instance configured with the provided default configuration. + /// + /// By using this method, any customizations to the default unit definitions are taken into account by the unit + /// converter, parser, formatter, the debug proxy, etc. + /// + internal static QuantityInfo CreateQuantityInfo(Func> defaultConfiguration) + where TQuantity : IQuantity + where TUnit : struct, Enum { - var quantityInfoLookup = new QuantityInfoLookup(quantityInfos); - var unitAbbreviations = new UnitAbbreviationsCache(quantityInfoLookup); - - UnitConverter = unitConverter; - UnitAbbreviations = unitAbbreviations; - Formatter = new QuantityFormatter(unitAbbreviations); - UnitParser = new UnitParser(unitAbbreviations); - QuantityParser = new QuantityParser(unitAbbreviations); - Quantities = quantityInfoLookup; + return ConfigurationBuilder.CreateQuantityInfoOrDefault(defaultConfiguration); + } + + /// + /// Configures the default setup of UnitsNet, including quantities, units, unit abbreviations, and conversion functions.
+ ///
+ /// This method returns a that allows for customization of the default configuration + /// by specifying which quantities to use, adding additional quantities, and enabling or disabling the quantity converter feature.
+ ///
+ /// Note that once the default configuration is built, it cannot be changed. + ///
+ /// + /// A instance for configuring the default setup. + /// + /// + /// Thrown if the default configuration has already been built. + /// + public static UnitsNetSetup ConfigureDefaults(Action configuration) + { + if (DefaultConfiguration.IsValueCreated) + { + throw new InvalidOperationException("You cannot change the default configuration once it is build."); + } + + configuration(ConfigurationBuilder); + + if (DefaultConfiguration.IsValueCreated) + { + throw new InvalidOperationException("You cannot change the default configuration once it is build."); + } + + return DefaultConfiguration.Value; + } + + /// + /// Creates a new instance of , independent of the configuration. + /// + /// + /// An action that configures the to set up quantities, units, unit + /// abbreviations, + /// and conversion functions. + /// + /// + /// A configured instance of . + /// + /// + /// This method allows for customization of the UnitsNet setup by specifying which quantities to use, adding additional + /// quantities, and enabling or disabling the quantity converter feature. + /// + public static UnitsNetSetup Create(Action configuration) + { + var builder = new DefaultConfigurationBuilder(); + + configuration(builder); + + return builder.Build(); + } + + private UnitsNetSetup(QuantityInfoLookup quantitiesLookup, UnitAbbreviationsCache unitAbbreviations, QuantityFormatter formatter, UnitParser unitParser, + QuantityParser quantityParser, UnitConverter unitConverter) + { + Quantities = quantitiesLookup ?? throw new ArgumentNullException(nameof(quantitiesLookup)); + UnitAbbreviations = unitAbbreviations ?? throw new ArgumentNullException(nameof(unitAbbreviations)); + Formatter = formatter ?? throw new ArgumentNullException(nameof(formatter)); + UnitParser = unitParser ?? throw new ArgumentNullException(nameof(unitParser)); + QuantityParser = quantityParser ?? throw new ArgumentNullException(nameof(quantityParser)); + UnitConverter = unitConverter ?? throw new ArgumentNullException(nameof(unitConverter)); } /// @@ -52,7 +288,7 @@ public UnitsNetSetup(IEnumerable quantityInfos, UnitConverter unit /// usages of UnitsNet in the /// current AppDomain since the typical use is via static members and not providing a setup instance. /// - public static UnitsNetSetup Default { get; } + public static UnitsNetSetup Default => DefaultConfiguration.Value; /// /// Converts between units of a quantity, such as from meters to centimeters of a given length. @@ -60,11 +296,10 @@ public UnitsNetSetup(IEnumerable quantityInfos, UnitConverter unit public UnitConverter UnitConverter { get; } /// - /// Maps unit enums to unit abbreviation strings for one or more cultures, used by ToString() and Parse() methods of - /// quantities. + /// Maps unit enums to unit abbreviation strings for one or more cultures, used by the , and the . /// public UnitAbbreviationsCache UnitAbbreviations { get; } - + /// /// Converts a quantity to string using the specified format strings and culture-specific format providers. /// diff --git a/UnitsNet/CustomCode/Value/QuantityValue.ArithmeticOperations.cs b/UnitsNet/CustomCode/Value/QuantityValue.ArithmeticOperations.cs new file mode 100644 index 0000000000..dba25cc38f --- /dev/null +++ b/UnitsNet/CustomCode/Value/QuantityValue.ArithmeticOperations.cs @@ -0,0 +1,393 @@ +using System.Numerics; + +namespace UnitsNet; + +public readonly partial struct QuantityValue +{ + /// + /// Adds two QuantityValue instances. + /// + /// The first QuantityValue. + /// The second QuantityValue. + /// The sum of the two QuantityValue instances. + public static QuantityValue operator +(QuantityValue a, QuantityValue b) + { + var numerator1 = a.Numerator; + if (numerator1.IsZero) + { + // `a` is either NaN (NaN + b == NaN) or Zero (0 + b == b) + return a.Denominator.IsZero ? a : b; + } + + var numerator2 = b.Numerator; + if (numerator2.IsZero) + { + // 'b' is either NaN (a + NaN == NaN) or Zero (a + 0 == a) + return b.Denominator.IsZero ? b : a; + } + + // both fractions are non-zero numbers + var denominator1 = a.Denominator; + var denominator2 = b.Denominator; + + if (denominator1.IsZero) + { + // `a` is (+/-) Infinity + if (!denominator2.IsZero) + { + return a; // Inf + b = Inf + } + + // adding infinities + return (numerator1.Sign + numerator2.Sign) switch + { + 2 => PositiveInfinity, + -2 => NegativeInfinity, + _ => NaN + }; + } + + if (denominator2.IsZero) + { + return b; // (+/-) Infinity + } + + // both values are non-zero + if (denominator1 == denominator2) + { + return new QuantityValue(numerator1 + numerator2, denominator1); + } + + if (denominator1.IsOne) + { + return new QuantityValue(numerator1 * denominator2 + numerator2, denominator2); + } + + if (denominator2.IsOne) + { + return new QuantityValue(numerator1 + numerator2 * denominator1, denominator1); + } + + var gcd = BigInteger.GreatestCommonDivisor(denominator1, denominator2); + if (gcd.IsOne) + { + return new QuantityValue(numerator1 * denominator2 + numerator2 * denominator1, denominator1 * denominator2); + } + + if (gcd == denominator1) + { + return new QuantityValue(denominator2 / gcd * numerator1 + numerator2, denominator2); + } + + if (gcd == denominator2) + { + return new QuantityValue(numerator1 + denominator1 / gcd * numerator2, denominator1); + } + + var thisMultiplier = denominator1 / gcd; + var otherMultiplier = denominator2 / gcd; + + var calculatedNumerator = numerator1 * otherMultiplier + numerator2 * thisMultiplier; + var leastCommonMultiple = thisMultiplier * denominator2; + + return new QuantityValue(calculatedNumerator, leastCommonMultiple); + } + + /// + /// Increments the QuantityValue by one. + /// + /// The QuantityValue to be incremented. + /// A new QuantityValue that represents the original value incremented by one. + public static QuantityValue operator ++(QuantityValue value) + { + return value + One; + } + + /// + /// Subtracts one QuantityValue from another. + /// + /// The QuantityValue to subtract from. + /// The QuantityValue to subtract. + /// The difference between the two QuantityValue instances. + public static QuantityValue operator -(QuantityValue a, QuantityValue b) + { + return a + -b; + } + + /// + /// Returns the same value for the given QuantityValue. This unary plus operator doesn't change the value. + /// + /// The QuantityValue to return. + /// The same QuantityValue that was passed in. + public static QuantityValue operator +(QuantityValue value) + { + return value; + } + + /// + /// Returns the negated value of the operand + /// + /// Value to negate + /// -v + public static QuantityValue operator -(QuantityValue v) + { + return new QuantityValue(-v.Numerator, v.Denominator); + } + + /// + /// Decrements the value of the specified QuantityValue by one. + /// + /// The QuantityValue to decrement. + /// A new QuantityValue that is the value of the input QuantityValue minus one. + public static QuantityValue operator --(QuantityValue value) + { + return value - One; + } + + /// + /// Multiplies two QuantityValue instances. + /// + /// The first QuantityValue. + /// The second QuantityValue. + /// The product of the two QuantityValue instances. + public static QuantityValue operator *(QuantityValue a, QuantityValue b) + { + // we want to skip the multiplications if we know the result is going to be 0/b or a/0 + var numerator1 = a.Numerator; + var denominator1 = a.Denominator; + if (denominator1.IsZero) + { + // `a` is NaN or Infinity + return new QuantityValue(numerator1.Sign * b.Numerator.Sign, BigInteger.Zero); + } + + var numerator2 = b.Numerator; + var denominator2 = b.Denominator; + if (denominator2.IsZero) + { + // 'b' is NaN or Infinity + return new QuantityValue(numerator1.Sign * numerator2.Sign, BigInteger.Zero); + } + + if (numerator1.IsZero || numerator2.IsZero) + { + return Zero; + } + + return new QuantityValue(MultiplyTerms(numerator1, numerator2), MultiplyTerms(denominator1, denominator2)); + } + + private static BigInteger MultiplyTerms(BigInteger a, BigInteger b) + { + if (a.IsOne) + { + return b; + } + + return b.IsOne ? a : a * b; + } + + /// + /// Divides one QuantityValue by another. + /// + /// The QuantityValue to divide. + /// The QuantityValue to divide by. + /// The quotient of the two QuantityValue instances. + public static QuantityValue operator /(QuantityValue a, QuantityValue b) + { + // we want to skip the multiplications if we know the result is going to be 0/b or a/0 + var numerator2 = b.Numerator; + var denominator2 = b.Denominator; + if (denominator2.IsZero) + { + // dividing by NaN or Infinity produces NaN or Zero + return numerator2.IsZero || a.Denominator.IsZero ? NaN : Zero; + } + + var numerator1 = a.Numerator; + var denominator1 = a.Denominator; + if (denominator1.IsZero) + { + // `a` is NaN or Infinity + return numerator1.Sign switch + { + // +/- Infinity divided by a number + 1 => numerator2.Sign < 0 ? NegativeInfinity : PositiveInfinity, + -1 => numerator2.Sign < 0 ? PositiveInfinity : NegativeInfinity, + // NaN divided by a number + _ => NaN + }; + } + + if (numerator1.IsZero) + { + return numerator2.IsZero ? NaN : Zero; + } + + if (numerator2.IsZero) + { + return new QuantityValue(numerator1.Sign, BigInteger.Zero); + } + + // adjust the signs such that the divisor is positive (prevent a negative sign in the resulting denominator) + if (numerator2.Sign == -1) + { + numerator1 = -numerator1; + numerator2 = -numerator2; + } + + // attempt to reduce the denominators + switch (denominator1.CompareTo(denominator2)) + { + case 1: + { + if (denominator2.IsOne) + { + // {123/10} / {456/1} + return new QuantityValue(numerator1, + numerator2.IsOne ? denominator1 : denominator1 * numerator2); + } + + var gcd = BigInteger.GreatestCommonDivisor(denominator1, denominator2); + if (gcd == denominator2) + { + denominator1 /= denominator2; + return new QuantityValue(numerator1, + numerator2.IsOne ? denominator1 : denominator1 * numerator2); + } + + if (!gcd.IsOne) + { + denominator1 /= gcd; + denominator2 /= gcd; + } + + var numerator = numerator1.IsOne + ? denominator2 + : numerator1 == BigInteger.MinusOne + ? -denominator2 + : numerator1 * denominator2; + + var denominator = numerator2.IsOne + ? denominator1 + : denominator1 * numerator2; + + return new QuantityValue(numerator, denominator); + } + case -1: + { + if (denominator1.IsOne) + { + // {123/1} / {456/10} + return new QuantityValue( + numerator1.IsOne ? denominator2 : numerator1 == BigInteger.MinusOne ? -denominator2 : numerator1 * denominator2, + numerator2); + } + + var gcd = BigInteger.GreatestCommonDivisor(denominator2, denominator1); + if (gcd == denominator1) + { + denominator2 /= denominator1; + return new QuantityValue( + numerator1.IsOne ? denominator2 : numerator1 == BigInteger.MinusOne ? -denominator2 : numerator1 * denominator2, + numerator2); + } + + if (!gcd.IsOne) + { + denominator1 /= gcd; + denominator2 /= gcd; + } + + var numerator = numerator1.IsOne + ? denominator2 + : numerator1 == BigInteger.MinusOne + ? -denominator2 + : numerator1 * denominator2; + + var denominator = numerator2.IsOne + ? denominator1 + : denominator1 * numerator2; + + return new QuantityValue(numerator, denominator); + } + default: + { + return new QuantityValue(numerator1, numerator2); + } + } + } + + /// + /// Returns the remainder of dividing one QuantityValue by another. + /// + /// The QuantityValue to divide. + /// The QuantityValue to divide by. + /// The remainder of the division of the two QuantityValue instances. + public static QuantityValue operator %(QuantityValue a, QuantityValue b) + { + var numerator1 = a.Numerator; + var denominator1 = a.Denominator; + var numerator2 = b.Numerator; + var denominator2 = b.Denominator; + + if (numerator2.IsZero) + { + return NaN; // x / 0 == NaN + } + + if (numerator1.IsZero) + { + return denominator1.IsZero + ? NaN // 0 / NaN == NaN + : Zero; // 0 / x == 0 (where x != 0) + } + + if (denominator1.IsZero) + { + // a/0 (infinity) + return NaN; + } + + if (denominator2.IsZero) + { + // a % infinity + return a; + } + + if (denominator1 == denominator2) + { + return new QuantityValue(numerator1 % numerator2, denominator1); + } + + var gcd = BigInteger.GreatestCommonDivisor(denominator1, denominator2); + if (gcd.IsOne) + { + return new QuantityValue( + numerator1 * denominator2 % (numerator2 * denominator1), + denominator1 * denominator2); + } + + if (gcd == denominator1) + { + return new QuantityValue(denominator2 / gcd * numerator1 % numerator2, denominator2); + } + + if (gcd == denominator2) + { + return new QuantityValue(numerator1 % (denominator1 / gcd * numerator2), denominator1); + } + + var thisMultiplier = denominator1 / gcd; + var otherMultiplier = denominator2 / gcd; + + var leastCommonMultiple = thisMultiplier * denominator2; + + var numerator = numerator1 * otherMultiplier; + var denominator = numerator2 * thisMultiplier; + + var remainder = numerator % denominator; + + return new QuantityValue(remainder, leastCommonMultiple); + } +} \ No newline at end of file diff --git a/UnitsNet/CustomCode/Value/QuantityValue.ComparisonOperations.cs b/UnitsNet/CustomCode/Value/QuantityValue.ComparisonOperations.cs new file mode 100644 index 0000000000..3c82a29647 --- /dev/null +++ b/UnitsNet/CustomCode/Value/QuantityValue.ComparisonOperations.cs @@ -0,0 +1,360 @@ +// 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.Numerics; + +namespace UnitsNet; + +public partial struct QuantityValue +{ + /// + /// Greater-than operator + /// + public static bool operator >(QuantityValue a, QuantityValue b) + { + return a.CompareTo(b) > 0 && !IsNaN(a) && !IsNaN(b); + } + + /// + /// Less-than operator + /// + public static bool operator <(QuantityValue a, QuantityValue b) + { + return a.CompareTo(b) < 0 && !IsNaN(a) && !IsNaN(b); + } + + /// + /// Greater-than-or-equal operator + /// + public static bool operator >=(QuantityValue a, QuantityValue b) + { + return a.CompareTo(b) >= 0 && !IsNaN(a) && !IsNaN(b); + } + + /// + /// Less-than-or-equal operator + /// + public static bool operator <=(QuantityValue a, QuantityValue b) + { + return a.CompareTo(b) <= 0 && !IsNaN(a) && !IsNaN(b); + } + + /// + /// Compares this QuantityValue instance to another QuantityValue instance. + /// + /// The QuantityValue to compare with this instance. + /// + /// A value indicating the relative order of the QuantityValue instances being compared. + /// Less than zero: This instance is less than the other instance. + /// Zero: This instance is equal to the other instance. + /// Greater than zero: This instance is greater than the other instance. + /// + public int CompareTo(QuantityValue other) + { + var numerator1 = Numerator; + var denominator1 = Denominator; + var numerator2 = other.Numerator; + var denominator2 = other.Denominator; + + if (denominator1 == denominator2) + { + if (!denominator1.IsZero) + { + return numerator1.CompareTo(numerator2); // finite numbers: {-1/2} < {1/2} + } + + if (numerator1.IsZero) + { + return numerator2.IsZero ? 0 : -1; // NaN and anything else + } + + if (numerator2.IsZero) + { + return 1; // other is NaN + } + + // comparing infinities + return numerator1.Sign.CompareTo(numerator2.Sign); + } + + if (denominator1.IsZero) + { + return numerator1.Sign switch + { + 1 => 1, // PositiveInfinity -> 1 + _ => -1 // NaN or NegativeInfinity -> -1 + }; + } + + if (denominator2.IsZero) + { + return numerator2.Sign switch + { + 1 => -1, // PositiveInfinity -> -1 + _ => 1 // NaN or NegativeInfinity -> 1 + }; + } + + var firstNumeratorSign = numerator1.Sign; + var secondNumeratorSign = numerator2.Sign; + + if (firstNumeratorSign != secondNumeratorSign) + { + return firstNumeratorSign.CompareTo(secondNumeratorSign); + } + + if (firstNumeratorSign == 0) + { + return 0; // both fractions are zeros + } + + // both values are non-zero fractions with different denominators + if (denominator1 < denominator2) + { + // reverse the comparison from x.CompareTo(y) to y.CompareTo(x) + return firstNumeratorSign == 1 + ? -ComparePositiveTerms(numerator2, denominator2, numerator1, denominator1) + : -CompareNegativeTerms(numerator2, denominator2, numerator1, denominator1); + } + + return firstNumeratorSign == 1 + ? ComparePositiveTerms(numerator1, denominator1, numerator2, denominator2) + : CompareNegativeTerms(numerator1, denominator1, numerator2, denominator2); + + static int ComparePositiveTerms(BigInteger numerator1, BigInteger denominator1, BigInteger numerator2, BigInteger denominator2) + { + // From here [denominator1 > denominator2 > 0] applies + + // example: {10/10} and {1/1} or {10/100} and {1/10} + if (numerator1 <= numerator2) + { + return -1; // expecting: 0 < numerator2 < numerator1 + } + + if (numerator2.IsOne) + { + if (denominator2.IsOne) + { + // {n1/d1}.CompareTo({1/1}) + return numerator1.CompareTo(denominator1); + } + + // {n1/d1}.CompareTo({1/d2}) => {(n1*d2)/d1}.CompareTo(1) => (n1*d2).CompareTo(d1) + return (numerator1 * denominator2).CompareTo(denominator1); + } + + if (denominator2.IsOne) + { + // {n1/d1}.CompareTo({n2/1}) => (n1).CompareTo((n2*d1)) + return numerator1.CompareTo(numerator2 * denominator1); + } + + /* Comparing the positive term ratios: + * {9/7} / {4/3} = {(1 + 2/7) / (1 + 1/3)} = {27/28} + * => ((1).CompareTo(1)) == 0 and ((2/7).CompareTo(1/3)) == -1 + * Given that: + * {a/b} / {c/d} = {a/b} * {d/c} = {(a*d)/(c*b)} = {a/c} * {d/b} = {a/c} / {b/d} + * we can also write: + * {9/4} / {7/3} = {(2 + 1/4) / (2 + 1/3)} = {27/28} + * => ((2).CompareTo(2)) == 0 and ((1/4).CompareTo(1/3)) == -1 + */ + + var denominatorQuotient = BigInteger.DivRem(denominator1, denominator2, out var remainderDenominators); + if (remainderDenominators.IsZero) + { + /* Example: + * {7/4} / {3/2} = + * {7/3} / {4/2} = + * {(2 + 1/3) / (2 + 0)} = + * {7/3} / 2 = {7/6} + * => (7).CompareTo(3*2) == 1 + */ + return numerator1.CompareTo(numerator2 * denominatorQuotient); + } + + var numeratorQuotient = BigInteger.DivRem(numerator1, numerator2, out var remainderNumerators); + // if the fractions are equal: numeratorQuotient should be equal to denominatorQuotient + var quotientComparison = numeratorQuotient.CompareTo(denominatorQuotient); + if (quotientComparison != 0) + { + return quotientComparison; + } + + // if the fractions are equal: {remainderNumerators / numerator2} should be equal to {remainderDenominators / denominator2} + if (remainderNumerators.IsZero) + { + /* Example: + * {6/5} / {3/2} = + * {6/3} / {5/2} = + * {2 / (2 + 1/2)} = + * {2 / (3/2)} = {4/3} + */ + return -1; // when both values are 0 the fractions are equal + } + + return (remainderNumerators * denominator2).CompareTo(remainderDenominators * numerator2); + } + + static int CompareNegativeTerms(BigInteger numerator1, BigInteger denominator1, BigInteger numerator2, BigInteger denominator2) + { + // From here [denominator1 > denominator2 > 0] applies + + // example: {-10/10} and {-1/1} or {-10/100} and {-1/10} + if (numerator1 >= numerator2) + { + return 1; // expecting: numerator1 < numerator2 < 0 + } + + if (numerator2 == BigInteger.MinusOne) + { + return denominator2.IsOne ? numerator1.CompareTo(-denominator1) : denominator1.CompareTo(numerator1 * -denominator2); + } + + if (denominator2.IsOne) + { + return numerator1.CompareTo(numerator2 * denominator1); + } + + /* Comparing the negative term ratios, example: + * {-9/7} / {-4/3} = {(-1 + -2/7) / (-1 + -1/3)} = {27/28} + * => ((-1).CompareTo(-1)) == 0 and ((-2/7).CompareTo(-1/3)) == 1 + * Given that: + * {a/b} / {c/d} = {a/b} * {d/c} = {(a*d)/(c*b)} = {a/c} * {d/b} = {a/c} / {b/d} + * we can also write: + * {-9/4} / {-7/3} = {(-2 + -1/4) / (-2 - 1/3)} = {27/28} + * => ((-2).CompareTo(-2)) == 0 and ((-1/4).CompareTo(-1/3)) == 1 + */ + var denominatorQuotient = BigInteger.DivRem(denominator1, denominator2, out var remainderDenominators); + if (remainderDenominators.IsZero) + { + // {-7/4} / {-3/2} = {(2 + 1/3) / 2} = {(7/3)/2} = {7/6} + return numerator1.CompareTo(numerator2 * denominatorQuotient); + } + + var numeratorQuotient = BigInteger.DivRem(numerator1, numerator2, out var remainderNumerators); + // if the fractions are equal: numeratorQuotient should be equal to denominatorQuotient + var quotientComparison = numeratorQuotient.CompareTo(denominatorQuotient); + if (quotientComparison != 0) + { + return -quotientComparison; + } + + // if the fractions are equal: {remainderNumerators / numerator2} should be equal to {remainderDenominators / denominator2} + if (remainderNumerators.IsZero) + { + return 1; // when both values are 0 the fractions are equal + } + + return (remainderNumerators * denominator2).CompareTo(remainderDenominators * numerator2); + } + } + + /// + /// Compares this QuantityValue instance to another object. + /// + /// The object to compare with this instance. + /// + /// A value indicating the relative order of the QuantityValue instances being compared. + /// Less than zero: This instance is less than the other instance. + /// Zero: This instance is equal to the other instance. + /// Greater than zero: This instance is greater than the other instance. + /// + public int CompareTo(object? obj) + { + return obj switch + { + null => 1, + QuantityValue other => CompareTo(other), + _ => throw new ArgumentException($"Object must be of type {nameof(QuantityValue)}") + }; + } + + /// + /// Returns the with the maximum magnitude from the two provided values. + /// + /// The first to compare. + /// The second to compare. + /// The with the maximum magnitude. + public static QuantityValue MaxMagnitude(QuantityValue x, QuantityValue y) + { + if (IsNaN(x)) + { + return x; + } + + if (IsNaN(y)) + { + return y; + } + + // note: unlike the <= operator, CompareTo with NaN returns NaN + var comparison = Abs(x).CompareTo(Abs(y)); + return comparison switch + { + 1 => x, + -1 => y, + _ => IsNegative(x) ? y : x + }; + } + + /// + /// Compares two values to compute which has the greater magnitude and returning the other value if an input is + /// NaN. + /// + /// The value to compare with . + /// The value to compare with . + /// + /// if it is greater than ; otherwise, . + /// + public static QuantityValue MaxMagnitudeNumber(QuantityValue x, QuantityValue y) + { + if (IsNaN(x)) + { + return y; + } + + if (IsNaN(y)) + { + return x; + } + + var comparison = Abs(x).CompareTo(Abs(y)); + return comparison switch + { + 1 => x, + -1 => y, + _ => IsNegative(x) ? y : x + }; + } + + /// + /// Returns the QuantityValue with the smallest magnitude from the two provided QuantityValues. + /// + /// The first QuantityValue to compare. + /// The second QuantityValue to compare. + /// The QuantityValue with the smallest magnitude. + public static QuantityValue MinMagnitude(QuantityValue x, QuantityValue y) + { + var comparison = Abs(x).CompareTo(Abs(y)); + return comparison switch + { + -1 => x, + 1 => y, + _ => IsNegative(x) ? x : y + }; + } + + /// + /// Compares two values to compute which has the lesser magnitude and returning the other value if an input is + /// NaN. + /// + /// The value to compare with . + /// The value to compare with . + /// + /// if it is less than ; otherwise, . + /// + public static QuantityValue MinMagnitudeNumber(QuantityValue x, QuantityValue y) + { + return IsNaN(x) ? y : IsNaN(y) ? x : MinMagnitude(x, y); + } +} \ No newline at end of file diff --git a/UnitsNet/CustomCode/Value/QuantityValue.ConvertFromNumber.cs b/UnitsNet/CustomCode/Value/QuantityValue.ConvertFromNumber.cs new file mode 100644 index 0000000000..d2dd2c1b53 --- /dev/null +++ b/UnitsNet/CustomCode/Value/QuantityValue.ConvertFromNumber.cs @@ -0,0 +1,521 @@ +// 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.Numerics; +#if NET +using System.Runtime.CompilerServices; +#endif + +namespace UnitsNet; + +public partial struct QuantityValue +{ + /// Implicit cast from to . + public static implicit operator QuantityValue(byte value) + { + return new QuantityValue(value, BigInteger.One); + } + + /// Implicit cast from to . + [CLSCompliant(false)] + public static implicit operator QuantityValue(sbyte value) + { + return new QuantityValue(value); + } + + /// Implicit cast from to . + public static implicit operator QuantityValue(short value) + { + return new QuantityValue(value); + } + + /// Implicit cast from to . + [CLSCompliant(false)] + public static implicit operator QuantityValue(ushort value) + { + return new QuantityValue(value); + } + + /// Implicit cast from to . + public static implicit operator QuantityValue(int value) + { + return new QuantityValue(value); + } + + /// Implicit cast from to . + [CLSCompliant(false)] + public static implicit operator QuantityValue(uint value) + { + return new QuantityValue(value); + } + + /// Implicit cast from to . + public static implicit operator QuantityValue(long value) + { + return new QuantityValue(value); + } + + /// Implicit cast from to . + [CLSCompliant(false)] + public static implicit operator QuantityValue(ulong value) + { + return new QuantityValue(value); + } + + /// Implicit cast from to . + public static implicit operator QuantityValue(float value) + { + return FromDoubleRounded(value); + } + + /// Implicit cast from to . + public static implicit operator QuantityValue(double value) + { + return FromDoubleRounded(value); + } + + /// Implicit cast from to . + public static implicit operator QuantityValue(decimal value) + { + return new QuantityValue(value); + } + + /// Implicit cast from to . + public static implicit operator QuantityValue(BigInteger value) + { + return new QuantityValue(value); + } + + /// + /// Creates a new instance of from the specified numerator and denominator. + /// + /// The numerator of the fraction representing the quantity value. + /// + /// The denominator of the fraction representing the quantity value. + /// If the denominator is negative, both the numerator and denominator are negated to ensure a canonical + /// representation. + /// + /// + /// A instance representing the fraction defined by the given numerator and denominator. + /// + public static QuantityValue FromTerms(BigInteger numerator, BigInteger denominator) + { + return denominator.Sign < 0 ? new QuantityValue(-numerator, -denominator) : new QuantityValue(numerator, denominator); + } + + /// + /// Creates a new instance of the struct with the specified number and a power of ten exponent. + /// + /// The number to multiply. + /// + /// The power of ten to adjust the value. A positive exponent multiplies the number by 10 raised to the power, + /// while a negative exponent multiplies the denominator by 10 raised to the absolute value of the power. + /// + /// + /// A new instance representing the specified value, corresponding to the scientific + /// notation: number * 10 ^ powerOfTen. + /// + /// + /// This constructor enables precise representation of values using a fraction and a power of ten, + /// corresponding to the scientific notation: number * 10 ^ powerOfTen. + /// + public static QuantityValue FromPowerOfTen(BigInteger number, int powerOfTen) + { + return new QuantityValue(number, BigInteger.One, powerOfTen); + } + + /// + /// Creates a new instance of the struct with the specified numerator, denominator, + /// and a power of ten exponent. + /// + /// The numerator of the fraction representing the value. + /// The denominator of the fraction representing the value. + /// + /// The power of ten to adjust the value. A positive exponent multiplies the numerator by 10 raised to the power, + /// while a negative exponent multiplies the denominator by 10 raised to the absolute value of the power. + /// + /// + /// A new instance representing the specified value, corresponding to the scientific + /// notation: (numerator/denominator) * 10 ^ powerOfTen. + /// + /// + /// This constructor enables precise representation of values using a fraction and a power of ten, + /// corresponding to the scientific notation: (numerator/denominator) * 10 ^ powerOfTen. + /// + public static QuantityValue FromPowerOfTen(BigInteger numerator, BigInteger denominator, int powerOfTen) + { + return denominator.Sign < 0 ? new QuantityValue(-numerator, -denominator, powerOfTen) : new QuantityValue(numerator, denominator, powerOfTen); + } + + /// + /// Converts a floating point value to a QuantityValue. The value is rounded if possible. + /// + /// The floating point value to convert. + /// + /// + /// Thrown when the number of significant digits is less than 1 or greater than 17. + /// + /// A QuantityValue representing the rounded floating point value. + /// + /// The double data type stores its values as 64-bit floating point numbers in accordance with the IEC 60559:1989 (IEEE + /// 754) standard for binary floating-point arithmetic. + /// However, the double data type cannot precisely store some numbers. For instance, 1/10, which is accurately + /// represented by .1 as a decimal fraction, is represented by .0001100110011... as a binary fraction, with the pattern + /// 0011 repeating indefinitely. + /// In such cases, the floating-point value provides an approximate representation of the number. + /// + /// This method can be used to avoid large numbers in the numerator and denominator while also making it safe to + /// use in comparison operations with other values. + /// + /// QuantityValue value = QuantityValue.FromDoubleRounded(0.1, 15); // returns {1/10}, which is exactly 0.1 + /// + /// + /// + /// + /// + /// QuantityValue qv = QuantityValue.FromDoubleRounded(0.1); + /// // Output: 1/10, which is exactly 0.1 + /// + /// + public static QuantityValue FromDoubleRounded(double value, byte nbSignificantDigits = 15) + { + if (nbSignificantDigits is < 1 or > 17) + { + throw new ArgumentOutOfRangeException(nameof(nbSignificantDigits), nbSignificantDigits, "The number of significant digits must be between 1 and 17 (inclusive)."); + } + + switch (value) + { + case 0d: + return Zero; + case double.NaN: + return NaN; + case double.PositiveInfinity: + return PositiveInfinity; + case double.NegativeInfinity: + return NegativeInfinity; + } + + // Determine the number of decimal places to keep + var magnitude = Math.Floor(Math.Log10(Math.Abs(value))); + if (magnitude > nbSignificantDigits) + { + var digitsToKeep = new BigInteger(value / Math.Pow(10, magnitude - nbSignificantDigits)); + return new QuantityValue(digitsToKeep * PowerOfTen((int)magnitude - nbSignificantDigits)); + } + + // "decimal" values + var truncatedValue = Math.Truncate(value); + var integerPart = new BigInteger(truncatedValue); + + var decimalPlaces = Math.Min(-(int)magnitude + nbSignificantDigits - 1, 308); + var scaleFactor = Math.Pow(10, decimalPlaces); + // Get the fractional part + var fractionalPart = (long)Math.Round((value - truncatedValue) * scaleFactor); + if (fractionalPart == 0) // rounded to integer + { + return new QuantityValue(integerPart); + } + + // reduce the insignificant trailing zeros from the fractional part before converting it to BigInteger + while (fractionalPart % 10 == 0) + { + fractionalPart /= 10; + decimalPlaces--; + } + + var denominator = PowerOfTen(decimalPlaces); + var numerator = integerPart.IsZero ? fractionalPart : integerPart * denominator + fractionalPart; + return new QuantityValue(numerator, denominator); + } + +#if NET7_0_OR_GREATER + + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static bool INumberBase.TryConvertFromChecked(TOther value, out QuantityValue result) + { + if (TryConvertFrom(value, out result)) + { + return true; + } + + if (typeof(TOther) == typeof(Complex)) + { + // Complex numbers with an imaginary part can't be represented as a "real number" + // so we will convert it to NaN for the floating-point types, + // since that's what Sqrt(-1) (which is `new Complex(0, 1)`) results in. + result = FromDoubleRounded(double.CreateChecked(value)); + return true; + } + + result = default; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static bool INumberBase.TryConvertFromSaturating(TOther value, out QuantityValue result) + { + if (TryConvertFrom(value, out result)) + { + return true; + } + + if (typeof(TOther) == typeof(Complex)) + { + result = FromDoubleRounded(double.CreateSaturating(value)); + return true; + } + + result = default; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static bool INumberBase.TryConvertFromTruncating(TOther value, out QuantityValue result) + { + if (TryConvertFrom(value, out result)) + { + return true; + } + + if (typeof(TOther) == typeof(Complex)) + { + result = FromDoubleRounded(double.CreateTruncating(value)); + return true; + } + + result = default; + return false; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static bool TryConvertFrom(TOther value, out QuantityValue result) where TOther : INumberBase + { + if (typeof(TOther) == typeof(decimal)) + { + var num = (decimal)(object)value; + result = num; + return true; + } + + if (typeof(TOther) == typeof(double)) + { + var num = (double)(object)value; + result = num; + return true; + } + + if (typeof(TOther) == typeof(float)) + { + var actualValue = (float)(object)value; + result = actualValue; + return true; + } + + if (typeof(TOther) == typeof(Half)) + { + var actualValue = (Half)(object)value; + result = (float)actualValue; + return true; + } + + if (typeof(TOther) == typeof(BigInteger)) + { + var num = (BigInteger)(object)value; + result = num; + return true; + } + + if (typeof(TOther) == typeof(Int128)) + { + var num = (Int128)(object)value; + result = (BigInteger)num; + return true; + } + + if (typeof(TOther) == typeof(UInt128)) + { + var num = (UInt128)(object)value; + result = (BigInteger)num; + return true; + } + + if (typeof(TOther) == typeof(long)) + { + var num = (long)(object)value; + result = num; + return true; + } + + if (typeof(TOther) == typeof(ulong)) + { + var num = (ulong)(object)value; + result = num; + return true; + } + + if (typeof(TOther) == typeof(int)) + { + long num = (int)(object)value; + result = num; + return true; + } + + if (typeof(TOther) == typeof(uint)) + { + var num = (uint)(object)value; + result = num; + return true; + } + + if (typeof(TOther) == typeof(nint)) + { + var num = (nint)(object)value; + result = num; + return true; + } + + if (typeof(TOther) == typeof(UIntPtr)) + { + var num = (UIntPtr)(object)value; + result = num; + return true; + } + + if (typeof(TOther) == typeof(short)) + { + var num = (short)(object)value; + result = (BigInteger)num; + return true; + } + + if (typeof(TOther) == typeof(ushort)) + { + var num = (ushort)(object)value; + result = (decimal)num; + return true; + } + + if (typeof(TOther) == typeof(char)) + { + var ch = (char)(object)value; + result = (decimal)ch; + return true; + } + + if (typeof(TOther) == typeof(byte)) + { + var num = (byte)(object)value; + result = num; + return true; + } + + if (typeof(TOther) == typeof(sbyte)) + { + var num = (sbyte)(object)value; + result = num; + return true; + } + + result = default; + return false; + } + + /// + /// Creates a instance from the specified value, throwing an exception if the value + /// cannot be represented within the range of . + /// + /// The type of the input value. + /// The value to convert to a . + /// A instance representing the specified value. + /// + /// Thrown if the conversion from to is not supported. + /// + /// + /// Thrown if the specified value is outside the representable range of . + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static QuantityValue CreateChecked(TOther value) where TOther : INumberBase + { + QuantityValue result; + if (typeof(TOther) == typeof(QuantityValue)) + result = (QuantityValue)(object)value; + else if (!TryConvertChecked(value, out result) && !TOther.TryConvertToChecked(value, out result)) + throw new NotSupportedException($"Cannot create a {nameof(QuantityValue)} from the given value of type {typeof(TOther)}."); + return result; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static bool TryConvertChecked(TSource source, out TTarget? result) + where TSource : INumberBase + where TTarget : INumberBase + { + return TTarget.TryConvertFromChecked(source, out result); + } + } + + /// + /// Creates a new instance of from the specified value, saturating the value if it falls + /// outside the representable range of . + /// + /// The type of the input value. + /// The value to be converted into a . + /// + /// A instance created from the specified value. If the value is outside the representable + /// range, it is saturated to the nearest representable value. + /// + /// + /// Thrown if the conversion from to is not supported. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static QuantityValue CreateSaturating(TOther value) where TOther : INumberBase + { + QuantityValue result; + if (typeof(TOther) == typeof(QuantityValue)) + result = (QuantityValue)(object)value; + else if (!TryConvertSaturating(value, out result) && !TOther.TryConvertToSaturating(value, out result)) + throw new NotSupportedException($"Cannot create a {nameof(QuantityValue)} from the given value of type {typeof(TOther)}."); + return result; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static bool TryConvertSaturating(TSource source, out TTarget? result) + where TSource : INumberBase + where TTarget : INumberBase + { + return TTarget.TryConvertFromSaturating(source, out result); + } + } + + /// + /// Creates a instance from the specified value, truncating any values that fall outside + /// the representable range of . + /// + /// The type of the input value. + /// The value to convert to a . + /// + /// A instance created from the specified value, with truncation applied if the value + /// exceeds the representable range. + /// + /// + /// Thrown if the conversion from to is not supported. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static QuantityValue CreateTruncating(TOther value) where TOther : INumberBase + { + QuantityValue result; + if (typeof(TOther) == typeof(QuantityValue)) + result = (QuantityValue)(object)value; + else if (!TryConvertTruncating(value, out result) && !TOther.TryConvertToTruncating(value, out result)) + throw new NotSupportedException($"Cannot create a {nameof(QuantityValue)} from the given value of type {typeof(TOther)}."); + return result; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + static bool TryConvertTruncating(TSource source, out TTarget? result) + where TSource : INumberBase + where TTarget : INumberBase + { + return TTarget.TryConvertFromTruncating(source, out result); + } + } +#endif +} diff --git a/UnitsNet/CustomCode/Value/QuantityValue.ConvertFromString.cs b/UnitsNet/CustomCode/Value/QuantityValue.ConvertFromString.cs new file mode 100644 index 0000000000..0fe69ffd40 --- /dev/null +++ b/UnitsNet/CustomCode/Value/QuantityValue.ConvertFromString.cs @@ -0,0 +1,1311 @@ +// 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.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Numerics; + +namespace UnitsNet; + +public partial struct QuantityValue +{ + private const NumberStyles DefaultNumberStyles = NumberStyles.Integer | NumberStyles.Number | NumberStyles.Float; + + /// + /// Parses a string representation of a quantity value into a QuantityValue object. + /// + /// The string representation of the quantity value. + /// + /// A NumberStyles value that indicates the style elements that can be present in + /// valueString. + /// + /// A QuantityValue object that represents the parsed string. + /// Thrown when the provided string argument is null. + /// + /// Thrown when the format of the provided string argument is invalid and cannot + /// be successfully parsed into a QuantityValue. + /// + public static QuantityValue Parse(string s, IFormatProvider? provider) + { + return Parse(s, DefaultNumberStyles, provider); + } + + /// + /// Parses a string representation of a quantity value into a QuantityValue object. + /// + /// The string representation of the quantity value. + /// + /// A NumberStyles value that indicates the style elements that can be present in + /// valueString. + /// + /// + /// An IFormatProvider that supplies culture-specific formatting information about + /// valueString. + /// + /// A QuantityValue object that represents the parsed string. + /// Thrown when the provided string argument is null. + /// + /// Thrown when the format of the provided string argument is invalid and cannot + /// be successfully parsed into a QuantityValue. + /// + public static QuantityValue Parse(string s, NumberStyles style, IFormatProvider? provider) + { + if (TryParse(s, style, provider, out var valueParsed)) + { + return valueParsed; + } + + throw new FormatException( + $"The format of the provided string argument '{s}' is invalid and cannot be successfully parsed into a QuantityValue."); + } + + /// + /// Tries to convert the string representation of a quantity value to its QuantityValue equivalent, and returns a value + /// that indicates whether the conversion succeeded. + /// + /// A string containing a quantity value to convert. + /// An object that supplies culture-specific formatting information about s. + /// + /// When this method returns, contains the QuantityValue equivalent to the quantity value contained in + /// s, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s parameter is null + /// or is not of the correct format. This parameter is passed uninitialized; any value originally supplied in result + /// will be overwritten. + /// + /// true if s was converted successfully; otherwise, false. + public static bool TryParse(string? s, IFormatProvider? provider, out QuantityValue result) + { + return TryParse(s, DefaultNumberStyles, provider, out result); + } + +#if NET + /// + public static QuantityValue Parse(ReadOnlySpan s, IFormatProvider? provider) + { + return Parse(s, DefaultNumberStyles, provider); + } + + /// + public static QuantityValue Parse(ReadOnlySpan s, NumberStyles style, IFormatProvider? provider) + { + if (TryParse(s, style, provider, out var quantityValue)) + { + return quantityValue; + } + + throw new FormatException( + $"The format of the provided string argument '{s}' is invalid and cannot be successfully parsed into a QuantityValue."); + } + + /// + public static bool TryParse(ReadOnlySpan s, IFormatProvider? provider, out QuantityValue result) + { + return TryParse(s, DefaultNumberStyles, provider, out result); + } + + /// + public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out QuantityValue result) + { + return TryParse(s.AsSpan(), style, provider, out result); + } + + /// + /// Attempts to parse a ReadOnlySpan of characters into a QuantityValue. + /// + /// + /// The input string to parse. The numerator and denominator must be separated by a '/' (slash) character. + /// For example, "3/4". If the string is not in this format, the parsing behavior is influenced by the + /// and parameters. + /// + /// + /// A bitwise combination of number styles permitted in the input string. This is relevant when the string + /// is not in the numerator/denominator format. For instance, allows decimal + /// points and scientific notation. + /// + /// + /// An that supplies culture-specific information used to parse the input string. + /// This is relevant when the string is not in the numerator/denominator format. For example, + /// CultureInfo.GetCultureInfo("en-US") for US English culture. + /// + /// + /// When this method returns, contains the parsed QuantityValue if the operation was successful; otherwise, + /// it contains the default value of . + /// + /// + /// true if the input string is well-formed and could be parsed into a QuantityValue; otherwise, false. + /// + /// + /// The parameter allows you to specify which number styles are allowed in the input + /// string while the parameter provides culture-specific formatting information. + /// + /// Here are some examples of how to use the + /// method: + /// + /// + /// QuantityValue.TryParse("3/4", NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), true, out var QuantityValue); + /// + /// This example parses the string "3/4" into a object with a numerator of 3 and a + /// denominator of 4. + /// + /// QuantityValue.TryParse("1.25", NumberStyles.Number, CultureInfo.GetCultureInfo("en-US"), true, out var QuantityValue); + /// + /// This example parses the string "1.25" into a object with a numerator of 5 and + /// a + /// denominator of 4. + /// + /// QuantityValue.TryParse("1,234.56", NumberStyles.Number, CultureInfo.GetCultureInfo("en-US"), false, out var QuantityValue); + /// + /// This example parses the string "1,234.56" into a object with a numerator of + /// 12345 + /// and a + /// denominator of 100. + /// + /// QuantityValue.TryParse("1.23e-2", NumberStyles.Float, CultureInfo.GetCultureInfo("en-US"), false, out var QuantityValue); + /// + /// This example parses the string "1.23e-2" into a object with a numerator of 123 + /// and + /// a + /// denominator of 10000. + /// + /// + /// + public static bool TryParse(ReadOnlySpan value, NumberStyles numberStyles, IFormatProvider? formatProvider, out QuantityValue quantityValue) + { + if (value.IsEmpty) + { + return CannotParse(out quantityValue); + } + + var numberFormatInfo = NumberFormatInfo.GetInstance(formatProvider); + + if (value.Length == 1) + { + if (!byte.TryParse(value, numberStyles, formatProvider, out var singleDigit)) + { + if (value.SequenceEqual(numberFormatInfo.PositiveInfinitySymbol)) + { + quantityValue = PositiveInfinity; + return true; + } + + if (value.SequenceEqual(numberFormatInfo.NegativeInfinitySymbol)) + { + quantityValue = NegativeInfinity; + return true; + } + + if (value.SequenceEqual(numberFormatInfo.NaNSymbol)) + { + quantityValue = NaN; + return true; + } + + return CannotParse(out quantityValue); + } + + quantityValue = singleDigit; + return true; + } + + // TODO see if we want to support this +#if FRACTION_PARSING_ENABLED + var ranges = new Span(new Range[2]); + var nbRangesFilled = value.Split(ranges, '/'); + + if (nbRangesFilled == 2) + { + var numeratorValue = value[ranges[0]]; + var denominatorValue = value[ranges[1]]; + + var withoutDecimalPoint = numberStyles & ~NumberStyles.AllowDecimalPoint; + if (!BigInteger.TryParse( + numeratorValue, + withoutDecimalPoint, + formatProvider, + out var numerator) + || !BigInteger.TryParse( + denominatorValue, + withoutDecimalPoint, + formatProvider, + out var denominator)) + { + return CannotParse(out quantityValue); + } + + quantityValue = FromTerms(numerator, denominator); + return true; + } +#endif + + // parsing a number using to the selected NumberStyles: e.g. " $ 12345.1234321e-4- " should result in -1.23451234321 with NumberStyles.Any + // check for any of the special symbols (these cannot be combined with anything else) + if (value.SequenceEqual(numberFormatInfo.NaNSymbol.AsSpan())) + { + quantityValue = NaN; + return true; + } + + if (value.SequenceEqual(numberFormatInfo.PositiveInfinitySymbol.AsSpan())) + { + quantityValue = PositiveInfinity; + return true; + } + + if (value.SequenceEqual(numberFormatInfo.NegativeInfinitySymbol.AsSpan())) + { + quantityValue = NegativeInfinity; + return true; + } + + var currencyAllowed = (numberStyles & NumberStyles.AllowCurrencySymbol) != 0; + // there "special" rules regarding the white-spaces after a leading currency symbol is detected + var currencyDetected = false; + ReadOnlySpan currencySymbol; + if (currencyAllowed) + { + currencySymbol = numberFormatInfo.CurrencySymbol.AsSpan(); + if (currencySymbol.IsEmpty) + { + currencyAllowed = false; + numberStyles &= ~NumberStyles.AllowCurrencySymbol; // no currency symbol available + } + } + else + { + currencySymbol = []; + } + + // note: decimal.TryParse relies on the CurrencySymbol (when currency is detected) + var decimalsAllowed = (numberStyles & NumberStyles.AllowDecimalPoint) != 0; + var decimalSeparator = decimalsAllowed ? numberFormatInfo.NumberDecimalSeparator.AsSpan() : []; + + var startIndex = 0; + var endIndex = value.Length; + var isNegative = false; + + // examine the leading characters + do + { + var character = value[startIndex]; + if (char.IsDigit(character)) + { + break; + } + + if (char.IsWhiteSpace(character)) + { + if ((numberStyles & NumberStyles.AllowLeadingWhite) == 0) + { + return CannotParse(out quantityValue); + } + + startIndex++; + continue; + } + + if (character == '(') + { + if ((numberStyles & NumberStyles.AllowParentheses) == 0) + { + return CannotParse(out quantityValue); // not allowed + } + + if (startIndex == endIndex - 1) + { + return CannotParse(out quantityValue); // not enough characters + } + + startIndex++; // consume the current character + isNegative = true; // the closing parenthesis will be validated in the backwards iteration + + if (currencyDetected) + { + // any number of white-spaces are allowed following a leading currency symbol (but no other signs) + numberStyles &= ~(NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowHexSpecifier); + } + else if (currencyAllowed && value[startIndex..].StartsWith(currencySymbol)) + { + // there can be no more currency symbols but there could be more white-spaces (we skip and continue) + currencyDetected = true; + startIndex += currencySymbol.Length; + numberStyles &= ~(NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowCurrencySymbol | + NumberStyles.AllowHexSpecifier); + } + else + { + // if next character is a white space the format should be rejected + numberStyles &= ~(NumberStyles.AllowLeadingWhite | + NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowHexSpecifier); + break; + } + + continue; + } + + if ((numberStyles & NumberStyles.AllowLeadingSign) != 0) + { + if (numberFormatInfo.NegativeSign.AsSpan() is { IsEmpty: false } negativeSign && value[startIndex..].StartsWith(negativeSign)) + { + isNegative = true; + startIndex += negativeSign.Length; + if (currencyDetected) + { + // any number of white-spaces are allowed following a leading currency symbol (but no other signs) + numberStyles &= ~(NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowParentheses | + NumberStyles.AllowHexSpecifier); + } + else if (currencyAllowed && value[startIndex..].StartsWith(currencySymbol)) + { + // there can be no more currency symbols but there could be more white-spaces (we skip and continue) + currencyDetected = true; + startIndex += currencySymbol.Length; + numberStyles &= ~(NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowParentheses | + NumberStyles.AllowCurrencySymbol | + NumberStyles.AllowHexSpecifier); + } + else + { + // if next character is a white space the format should be rejected + numberStyles &= ~(NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowParentheses | + NumberStyles.AllowLeadingWhite | + NumberStyles.AllowHexSpecifier); + break; + } + + continue; + } + + if (numberFormatInfo.PositiveSign.AsSpan() is { IsEmpty: false } positiveSign && value[startIndex..].StartsWith(positiveSign)) + { + isNegative = false; + startIndex += positiveSign.Length; + if (currencyDetected) + { + // any number of white-spaces are allowed following a leading currency symbol (but no other signs) + numberStyles &= ~(NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowParentheses | + NumberStyles.AllowHexSpecifier); + } + else if (currencyAllowed && value[startIndex..].StartsWith(currencySymbol)) + { + // there can be no more currency symbols but there could be more white-spaces (we skip and continue) + currencyDetected = true; + startIndex += currencySymbol.Length; + numberStyles &= ~(NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowParentheses | + NumberStyles.AllowCurrencySymbol | + NumberStyles.AllowHexSpecifier); + } + else + { + // if next character is a white space the format should be rejected + numberStyles &= ~(NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowParentheses | + NumberStyles.AllowLeadingWhite | + NumberStyles.AllowHexSpecifier); + break; + } + + continue; + } + } + + if (currencyAllowed && !currencyDetected && value[startIndex..].StartsWith(currencySymbol)) + { + // there can be no more currency symbols but there could be more white-spaces (we skip and continue) + currencyDetected = true; + numberStyles &= ~NumberStyles.AllowCurrencySymbol; + startIndex += currencySymbol.Length; + continue; + } + + if (decimalsAllowed && value[startIndex..].StartsWith(decimalSeparator)) + { + break; // decimal string with no leading zeros + } + + // this is either an expected hex string or an invalid format + return (numberStyles & NumberStyles.AllowHexSpecifier) != 0 + ? TryParseInteger(value[startIndex..endIndex], numberStyles & ~NumberStyles.AllowTrailingSign, + formatProvider, isNegative, out quantityValue) + : CannotParse(out quantityValue); // unexpected character + } while (startIndex < endIndex); + + if (startIndex >= endIndex) + { + return CannotParse(out quantityValue); + } + + if (isNegative) + { + numberStyles &= ~(NumberStyles.AllowLeadingWhite | + NumberStyles.AllowLeadingSign); + } + else + { + numberStyles &= ~(NumberStyles.AllowLeadingWhite | + NumberStyles.AllowLeadingSign | + NumberStyles.AllowParentheses); + } + + // examine the trailing characters + do + { + var character = value[endIndex - 1]; + if (char.IsDigit(character)) + { + break; + } + + if (char.IsWhiteSpace(character)) + { + if ((numberStyles & NumberStyles.AllowTrailingWhite) == 0) + { + return CannotParse(out quantityValue); + } + + endIndex--; + continue; + } + + if (character == ')') + { + if ((numberStyles & NumberStyles.AllowParentheses) == 0) + { + return CannotParse(out quantityValue); // not allowed + } + + numberStyles &= ~(NumberStyles.AllowParentheses | NumberStyles.AllowCurrencySymbol); + endIndex--; + continue; + } + + if ((numberStyles & NumberStyles.AllowTrailingSign) != 0) + { + if (numberFormatInfo.NegativeSign.AsSpan() is { IsEmpty: false } negativeSign && value[..endIndex].EndsWith(negativeSign)) + { + isNegative = true; + numberStyles &= ~(NumberStyles.AllowTrailingSign | NumberStyles.AllowHexSpecifier); + endIndex -= negativeSign.Length; + continue; + } + + if (numberFormatInfo.PositiveSign.AsSpan() is { IsEmpty: false } positiveSign && value[..endIndex].EndsWith(positiveSign)) + { + isNegative = false; + numberStyles &= ~(NumberStyles.AllowTrailingSign | NumberStyles.AllowHexSpecifier); + endIndex -= positiveSign.Length; + continue; + } + } + + if (currencyAllowed && !currencyDetected && value[..endIndex].EndsWith(currencySymbol)) + { + // there can be no more currency symbols but there could be more white-spaces (we skip and continue) + currencyDetected = true; + numberStyles &= ~NumberStyles.AllowCurrencySymbol; + endIndex -= currencySymbol.Length; + continue; + } + + if (decimalsAllowed && value[..endIndex].EndsWith(decimalSeparator)) + { + break; + } + + // this is either an expected hex string or an invalid format + return (numberStyles & NumberStyles.AllowHexSpecifier) != 0 + ? TryParseInteger(value[startIndex..endIndex], numberStyles & ~NumberStyles.AllowTrailingSign, + formatProvider, isNegative, out quantityValue) + : CannotParse(out quantityValue); // unexpected character + } while (startIndex < endIndex); + + if (startIndex >= endIndex) + { + return CannotParse(out quantityValue); // not enough characters + } + + if (isNegative && (numberStyles & NumberStyles.AllowParentheses) != 0) + { + return CannotParse(out quantityValue); // failed to find a closing parentheses + } + + numberStyles &= ~(NumberStyles.AllowTrailingWhite | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowCurrencySymbol); + // at this point value[startIndex, endIndex] should correspond to the number without the sign (or the format is invalid) + var unsignedValue = value[startIndex..endIndex]; + + if (unsignedValue.Length == 1) + { + // this can only be a single digit (integer) + return TryParseInteger(unsignedValue, numberStyles, formatProvider, isNegative, out quantityValue); + } + + if ((numberStyles & NumberStyles.AllowExponent) != 0) + { + return TryParseWithExponent(unsignedValue, numberStyles, numberFormatInfo, isNegative, out quantityValue); + } + + return decimalsAllowed + ? TryParseDecimalNumber(unsignedValue, numberStyles, numberFormatInfo, isNegative, out quantityValue) + : TryParseInteger(unsignedValue, numberStyles, formatProvider, isNegative, out quantityValue); + } + + private static bool TryParseWithExponent(ReadOnlySpan value, NumberStyles parseNumberStyles, + NumberFormatInfo numberFormatInfo, bool isNegative, out QuantityValue quantityValue) + { + // 1. try to find the exponent character (extracting the left and right sides) + parseNumberStyles &= ~NumberStyles.AllowExponent; + if (!TrySplitAny(value, ['E', 'e'], out ReadOnlySpan coefficientSpan, out ReadOnlySpan exponentSpan)) + { + // no exponent found + return (parseNumberStyles & NumberStyles.AllowDecimalPoint) != 0 + ? TryParseDecimalNumber(value, parseNumberStyles, numberFormatInfo, isNegative, out quantityValue) + : TryParseInteger(value, parseNumberStyles, numberFormatInfo, isNegative, out quantityValue); + } + + // 2. try to parse the exponent (w.r.t. the scientific notation format) + if (!int.TryParse(exponentSpan, NumberStyles.AllowLeadingSign | NumberStyles.Integer, numberFormatInfo, + out var exponent)) + { + return CannotParse(out quantityValue); + } + + // 3. try to parse the coefficient (w.r.t. the decimal separator allowance) + if (coefficientSpan.Length == 1 || (parseNumberStyles & NumberStyles.AllowDecimalPoint) == 0) + { + if (!TryParseInteger(coefficientSpan, parseNumberStyles, numberFormatInfo, isNegative, out quantityValue)) + { + return false; + } + } + else + { + if (!TryParseDecimalNumber(coefficientSpan, parseNumberStyles, numberFormatInfo, isNegative, out quantityValue)) + { + return false; + } + } + + // 4. multiply the coefficient by 10 to the power of the exponent + quantityValue = new QuantityValue(quantityValue.Numerator, quantityValue.Denominator, exponent); + return true; + } + + private static bool TryParseDecimalNumber(ReadOnlySpan value, NumberStyles parseNumberStyles, + NumberFormatInfo numberFormatInfo, bool isNegative, out QuantityValue quantityValue) + { + // 1. try to find the decimal separator (extracting the left and right sides) + if (!TrySplit(value, numberFormatInfo.NumberDecimalSeparator, out ReadOnlySpan integerSpan, out ReadOnlySpan fractionalSpan)) + { + return TryParseInteger(value, parseNumberStyles, numberFormatInfo, isNegative, out quantityValue); + } + + // 2. validate the format of the string after the radix + if (fractionalSpan.IsEmpty) + { + // after excluding the sign, the input was reduced to just an integer part (e.g. "1 234.") + return TryParseInteger(integerSpan, parseNumberStyles, numberFormatInfo, isNegative, out quantityValue); + } + + if ((parseNumberStyles & NumberStyles.AllowThousands) != 0) + { + if (fractionalSpan.Contains(numberFormatInfo.NumberGroupSeparator, StringComparison.Ordinal)) + { + return CannotParse(out quantityValue); // number group separator detected in the fractional part (e.g. "1.2 34") + } + } + + // 3. extract the value of the string corresponding to the number without the decimal separator: "0.123 " should return "0123" + var integerString = string.Concat(integerSpan, fractionalSpan); + if (!BigInteger.TryParse(integerString, parseNumberStyles, numberFormatInfo, out var numerator)) + { + return CannotParse(out quantityValue); + } + + if (numerator.IsZero) + { + quantityValue = Zero; + return true; + } + + if (isNegative) + { + numerator = -numerator; + } + + // 4. construct the fractional part using the corresponding decimal power for the denominator + var nbDecimals = fractionalSpan.Length; + BigInteger denominator = PowerOfTen(nbDecimals); + quantityValue = new QuantityValue(numerator, denominator); + return true; + } + + private static bool TryParseInteger(ReadOnlySpan value, NumberStyles parseNumberStyles, + IFormatProvider? formatProvider, bool isNegative, out QuantityValue quantityValue) + { + if (!BigInteger.TryParse(value, parseNumberStyles, formatProvider, out var bigInteger)) + { + return CannotParse(out quantityValue); + } + + quantityValue = isNegative ? -bigInteger : bigInteger; + return true; + } + + private static bool TrySplit(ReadOnlySpan span, ReadOnlySpan separator, out ReadOnlySpan firstSpan, out ReadOnlySpan secondSpan) + { + var separatorIndex = span.IndexOf(separator); + + if (separatorIndex < 0) + { + firstSpan = span; + secondSpan = ReadOnlySpan.Empty; + return false; + } + + firstSpan = span[..separatorIndex]; + secondSpan = span[(separatorIndex + separator.Length)..]; + return true; + } + + private static bool TrySplitAny(ReadOnlySpan span, ReadOnlySpan separators, out ReadOnlySpan firstSpan, out ReadOnlySpan secondSpan) + { + var separatorIndex = span.IndexOfAny(separators); + + if (separatorIndex < 0) + { + firstSpan = span; + secondSpan = ReadOnlySpan.Empty; + return false; + } + + firstSpan = span[..separatorIndex]; + secondSpan = span[(separatorIndex + 1)..]; + return true; + } +#else + /// + /// Attempts to parse a string of characters into a QuantityValue, and returns a value + /// that indicates whether the conversion succeeded. + /// + /// + /// The input string to parse. The numerator and denominator must be separated by a '/' (slash) character. + /// For example, "3/4". If the string is not in this format, the parsing behavior is influenced by the + /// and parameters. + /// + /// + /// A bitwise combination of number styles permitted in the input string. This is relevant when the string + /// is not in the numerator/denominator format. For instance, allows decimal + /// points and scientific notation. + /// + /// + /// An that supplies culture-specific information used to parse the input string. + /// This is relevant when the string is not in the numerator/denominator format. For example, + /// CultureInfo.GetCultureInfo("en-US") for US English culture. + /// + /// + /// When this method returns, contains the parsed fraction if the operation was successful; otherwise, + /// it contains the default value of . + /// + /// + /// true if the input string is well-formed and could be parsed into a fraction; otherwise, false. + /// + /// + /// The parameter allows you to specify which number styles are allowed in the input + /// string. + /// For example, allows decimal points and scientific notation. + /// The parameter provides culture-specific formatting information. + /// For example, you can use CultureInfo.GetCultureInfo("en-US") for US English culture. + /// Here are some examples of how to use the + /// method: + /// + /// + /// QuantityValue.TryParse("3/4", NumberStyles.Any, CultureInfo.GetCultureInfo("en-US"), true, out var fraction); + /// + /// This example parses the string "3/4" into a object with a numerator of 3 and a + /// denominator of 4. + /// + /// QuantityValue.TryParse("1.25", NumberStyles.Number, CultureInfo.GetCultureInfo("en-US"), true, out var fraction); + /// + /// This example parses the string "1.25" into a object with a numerator of 5 and a + /// denominator of 4. + /// + /// QuantityValue.TryParse("1.23e-2", NumberStyles.Float, CultureInfo.GetCultureInfo("en-US"), true, out var fraction); + /// + /// This example parses the string "1.23e-2" into a object with a numerator of 123 and + /// a + /// denominator of 10000. + /// + /// + public static bool TryParse(string? value, NumberStyles numberStyles, IFormatProvider? formatProvider, out QuantityValue quantityValue) + { + if (string.IsNullOrEmpty(value)) + { + return CannotParse(out quantityValue); + } + + var numberFormatInfo = NumberFormatInfo.GetInstance(formatProvider); + + if (value!.Length == 1) + { + if (!byte.TryParse(value, numberStyles, formatProvider, out var singleDigit)) + { + if (value == numberFormatInfo.PositiveInfinitySymbol) + { + quantityValue = PositiveInfinity; + return true; + } + + if (value == numberFormatInfo.NegativeInfinitySymbol) + { + quantityValue = NegativeInfinity; + return true; + } + + if (value == numberFormatInfo.NaNSymbol) + { + quantityValue = NaN; + return true; + } + + return CannotParse(out quantityValue); + } + + quantityValue = new QuantityValue(singleDigit); + return true; + } + + // TODO see if we want to support this +#if FRACTION_PARSING_ENABLED + var components = value.Split('/'); + if (components.Length >= 2) + { + var numeratorString = components[0]; + var denominatorString = components[1]; + + var withoutDecimalPoint = numberStyles & ~NumberStyles.AllowDecimalPoint; + if (!BigInteger.TryParse( + numeratorString, + withoutDecimalPoint, + formatProvider, + out var numerator) + || !BigInteger.TryParse( + denominatorString, + withoutDecimalPoint, + formatProvider, + out var denominator)) + { + return CannotParse(out quantityValue); + } + + quantityValue = FromTerms(numerator, denominator); + return true; + } +#endif + + // parsing a number using to the selected NumberStyles: e.g. " $ 12345.1234321e-4- " should result in -1.23451234321 with NumberStyles.Any + // check for any of the special symbols (these cannot be combined with anything else) + if (value == numberFormatInfo.NaNSymbol) + { + quantityValue = NaN; + return true; + } + + if (value == numberFormatInfo.PositiveInfinitySymbol) + { + quantityValue = PositiveInfinity; + return true; + } + + if (value == numberFormatInfo.NegativeInfinitySymbol) + { + quantityValue = NegativeInfinity; + return true; + } + + var currencyAllowed = (numberStyles & NumberStyles.AllowCurrencySymbol) != 0; + + // there "special" rules regarding the white-spaces after a leading currency symbol is detected + var currencyDetected = false; + + var currencySymbol = numberFormatInfo.CurrencySymbol; + if (currencyAllowed && string.IsNullOrEmpty(currencySymbol)) + { + numberStyles &= ~NumberStyles.AllowCurrencySymbol; // no currency symbol available + currencyAllowed = false; + } + + // note: decimal.TryParse relies on the CurrencySymbol (when currency is detected) + var decimalSeparator = numberFormatInfo.NumberDecimalSeparator; + var decimalsAllowed = (numberStyles & NumberStyles.AllowDecimalPoint) != 0; + + var startIndex = 0; + var endIndex = value.Length; + var isNegative = false; + + // examine the leading characters + do + { + var character = value[startIndex]; + if (char.IsDigit(character)) + { + break; + } + + if (char.IsWhiteSpace(character)) + { + if ((numberStyles & NumberStyles.AllowLeadingWhite) == 0) + { + return CannotParse(out quantityValue); + } + + startIndex++; + continue; + } + + if (character == '(') + { + if ((numberStyles & NumberStyles.AllowParentheses) == 0) + { + return CannotParse(out quantityValue); // not allowed + } + + if (startIndex == endIndex - 1) + { + return CannotParse(out quantityValue); // not enough characters + } + + startIndex++; // consume the current character + isNegative = true; // the closing parenthesis will be validated in the backwards iteration + + if (currencyDetected) + { + // any number of white-spaces are allowed following a leading currency symbol (but no other signs) + numberStyles &= ~(NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowHexSpecifier); + } + else if (currencyAllowed && StartsWith(value, currencySymbol, startIndex)) + { + // there can be no more currency symbols but there could be more white-spaces (we skip and continue) + currencyDetected = true; + startIndex += currencySymbol.Length; + numberStyles &= ~(NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowCurrencySymbol | + NumberStyles.AllowHexSpecifier); + } + else + { + // if next character is a white space the format should be rejected + numberStyles &= ~(NumberStyles.AllowLeadingWhite | + NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowHexSpecifier); + break; + } + + continue; + } + + if ((numberStyles & NumberStyles.AllowLeadingSign) != 0) + { + if (numberFormatInfo.NegativeSign is { Length: > 0 } negativeSign && + StartsWith(value, negativeSign, startIndex)) + { + isNegative = true; + startIndex += negativeSign.Length; + if (currencyDetected) + { + // any number of white-spaces are allowed following a leading currency symbol (but no other signs) + numberStyles &= ~(NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowParentheses | + NumberStyles.AllowHexSpecifier); + } + else if (currencyAllowed && StartsWith(value, currencySymbol, startIndex)) + { + // there can be no more currency symbols but there could be more white-spaces (we skip and continue) + currencyDetected = true; + startIndex += currencySymbol.Length; + numberStyles &= ~(NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowParentheses | + NumberStyles.AllowCurrencySymbol | + NumberStyles.AllowHexSpecifier); + } + else + { + // if next character is a white space the format should be rejected + numberStyles &= ~(NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowParentheses | + NumberStyles.AllowLeadingWhite | + NumberStyles.AllowHexSpecifier); + break; + } + + continue; + } + + if (numberFormatInfo.PositiveSign is { Length: > 0 } positiveSign && + StartsWith(value, positiveSign, startIndex)) + { + isNegative = false; + startIndex += positiveSign.Length; + if (currencyDetected) + { + // any number of white-spaces are allowed following a leading currency symbol (but no other signs) + numberStyles &= ~(NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowParentheses | + NumberStyles.AllowHexSpecifier); + } + else if (currencyAllowed && StartsWith(value, currencySymbol, startIndex)) + { + // there can be no more currency symbols but there could be more white-spaces (we skip and continue) + currencyDetected = true; + startIndex += currencySymbol.Length; + numberStyles &= ~(NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowParentheses | + NumberStyles.AllowCurrencySymbol | + NumberStyles.AllowHexSpecifier); + } + else + { + // if next character is a white space the format should be rejected + numberStyles &= ~(NumberStyles.AllowLeadingSign | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowParentheses | + NumberStyles.AllowLeadingWhite | + NumberStyles.AllowHexSpecifier); + break; + } + + continue; + } + } + + if (currencyAllowed && !currencyDetected && StartsWith(value, currencySymbol, startIndex)) + { + // there can be no more currency symbols but there could be more white-spaces (we skip and continue) + currencyDetected = true; + numberStyles &= ~NumberStyles.AllowCurrencySymbol; + startIndex += currencySymbol.Length; + continue; + } + + if (decimalsAllowed && StartsWith(value, decimalSeparator, startIndex)) + { + break; // decimal string with no leading zeros + } + + // this is either an expected hex string or an invalid format + return (numberStyles & NumberStyles.AllowHexSpecifier) != 0 + ? TryParseInteger(value, numberStyles & ~NumberStyles.AllowTrailingSign, formatProvider, startIndex, + endIndex, isNegative, out quantityValue) + : CannotParse(out quantityValue); // unexpected character + } while (startIndex < endIndex); + + if (startIndex >= endIndex) + { + return CannotParse(out quantityValue); + } + + if (isNegative) + { + numberStyles &= ~(NumberStyles.AllowLeadingWhite | + NumberStyles.AllowLeadingSign); + } + else + { + numberStyles &= ~(NumberStyles.AllowLeadingWhite | + NumberStyles.AllowLeadingSign | + NumberStyles.AllowParentheses); + } + + // examine the trailing characters + do + { + var character = value[endIndex - 1]; + if (char.IsDigit(character)) + { + break; + } + + if (char.IsWhiteSpace(character)) + { + if ((numberStyles & NumberStyles.AllowTrailingWhite) == 0) + { + return CannotParse(out quantityValue); + } + + endIndex--; + continue; + } + + if (character == ')') + { + if ((numberStyles & NumberStyles.AllowParentheses) == 0) + { + return CannotParse(out quantityValue); // not allowed + } + + numberStyles &= ~(NumberStyles.AllowParentheses | NumberStyles.AllowCurrencySymbol); + endIndex--; + continue; + } + + if ((numberStyles & NumberStyles.AllowTrailingSign) != 0) + { + if (numberFormatInfo.NegativeSign is { Length: > 0 } negativeSign && + EndsWith(value, negativeSign, endIndex)) + { + isNegative = true; + numberStyles &= ~(NumberStyles.AllowTrailingSign | NumberStyles.AllowHexSpecifier); + endIndex -= negativeSign.Length; + continue; + } + + if (numberFormatInfo.PositiveSign is { Length: > 0 } positiveSign && + EndsWith(value, positiveSign, endIndex)) + { + isNegative = false; + numberStyles &= ~(NumberStyles.AllowTrailingSign | NumberStyles.AllowHexSpecifier); + endIndex -= positiveSign.Length; + continue; + } + } + + if (currencyAllowed && !currencyDetected && EndsWith(value, currencySymbol, endIndex)) + { + // there can be no more currency symbols but there could be more white-spaces (we skip and continue) + currencyDetected = true; + numberStyles &= ~NumberStyles.AllowCurrencySymbol; + endIndex -= currencySymbol.Length; + continue; + } + + if (decimalsAllowed && EndsWith(value, decimalSeparator, endIndex)) + { + break; + } + + // this is either an expected hex string or an invalid format + return (numberStyles & NumberStyles.AllowHexSpecifier) != 0 + ? TryParseInteger(value, numberStyles & ~NumberStyles.AllowTrailingSign, formatProvider, startIndex, + endIndex, isNegative, out quantityValue) + : CannotParse(out quantityValue); // unexpected character + } while (startIndex < endIndex); + + if (startIndex >= endIndex) + { + return CannotParse(out quantityValue); // not enough characters + } + + if (isNegative && (numberStyles & NumberStyles.AllowParentheses) != 0) + { + return CannotParse(out quantityValue); // failed to find a closing parentheses + } + + numberStyles &= ~(NumberStyles.AllowTrailingWhite | + NumberStyles.AllowTrailingSign | + NumberStyles.AllowCurrencySymbol); + // at this point value[startIndex, endIndex] should correspond to the number without the sign (or the format is invalid) + + if (startIndex == endIndex - 1) + { + // this can only be a single digit (integer) + return TryParseInteger(value, numberStyles, formatProvider, startIndex, endIndex, isNegative, out quantityValue); + } + + if ((numberStyles & NumberStyles.AllowExponent) != 0) + { + return TryParseWithExponent(value, numberStyles, numberFormatInfo, startIndex, endIndex, isNegative, out quantityValue); + } + + return decimalsAllowed + ? TryParseDecimalNumber(value, numberStyles, numberFormatInfo, startIndex, endIndex, isNegative, out quantityValue) + : TryParseInteger(value, numberStyles, formatProvider, startIndex, endIndex, isNegative, out quantityValue); + + static bool StartsWith(string fractionString, string testString, int startIndex) + { + var stringLength = testString.Length; + if (fractionString.Length - startIndex < stringLength) + { + return false; + } + + for (var i = 0; i < stringLength; i++) + { + if (testString[i] != fractionString[startIndex + i]) + { + return false; + } + } + + return true; + } + + static bool EndsWith(string fractionString, string testString, int endIndex) + { + return endIndex >= testString.Length && StartsWith(fractionString, testString, endIndex - testString.Length); + } + } + + private static bool TryParseWithExponent(string valueString, NumberStyles parseNumberStyles, + NumberFormatInfo numberFormatInfo, + int startIndex, int endIndex, bool isNegative, out QuantityValue quantityValue) + { + // 1. try to find the exponent character index + parseNumberStyles &= ~NumberStyles.AllowExponent; + var exponentIndex = valueString.IndexOfAny(['e', 'E'], startIndex + 1, endIndex - startIndex - 1); + if (exponentIndex == -1) + { + // no exponent found + return (parseNumberStyles & NumberStyles.AllowDecimalPoint) != 0 + ? TryParseDecimalNumber(valueString, parseNumberStyles, numberFormatInfo, startIndex, endIndex, + isNegative, out quantityValue) + : TryParseInteger(valueString, parseNumberStyles, numberFormatInfo, startIndex, endIndex, isNegative, + out quantityValue); + } + + // 2. try to parse the exponent (w.r.t. the scientific notation format) + var exponentString = valueString.Substring(exponentIndex + 1, endIndex - exponentIndex - 1); + if (!int.TryParse(exponentString, NumberStyles.AllowLeadingSign | NumberStyles.Integer, numberFormatInfo, + out var exponent)) + { + return CannotParse(out quantityValue); + } + + // 3. try to parse the coefficient (w.r.t. the decimal separator allowance) + if (startIndex == endIndex - 1 || (parseNumberStyles & NumberStyles.AllowDecimalPoint) == 0) + { + if (!TryParseInteger(valueString, parseNumberStyles, numberFormatInfo, startIndex, exponentIndex, + isNegative, out quantityValue)) + { + return false; + } + } + else + { + if (!TryParseDecimalNumber(valueString, parseNumberStyles, numberFormatInfo, startIndex, exponentIndex, isNegative, out quantityValue)) + { + return false; + } + } + + // 4. multiply the coefficient by 10 to the power of the exponent + quantityValue = new QuantityValue(quantityValue.Numerator, quantityValue.Denominator, exponent); + return true; + } + + private static bool TryParseDecimalNumber(string valueString, NumberStyles parseNumberStyles, NumberFormatInfo numberFormatInfo, + int startIndex, int endIndex, bool isNegative, out QuantityValue fraction) + { + // 1. find the position of the decimal separator (if any) + var decimalSeparatorIndex = valueString.IndexOf(numberFormatInfo.NumberDecimalSeparator, startIndex, + endIndex - startIndex, StringComparison.Ordinal); + if (decimalSeparatorIndex == -1) + { + return TryParseInteger(valueString, parseNumberStyles, numberFormatInfo, startIndex, endIndex, isNegative, + out fraction); + } + + // 2. validate the format of the string after the radix + var decimalSeparatorLength = numberFormatInfo.NumberDecimalSeparator.Length; + if (startIndex + decimalSeparatorLength == endIndex) + { + // after excluding the sign, the input was reduced to just the decimal separator (with nothing on either sides) + return CannotParse(out fraction); + } + + if ((parseNumberStyles & NumberStyles.AllowThousands) != 0) + { + if (valueString.IndexOf(numberFormatInfo.NumberGroupSeparator, + decimalSeparatorIndex + decimalSeparatorLength, StringComparison.Ordinal) != -1) + { + return CannotParse(out fraction); + } + } + + // 3. extract the value of the string corresponding to the number without the decimal separator: " 0.123 " should return "0123" + var integerString = string.Concat( + valueString.Substring(startIndex, decimalSeparatorIndex - startIndex), + valueString.Substring(decimalSeparatorIndex + decimalSeparatorLength, + endIndex - decimalSeparatorIndex - decimalSeparatorLength)); + + if (!BigInteger.TryParse(integerString, parseNumberStyles, numberFormatInfo, out var numerator)) + { + return CannotParse(out fraction); + } + + if (numerator.IsZero) + { + fraction = Zero; + return true; + } + + if (isNegative) + { + numerator = -numerator; + } + + var nbDecimals = endIndex - decimalSeparatorIndex - decimalSeparatorLength; + if (nbDecimals == 0) + { + fraction = new QuantityValue(numerator); + return true; + } + + // 4. construct the fractional part using the corresponding decimal power for the denominator + var denominator = PowerOfTen(nbDecimals); + fraction = new QuantityValue(numerator, denominator); + return true; + } + + private static bool TryParseInteger(string valueString, NumberStyles parseNumberStyles, + IFormatProvider? formatProvider, + int startIndex, int endIndex, bool isNegative, out QuantityValue fraction) + { + if (!BigInteger.TryParse(valueString.Substring(startIndex, endIndex - startIndex), parseNumberStyles, + formatProvider, out var bigInteger)) + { + return CannotParse(out fraction); + } + + fraction = new QuantityValue(isNegative ? -bigInteger : bigInteger); + return true; + } +#endif + + + /// + /// Sets the out parameter to the default value of QuantityValue and returns false. + /// This method is used when the parsing of a string to a QuantityValue fails. + /// + /// The QuantityValue object that will be set to its default value. + /// Always returns false. + private static bool CannotParse(out QuantityValue quantityValue) + { + quantityValue = default; + return false; + } +} diff --git a/UnitsNet/CustomCode/Value/QuantityValue.ConvertToNumber.cs b/UnitsNet/CustomCode/Value/QuantityValue.ConvertToNumber.cs new file mode 100644 index 0000000000..0e0ff4ddb6 --- /dev/null +++ b/UnitsNet/CustomCode/Value/QuantityValue.ConvertToNumber.cs @@ -0,0 +1,829 @@ +// 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.Numerics; +#if NET7_0_OR_GREATER +using System.Diagnostics.CodeAnalysis; +#endif + +namespace UnitsNet; + +public partial struct QuantityValue +{ + private static readonly BigInteger MaxDecimal = new(decimal.MaxValue); + private static readonly BigInteger MinDecimal = -MaxDecimal; + private static readonly BigInteger MaxDouble = new(double.MaxValue); + private static readonly BigInteger MinDouble = -MaxDouble; + + /// Explicit cast from to . + public static explicit operator double(QuantityValue value) + { + return value.ToDouble(); + } + + /// + /// Converts the quantity value to the closest double-precision floating point number. + /// + /// + /// A double-precision floating point representation of the quantity value, which may be NaN, positive infinity, or + /// negative infinity. + /// + public double ToDouble() + { + var numerator = Numerator; + var denominator = Denominator; + if (denominator.IsZero) + { + return numerator.Sign switch + { + 1 => double.PositiveInfinity, + -1 => double.NegativeInfinity, + _ => double.NaN + }; + } + + if (numerator.IsZero) + { + return 0; + } + + if (denominator.IsOne) + { + return (double)numerator; + } + + var convertedNumerator = (double)numerator; + if (double.IsPositiveInfinity(convertedNumerator)) + { + if (denominator > MaxDouble) + { + // both terms need to be rounded + numerator = numerator * MaxDouble / denominator; + denominator = MaxDouble; + if (numerator <= MaxDouble) + { + // both terms are now within range + return (double)numerator / (double)denominator; + } + } + + var withoutDecimalPlaces = (double)BigInteger.DivRem(numerator, denominator, out var remainder); + if (double.IsPositiveInfinity(withoutDecimalPlaces)) + { + return double.PositiveInfinity; + } + + return remainder.IsZero ? withoutDecimalPlaces : withoutDecimalPlaces + (double)remainder / (double)denominator; + } + + if (double.IsNegativeInfinity(convertedNumerator)) + { + if (denominator > MaxDouble) + { + // both terms need to be rounded + numerator = numerator * MaxDouble / denominator; + denominator = MaxDouble; + if (numerator >= MinDouble) + { + // both terms are now within range + return (double)numerator / (double)denominator; + } + } + + var withoutDecimalPlaces = (double)BigInteger.DivRem(numerator, denominator, out var remainder); + if (double.IsNegativeInfinity(withoutDecimalPlaces)) + { + return double.NegativeInfinity; + } + + return remainder.IsZero ? withoutDecimalPlaces : withoutDecimalPlaces + (double)remainder / (double)denominator; + } + + var convertedDenominator = (double)denominator; + if (double.IsPositiveInfinity(convertedDenominator)) + { + // since both terms are non-zero and the numerator is smaller (in magnitude) to the denominator + // the resulting number would be in the range [-1,1] (exclusive) + // we want to flip the operation: x = a/b -> 1/x = b/a + var decimalPart = (double)BigInteger.DivRem(denominator, numerator, out var remainder); + if (double.IsInfinity(decimalPart)) + { + return 0; + } + + return remainder.IsZero ? 1 / decimalPart : 1 / (decimalPart + (double)remainder / (double)numerator); + } + + return convertedNumerator / convertedDenominator; + } + + /// Explicit cast from to . + public static explicit operator decimal(QuantityValue value) + { + return value.ToDecimal(); + } + + /// + /// Converts the current to its equivalent. + /// + /// + /// A that represents the value of the current . + /// + /// + /// Thrown when the denominator of the underlying fraction is zero (case of PositiveInfinity, NegativeInfinity or NaN) + /// or when the resulting number is outside the range of the type. + /// + public decimal ToDecimal() + { + var numerator = Numerator; + var denominator = Denominator; + if (denominator.IsZero) + { + throw new OverflowException(); + } + + if (numerator.IsZero) + { + return decimal.Zero; + } + + if (denominator.IsOne) + { + return (decimal)numerator; + } + + if (numerator > MaxDecimal) + { + if (denominator > MaxDecimal) + { + // both terms need to be rounded + numerator = numerator * MaxDecimal / denominator; + denominator = MaxDecimal; + if (numerator <= MaxDecimal) + { + // both terms are now within range + return (decimal)numerator / (decimal)denominator; + } + } + + var withoutDecimalPlaces = (decimal)BigInteger.DivRem(numerator, denominator, out var remainder); + return remainder.IsZero ? withoutDecimalPlaces : withoutDecimalPlaces + (decimal)remainder / (decimal)denominator; + } + + if (numerator < MinDecimal) + { + if (denominator > MaxDecimal) + { + // both terms need to be rounded + numerator = numerator * MaxDecimal / denominator; + denominator = MaxDecimal; + if (numerator >= MinDecimal) + { + // both terms are now within range + return (decimal)numerator / (decimal)denominator; + } + } + + var withoutDecimalPlaces = (decimal)BigInteger.DivRem(numerator, denominator, out var remainder); + return remainder.IsZero ? withoutDecimalPlaces : withoutDecimalPlaces + (decimal)remainder / (decimal)denominator; + } + + if (denominator > MaxDecimal) + { + // since both terms are non-zero and the numerator is smaller (in magnitude) to the denominator + // the resulting number would be in the range [-1,1] (exclusive) + // we want to flip the operation: x = a/b -> 1/x = b/a + var decimalPart = BigInteger.DivRem(denominator, numerator, out var remainder); + return remainder.IsZero ? 1m / (decimal)decimalPart : 1m / ((decimal)decimalPart + (decimal)remainder / (decimal)numerator); + } + + return (decimal)numerator / (decimal)denominator; + } + + /// + /// Converts the fraction to a decimal number. If the fraction cannot be represented as a decimal due to its + /// size, the method will return the closest possible decimal representation (either decimal.MaxValue or + /// decimal.MinValue). + /// + /// + /// The decimal representation of the fraction. If the fraction is too large to represent as a decimal, returns + /// decimal.MaxValue. If the fraction is too small to represent as a decimal, returns decimal.MinValue. + /// + /// If the fraction is NaN (the numerator and the denominator are both zero), the method will return decimal.Zero. + public decimal ToDecimalSaturating() + { + var numerator = Numerator; + var denominator = Denominator; + if (denominator.IsZero) + { + return numerator.Sign switch + { + 1 => decimal.MaxValue, + -1 => decimal.MinValue, + _ => decimal.Zero + }; + } + + if (numerator.IsZero) + { + return decimal.Zero; + } + + if (denominator.IsOne) + { + if (numerator > MaxDecimal) + { + return decimal.MaxValue; + } + + if (numerator < MinDecimal) + { + return decimal.MinValue; + } + + return (decimal)numerator; + } + + if (numerator > MaxDecimal) + { + if (denominator > MaxDecimal) + { + // both terms need to be rounded + numerator = numerator * MaxDecimal / denominator; + denominator = MaxDecimal; + if (numerator <= MaxDecimal) + { + // both terms are now within range + return (decimal)numerator / (decimal)denominator; + } + } + + var withoutDecimalPlaces = BigInteger.DivRem(numerator, denominator, out BigInteger remainder); + if (withoutDecimalPlaces > MaxDecimal) + { + return decimal.MaxValue; + } + + return remainder.IsZero ? (decimal)withoutDecimalPlaces : (decimal)withoutDecimalPlaces + (decimal)remainder / (decimal)denominator; + } + + if (numerator < MinDecimal) + { + if (denominator > MaxDecimal) + { + // both terms need to be rounded + numerator = numerator * MaxDecimal / denominator; + denominator = MaxDecimal; + if (numerator >= MinDecimal) + { + // both terms are now within range + return (decimal)numerator / (decimal)denominator; + } + } + + var withoutDecimalPlaces = BigInteger.DivRem(numerator, denominator, out BigInteger remainder); + if (withoutDecimalPlaces < MinDecimal) + { + return decimal.MinValue; + } + + return remainder.IsZero ? (decimal)withoutDecimalPlaces : (decimal)withoutDecimalPlaces + (decimal)remainder / (decimal)denominator; + } + + if (denominator > MaxDecimal) + { + // since both terms are non-zero and the numerator is smaller (in magnitude) to the denominator + // the resulting number would be in the range [-1,1] (exclusive) + // we want to flip the operation: x = a/b -> 1/x = b/a + var decimalPart = BigInteger.DivRem(denominator, numerator, out BigInteger remainder); + if (decimalPart < MinDecimal || decimalPart > MaxDecimal) + { + return decimal.Zero; + } + + return remainder.IsZero ? 1m / (decimal)decimalPart : 1m / ((decimal)decimalPart + (decimal)remainder / (decimal)numerator); + } + + return (decimal)numerator / (decimal)denominator; + } + + /// Explicit cast from to . + public static explicit operator float(QuantityValue value) + { + return (float)(double)value; + } + + /// Explicit cast from to . + public static explicit operator BigInteger(QuantityValue value) + { + var numerator = value.Numerator; + var denominator = value.Denominator; + if (denominator.IsZero) + { + throw new OverflowException("The big integer type cannot represent NaN or Infinity"); + } + + return denominator.IsOne ? numerator : numerator / denominator; + } + + /// Explicit cast from to . + public static explicit operator long(QuantityValue value) + { + return (long)(BigInteger)value; + } + + /// Explicit cast from to . + [CLSCompliant(false)] + public static explicit operator ulong(QuantityValue value) + { + return (ulong)(BigInteger)value; + } + + /// Explicit cast from to . + public static explicit operator int(QuantityValue value) + { + return (int)(BigInteger)value; + } + + /// Explicit cast from to . + [CLSCompliant(false)] + public static explicit operator uint(QuantityValue value) + { + return (uint)(BigInteger)value; + } + + /// Explicit cast from to . + public static explicit operator short(QuantityValue value) + { + return (short)(BigInteger)value; + } + + /// Explicit cast from to . + [CLSCompliant(false)] + public static explicit operator ushort(QuantityValue value) + { + return (ushort)(BigInteger)value; + } + + /// Explicit cast from to . + public static explicit operator byte(QuantityValue value) + { + return (byte)(BigInteger)value; + } + +#if NET7_0_OR_GREATER + /// + /// Converts the given QuantityValue to a Half precision floating point number. + /// + /// The QuantityValue to convert. + /// The converted Half precision floating point number. + /// Thrown when the QuantityValue is too large to fit in a Half. + public static explicit operator Half(QuantityValue value) + { + return (Half)value.ToDouble(); + } + + /// + /// Converts the given QuantityValue to an Int128. + /// + /// The QuantityValue to convert. + /// The converted Int128. + /// Thrown when the QuantityValue is too large to fit in an Int128. + public static explicit operator Int128(QuantityValue value) + { + return (Int128)(BigInteger)value; + } + + /// + /// Converts the given Fraction to an UInt128. + /// + /// The Fraction to convert. + /// The converted UInt128. + /// Thrown when the Fraction is too large to fit in an UInt128. + [CLSCompliant(false)] + public static explicit operator UInt128(QuantityValue value) + { + return (UInt128)(BigInteger)value; + } + + static bool INumberBase.TryConvertToChecked(QuantityValue value, [MaybeNullWhen(false)] out TOther result) + { + if (typeof(TOther) == typeof(decimal)) + { + var convertedValue = value.ToDecimal(); + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(double)) + { + var convertedValue = value.ToDouble(); + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(Complex)) + { + Complex convertedValue = value.ToDouble(); + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(float)) + { + var convertedValue = (float)value.ToDouble(); + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(Half)) + { + var convertedValue = (Half)value; + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(BigInteger)) + { + var convertedValue = (BigInteger)value; + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(Int128)) + { + var convertedValue = (Int128)value; + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(UInt128)) + { + var convertedValue = (UInt128)value; + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(long)) + { + var convertedValue = (long)value; + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(ulong)) + { + var convertedValue = (ulong)value; + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(int)) + { + var num = (int)value; + result = (TOther)(object)num; + return true; + } + + if (typeof(TOther) == typeof(uint)) + { + var convertedValue = (uint)value; + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(nint)) + { + var convertedValue = (nint)(BigInteger)value; + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(UIntPtr)) + { + var convertedValue = (UIntPtr)(BigInteger)value; + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(short)) + { + var convertedValue = (short)value; + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(ushort)) + { + var convertedValue = (ushort)(BigInteger)value; + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(char)) { + var convertedValue = (char)(BigInteger)value; + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(byte)) + { + var convertedValue = (byte)(BigInteger)value; + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(sbyte)) + { + var num = (sbyte)value; + result = (TOther)(object)num; + return true; + } + + result = default; + return false; + } + + static bool INumberBase.TryConvertToSaturating(QuantityValue value, [MaybeNullWhen(false)] out TOther result) + { + if (typeof(TOther) == typeof(decimal)) + { + var convertedValue = value.ToDecimalSaturating(); + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(double)) + { + var convertedValue = value.ToDouble(); + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(Complex)) + { + Complex convertedValue = value.ToDouble(); + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(float)) + { + var convertedValue = (float)value.ToDouble(); + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(Half)) + { + var convertedValue = (Half)value; + result = (TOther)(object)convertedValue; + return true; + } + + if (typeof(TOther) == typeof(BigInteger)) + { + if (IsFinite(value)) + { + result = (TOther)(object)(BigInteger)value; + return true; + } + + if (value.Numerator.IsZero) + { + result = TOther.Zero; + } + else + { + throw new OverflowException(); + } + + return true; + } + + if (typeof(TOther) == typeof(Int128)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(UInt128)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(long)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(ulong)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(int)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(uint)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(nint)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(UIntPtr)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(short)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(ushort)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(char)) { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(byte)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(sbyte)) + { + return ConvertFromBigInteger(value, out result); + } + + result = default; + return false; + + static bool ConvertFromBigInteger(QuantityValue value, out TOther convertedValue) where TNumber : INumberBase, IMinMaxValue + { + if (IsFinite(value)) + { + convertedValue = TOther.CreateSaturating((BigInteger)value); + } + else + { + convertedValue = value.Numerator.Sign switch + { + 1 => (TOther)(object)TNumber.MaxValue, + -1 => (TOther)(object)TNumber.MinValue, + _ => (TOther)(object)TNumber.Zero + }; + } + + return true; + } + } + + static bool INumberBase.TryConvertToTruncating(QuantityValue value, [MaybeNullWhen(false)] out TOther result) + { + if (typeof(TOther) == typeof(decimal)) + { + var num = value.ToDecimalSaturating(); + result = (TOther)(object)num; + return true; + } + + if (typeof(TOther) == typeof(double)) + { + var num = value.ToDouble(); + result = (TOther)(object)num; + return true; + } + + if (typeof(TOther) == typeof(Complex)) + { + Complex num = value.ToDouble(); + result = (TOther)(object)num; + return true; + } + + if (typeof(TOther) == typeof(float)) + { + var num = (float)value.ToDouble(); + result = (TOther)(object)num; + return true; + } + + if (typeof(TOther) == typeof(Half)) + { + var half = (Half)value; + result = (TOther)(object)half; + return true; + } + + if (typeof(TOther) == typeof(BigInteger)) + { + if (IsFinite(value)) + { + result = (TOther)(object)(BigInteger)value; + } + else if (value.Numerator.IsZero) + { + result = TOther.Zero; + } + else + { + throw new OverflowException(); + } + + return true; + } + + if (typeof(TOther) == typeof(Int128)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(UInt128)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(long)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(ulong)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(int)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(uint)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(nint)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(UIntPtr)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(short)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(ushort)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(char)) { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(byte)) + { + return ConvertFromBigInteger(value, out result); + } + + if (typeof(TOther) == typeof(sbyte)) + { + return ConvertFromBigInteger(value, out result); + } + + result = default; + return false; + + static bool ConvertFromBigInteger(QuantityValue value, out TOther convertedValue) where TNumber : INumberBase, IMinMaxValue + { + convertedValue = IsFinite(value) + ? TOther.CreateTruncating((BigInteger)value) + : value.Numerator.Sign switch + { + 1 => (TOther)(object)TNumber.MaxValue, + -1 => (TOther)(object)TNumber.MinValue, + _ => (TOther)(object)TNumber.Zero + }; + + return true; + } + } + +#endif +} diff --git a/UnitsNet/CustomCode/Value/QuantityValue.ConvertToString.cs b/UnitsNet/CustomCode/Value/QuantityValue.ConvertToString.cs new file mode 100644 index 0000000000..6e13262f74 --- /dev/null +++ b/UnitsNet/CustomCode/Value/QuantityValue.ConvertToString.cs @@ -0,0 +1,3653 @@ +// 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.Globalization; +using System.Numerics; +using System.Runtime.CompilerServices; +#if !NET +using System.Text; +#endif + +namespace UnitsNet; + +public partial struct QuantityValue +{ + /// Returns the string representation of the numeric value. + public override string ToString() + { + return ToString("G"); + } + + /// + /// 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, NumberFormatInfo.CurrentInfo); + } + + /// + /// Returns the string representation of the numeric value, formatted using the given standard numeric format string + /// + /// The culture to use + /// The string representation + public string ToString(IFormatProvider? formatProvider) + { + return ToString(null, formatProvider); + } + + /// + /// 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 + /// + /// This method supports the following format strings: + /// + /// + /// + /// + /// 'G' + /// or 'g' + /// + /// : General format. Example: 400/3 formatted with 'G2' gives "1.3E+02". + /// + /// + /// + /// + /// + /// 'F' + /// or 'f' + /// + /// : Fixed-point format. Example: 12345/10 formatted with 'F2' gives "1234.50". + /// + /// + /// + /// + /// + /// 'N' + /// or 'n' + /// + /// : Standard Numeric format. Example: 1234567/1000 formatted with 'N2' gives "1,234.57". + /// + /// + /// + /// + /// + /// 'E' + /// or 'e' + /// + /// : Scientific format. Example: 1234567/1000 formatted with 'E2' gives "1.23E+003". + /// + /// + /// + /// + /// + /// 'P' + /// or 'p' + /// + /// : Percent format. Example: 2/3 formatted with 'P2' gives "66.67 %". + /// + /// + /// + /// + /// + /// 'C' + /// or 'c' + /// + /// : Currency format. Example: 1234567/1000 formatted with 'C2' gives "$1,234.57". + /// + /// + /// + /// + /// + /// 'R' + /// or 'r' + /// + /// : Round-trip format. Example: 1234567/1000 formatted with 'R' gives "1234.567". + /// + /// + /// + /// + /// + /// 'S' + /// or 's' + /// + /// : Significant Digits After Radix format. Example: 400/3 formatted with 'S2' gives + /// "133.33". + /// + /// + /// + /// Note: The 'R' format and custom formats do not support precision specifiers and are handed over to the `double` + /// type for formatting, which may result in a loss of precision. + /// For more information about the formatter, see the + /// + /// DecimalNotationFormatter + /// section + /// + /// in the GitHub README. + /// + public string ToString(string? format, IFormatProvider? formatProvider) + { + return DecimalNotationFormatter.Format(this, format, formatProvider); + } + +#if NET7_0_OR_GREATER + /// + public bool TryFormat(Span destination, out int charsWritten, ReadOnlySpan format, IFormatProvider? provider) + { + return DecimalNotationFormatter.TryFormat(destination, out charsWritten, this, format, provider); + } +#endif + +#if NET + + /// + /// Provides functionality to format the value of a QuantityValue object into a decimal string representation following + /// the + /// standard numeric formats, as implemented by the double type. + /// + private static class DecimalNotationFormatter + { + /// + /// + /// + /// On .NET Framework and .NET Core up to .NET Core 2.0, the runtime selects the result with the greater least + /// significant digit (that is, using ). + /// + /// + /// On .NET Core 2.1 and later, the runtime selects the result with an even least significant digit (that is, + /// using ). + /// + /// + /// + private const MidpointRounding DefaultMidpointRoundingMode = MidpointRounding.AwayFromZero; + + /// + /// The default precision used for the general format specifier (G) + /// + private const int DefaultGeneralFormatPrecision = 16; + + /// + /// The default precision used for the exponential (scientific) format specifier (E) + /// + private const int DefaultScientificFormatPrecision = 6; + + private const int StackLimit = 250; // Safe limit for stackalloc (512 chars) + + + private static readonly double Log10Of2 = Math.Log10(2); + + + /// + /// Formats the value of the specified Fraction as a string using the specified format. + /// + /// A standard or custom numeric format string. + /// The Fraction object to be formatted. + /// An object that supplies culture-specific formatting information. + /// + /// The string representation of the value of the Fraction object as specified by the format and formatProvider + /// parameters. + /// + /// + /// This method supports the following format strings: + /// + /// + /// + /// + /// 'G' + /// or 'g' + /// + /// : General format. Example: 400/3 formatted with 'G2' gives "1.3E+02". + /// + /// + /// + /// + /// + /// 'F' + /// or 'f' + /// + /// : Fixed-point format. Example: 12345/10 formatted with 'F2' gives "1234.50". + /// + /// + /// + /// + /// + /// 'N' + /// or 'n' + /// + /// : Standard Numeric format. Example: 1234567/1000 formatted with 'N2' gives "1,234.57". + /// + /// + /// + /// + /// + /// 'E' + /// or 'e' + /// + /// : Scientific format. Example: 1234567/1000 formatted with 'E2' gives "1.23E+003". + /// + /// + /// + /// + /// + /// 'P' + /// or 'p' + /// + /// : Percent format. Example: 2/3 formatted with 'P2' gives "66.67 %". + /// + /// + /// + /// + /// + /// 'C' + /// or 'c' + /// + /// : Currency format. Example: 1234567/1000 formatted with 'C2' gives "$1,234.57". + /// + /// + /// + /// + /// + /// 'R' + /// or 'r' + /// + /// : Round-trip format. Example: 1234567/1000 formatted with 'R' gives "1234.567". + /// + /// + /// + /// + /// + /// 'S' + /// or 's' + /// + /// : Significant Digits After Radix format. Example: 400/3 formatted with 'S2' gives + /// "133.33". + /// + /// + /// + /// Note: The 'R' format and custom formats do not support precision specifiers and are handed over to the `double` + /// type for formatting, which may result in a loss of precision. + /// For more information about the formatter, see the + /// + /// DecimalNotationFormatter + /// section + /// + /// in the GitHub README. + /// + public static string Format(QuantityValue fraction, string? format, IFormatProvider? formatProvider) + { + var numberFormatInfo = NumberFormatInfo.GetInstance(formatProvider); + BigInteger numerator = fraction.Numerator; + BigInteger denominator = fraction.Denominator; + if (denominator.Sign == 0) + { + return numerator.Sign switch + { + 1 => numberFormatInfo.PositiveInfinitySymbol, + -1 => numberFormatInfo.NegativeInfinitySymbol, + _ => numberFormatInfo.NaNSymbol + }; + } + + if (string.IsNullOrEmpty(format)) + { + return FormatGeneral(numerator, denominator, "G", numberFormatInfo); + } + + var formatCharacter = format[0]; + return formatCharacter switch + { + 'G' or 'g' => FormatGeneral(numerator, denominator, format, numberFormatInfo), + 'F' or 'f' => FormatWithFixedPointFormat(numerator, denominator, format, numberFormatInfo), + 'N' or 'n' => FormatWithStandardNumericFormat(numerator, denominator, format, numberFormatInfo), + 'E' or 'e' => FormatWithScientificFormat(numerator, denominator, format, numberFormatInfo), + 'P' or 'p' => FormatWithPercentFormat(numerator, denominator, format, numberFormatInfo), + 'C' or 'c' => FormatWithCurrencyFormat(numerator, denominator, format, numberFormatInfo), + 'S' or 's' => FormatWithSignificantDigitsAfterRadix(numerator, denominator, format, numberFormatInfo), + _ => // 'R', 'r' and the custom formats are handed over to the double (possible loss of precision) + fraction.ToDouble().ToString(format, numberFormatInfo) + }; + } + + public static bool TryFormat(Span destination, out int charsWritten, QuantityValue fraction, ReadOnlySpan format, IFormatProvider? formatProvider) + { + var numberFormatInfo = NumberFormatInfo.GetInstance(formatProvider); + BigInteger numerator = fraction.Numerator; + BigInteger denominator = fraction.Denominator; + if (denominator.Sign == 0) + { + charsWritten = 0; + switch (numerator.Sign) + { + case 1: + if (!numberFormatInfo.PositiveInfinitySymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = numberFormatInfo.PositiveInfinitySymbol.Length; + return true; + case -1: + if (!numberFormatInfo.NegativeInfinitySymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = numberFormatInfo.NegativeInfinitySymbol.Length; + return true; + default: + if (!numberFormatInfo.NaNSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = numberFormatInfo.NaNSymbol.Length; + return true; + } + } + + if (format.IsEmpty) + { + return TryFormatGeneral(destination, out charsWritten, numerator, denominator, "G", numberFormatInfo); + } + + var formatCharacter = format[0]; + return formatCharacter switch + { + 'G' or 'g' => TryFormatGeneral(destination, out charsWritten, numerator, denominator, format, numberFormatInfo), + 'F' or 'f' => TryFormatWithFixedPointFormat(destination, out charsWritten, numerator, denominator, format, numberFormatInfo), + 'N' or 'n' => TryFormatWithStandardNumericFormat(destination, out charsWritten, numerator, denominator, format, numberFormatInfo), + 'E' or 'e' => TryFormatWithScientificFormat(destination, out charsWritten, numerator, denominator, format, numberFormatInfo), + 'P' or 'p' => TryFormatWithPercentFormat(destination, out charsWritten, numerator, denominator, format, numberFormatInfo), + 'C' or 'c' => TryFormatWithCurrencyFormat(destination, out charsWritten, numerator, denominator, format, numberFormatInfo), + 'S' or 's' => TryFormatWithSignificantDigitsAfterRadix(destination, out charsWritten, numerator, denominator, format, numberFormatInfo), + _ => // 'R', 'r' and the custom formats are handed over to the double (possible loss of precision) + fraction.ToDouble().TryFormat(destination, out charsWritten, format, numberFormatInfo) + }; + } + + private static bool TryGetPrecisionDigits(ReadOnlySpan format, int defaultPrecision, out int maxNbDecimals) + { + if (format.Length == 1) + { + // The number of digits is not specified, use default precision. + maxNbDecimals = defaultPrecision; + return true; + } + + if (int.TryParse(format[1..], out maxNbDecimals)) + { + return true; + } + + // Seems to be some kind of custom format we do not understand, fallback to default precision. + maxNbDecimals = defaultPrecision; + return false; + } + + /// + /// The fixed-point ("F") format specifier converts a number to a string of the form "-ddd.ddd…" where each "d" + /// indicates a digit (0-9). The string starts with a minus sign if the number is negative. + /// + /// + /// The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the + /// current property supplies the numeric precision. + /// + private static string FormatWithFixedPointFormat(BigInteger numerator, BigInteger denominator, string format, NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.ToString(format, formatProvider); + } + + if (denominator.IsOne) + { + return numerator.ToString(format, formatProvider); + } + + if (!TryGetPrecisionDigits(format, formatProvider.NumberDecimalDigits, out var maxNbDecimalsAfterRadix)) + { + // not a valid "F" format: assuming a custom format + return FormatWithCustomFormat(numerator, denominator, format, formatProvider); + } + + Span buffer = stackalloc char[StackLimit]; // Use stack memory + int charsWritten; + while (!TryFormatWithFixedPointFormat(buffer, out charsWritten, numerator, denominator, format, formatProvider, maxNbDecimalsAfterRadix)) + { + buffer = new char[buffer.Length * 2]; // Use heap if needed + } + + return new string(buffer[..charsWritten]); + } + + private static bool TryFormatWithFixedPointFormat(Span destination, out int charsWritten, BigInteger numerator, BigInteger denominator, ReadOnlySpan format, + NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.TryFormat(destination, out charsWritten, format, formatProvider); + } + + if (denominator.IsOne) + { + return numerator.TryFormat(destination, out charsWritten, format, formatProvider); + } + + if (!TryGetPrecisionDigits(format, formatProvider.NumberDecimalDigits, out var maxNbDecimalsAfterRadix)) + { + // not a valid "F" format: assuming a custom format + return TryFormatWithCustomFormat(destination, out charsWritten, numerator, denominator, format, formatProvider); + } + + return TryFormatWithFixedPointFormat(destination, out charsWritten, numerator, denominator, format, formatProvider, maxNbDecimalsAfterRadix); + } + + private static bool TryFormatWithFixedPointFormat(Span destination, out int charsWritten, BigInteger numerator, BigInteger denominator, ReadOnlySpan format, + NumberFormatInfo formatProvider, int maxNbDecimalsAfterRadix) + { + if (maxNbDecimalsAfterRadix == 0) + { + var roundedValue = RoundToBigInteger(numerator, denominator, DefaultMidpointRoundingMode); + return roundedValue.TryFormat(destination, out charsWritten, format, formatProvider); + } + + var (roundedNumerator, roundedDenominator) = Round(numerator, denominator, maxNbDecimalsAfterRadix, DefaultMidpointRoundingMode); + + switch (roundedNumerator.Sign) + { + case 0: + return 0.TryFormat(destination, out charsWritten, format, formatProvider); + case 1: + return TryAppendDecimals(destination, out charsWritten, roundedNumerator, roundedDenominator, formatProvider, maxNbDecimalsAfterRadix, "F0"); + default: + { + if (!formatProvider.NegativeSign.TryCopyTo(destination)) + { + charsWritten = 0; + return false; + } + + charsWritten = formatProvider.NegativeSign.Length; + + roundedNumerator = -roundedNumerator; + if (!TryAppendDecimals(destination[charsWritten..], out var digitsWritten, roundedNumerator, roundedDenominator, formatProvider, maxNbDecimalsAfterRadix, "F0")) + { + return false; + } + + charsWritten += digitsWritten; + return true; + } + } + } + + /// + /// The numeric ("N") format specifier converts a number to a string of the form "-d,ddd,ddd.ddd…", where "-" + /// indicates + /// a negative number symbol if required, "d" indicates a digit (0-9), "," indicates a group separator, and "." + /// indicates a decimal point symbol. + /// + /// + /// The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the + /// current property supplies the numeric precision. + /// + private static string FormatWithStandardNumericFormat(BigInteger numerator, BigInteger denominator, string format, NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.ToString(format, formatProvider); + } + + if (denominator.IsOne) + { + return numerator.ToString(format, formatProvider); + } + + if (!TryGetPrecisionDigits(format, formatProvider.NumberDecimalDigits, out var maxNbDecimals)) + { + // not a valid "N" format: assuming a custom format + return FormatWithCustomFormat(numerator, denominator, format, formatProvider); + } + + Span buffer = stackalloc char[StackLimit]; // Use stack memory + int charsWritten; + while (!TryFormatWithStandardNumericFormat(buffer, out charsWritten, numerator, denominator, format, formatProvider, maxNbDecimals)) + { + buffer = new char[buffer.Length * 2]; // Use heap if needed + } + + return new string(buffer[..charsWritten]); + } + + private static bool TryFormatWithStandardNumericFormat(Span destination, out int charsWritten, BigInteger numerator, BigInteger denominator, + ReadOnlySpan format, NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.TryFormat(destination, out charsWritten, format, formatProvider); + } + + if (denominator.IsOne) + { + return numerator.TryFormat(destination, out charsWritten, format, formatProvider); + } + + if (!TryGetPrecisionDigits(format, formatProvider.NumberDecimalDigits, out var maxNbDecimals)) + { + // not a valid "N" format: assuming a custom format + return TryFormatWithCustomFormat(destination, out charsWritten, numerator, denominator, format, formatProvider); + } + + return TryFormatWithStandardNumericFormat(destination, out charsWritten, numerator, denominator, format, formatProvider, maxNbDecimals); + } + + private static bool TryFormatWithStandardNumericFormat(Span destination, out int charsWritten, BigInteger numerator, BigInteger denominator, + ReadOnlySpan format, + NumberFormatInfo formatProvider, int maxNbDecimals) + { + if (maxNbDecimals == 0) + { + var roundedValue = RoundToBigInteger(numerator, denominator, DefaultMidpointRoundingMode); + return roundedValue.TryFormat(destination, out charsWritten, format, formatProvider); + } + + var (roundedNumerator, roundedDenominator) = Round(numerator, denominator, maxNbDecimals, DefaultMidpointRoundingMode); + switch (roundedNumerator.Sign) + { + case 0: + return 0.TryFormat(destination, out charsWritten, format, formatProvider); + case 1: + return TryAppendDecimals(destination, out charsWritten, roundedNumerator, roundedDenominator, formatProvider, maxNbDecimals, "N0"); + default: + if (!TryAppendLeadingNegativePattern(destination, out charsWritten, formatProvider.NegativeSign, formatProvider.NumberNegativePattern)) + { + return false; + } + + roundedNumerator = -roundedNumerator; + if (!TryAppendDecimals(destination[charsWritten..], out var decimalsWritten, roundedNumerator, roundedDenominator, formatProvider, maxNbDecimals, "N0")) + { + return false; + } + + charsWritten += decimalsWritten; + if (!TryAppendTrailingNegativePattern(destination[charsWritten..], out var trailingCharsWritten, formatProvider.NegativeSign, + formatProvider.NumberNegativePattern)) + { + return false; + } + + charsWritten += trailingCharsWritten; + return true; + } + + static bool TryAppendLeadingNegativePattern(Span destination, out int charsWritten, string negativeSignSymbol, int pattern) + { + charsWritten = 0; + switch (pattern) + { + case 0: // (n) : leading is '(' + if (destination.IsEmpty) + { + return false; + } + + destination[0] = '('; + charsWritten = 1; + return true; + case 1: // -n : leading is negativeSignSymbol + if (!negativeSignSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = negativeSignSymbol.Length; + return true; + case 2: // - n : leading is negativeSignSymbol + ' ' + if (!negativeSignSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = negativeSignSymbol.Length; + if (charsWritten == destination.Length) + { + return false; + } + + destination[charsWritten] = ' '; + charsWritten++; + return true; + default: //"n-" and "n -" : no leading addition + return true; + } + } + + static bool TryAppendTrailingNegativePattern(Span destination, out int charsWritten, string negativeSignSymbol, int pattern) + { + charsWritten = 0; + switch (pattern) + { + case 0: // (n) : trailing is ')' + if (destination.IsEmpty) + { + return false; + } + + destination[0] = ')'; + charsWritten = 1; + return true; + case 3: // n- : trailing is negativeSignSymbol + if (!negativeSignSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = negativeSignSymbol.Length; + return true; + case 4: // n - : trailing is ' ' + negativeSignSymbol + if (destination.IsEmpty) + { + return false; + } + + destination[0] = ' '; + charsWritten = 1; + if (!negativeSignSymbol.TryCopyTo(destination[charsWritten..])) + { + return false; + } + + charsWritten += negativeSignSymbol.Length; + return true; + default: // -n and - n cases are handled in leading function + return true; + } + } + } + + /// + /// The percent ("P") format specifier multiplies a number by 100 and converts it to a string that represents a + /// percentage. + /// + /// + /// The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, + /// the default numeric precision supplied by the current property + /// is used. + /// + private static string FormatWithPercentFormat(BigInteger numerator, BigInteger denominator, string format, NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.ToString(format, formatProvider); + } + + if (denominator.IsOne) + { + return numerator.ToString(format, formatProvider); + } + + if (!TryGetPrecisionDigits(format, formatProvider.PercentDecimalDigits, out var maxNbDecimals)) + { + // not a valid "P" format: assuming a custom format + return FormatWithCustomFormat(numerator, denominator, format, formatProvider); + } + + Span buffer = stackalloc char[StackLimit]; // Use stack memory + int charsWritten; + while (!TryFormatWithPercentFormat(buffer, out charsWritten, numerator, denominator, format, formatProvider, maxNbDecimals)) + { + buffer = new char[buffer.Length * 2]; // Use heap if needed + } + + return new string(buffer[..charsWritten]); + } + + private static bool TryFormatWithPercentFormat(Span destination, out int charsWritten, BigInteger numerator, BigInteger denominator, ReadOnlySpan format, + NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.TryFormat(destination, out charsWritten, format, formatProvider); + } + + if (denominator.IsOne) + { + return numerator.TryFormat(destination, out charsWritten, format, formatProvider); + } + + if (!TryGetPrecisionDigits(format, formatProvider.PercentDecimalDigits, out var maxNbDecimals)) + { + // not a valid "P" format: assuming a custom format + return TryFormatWithCustomFormat(destination, out charsWritten, numerator, denominator, format, formatProvider); + } + + return TryFormatWithPercentFormat(destination, out charsWritten, numerator, denominator, format, formatProvider, maxNbDecimals); + } + + private static bool TryFormatWithPercentFormat(Span destination, out int charsWritten, BigInteger numerator, BigInteger denominator, ReadOnlySpan format, + NumberFormatInfo formatProvider, int maxNbDecimals) + { + if (maxNbDecimals == 0) + { + var roundedValue = RoundToBigInteger(100 * numerator, denominator, DefaultMidpointRoundingMode); + if (roundedValue.IsZero) + { + return 0.TryFormat(destination, out charsWritten, format, formatProvider); + } + + var percentFormatInfo = new NumberFormatInfo + { + NumberDecimalSeparator = formatProvider.PercentDecimalSeparator, + NumberGroupSeparator = formatProvider.PercentGroupSeparator, + NumberGroupSizes = formatProvider.PercentGroupSizes, + NativeDigits = formatProvider.NativeDigits, + DigitSubstitution = formatProvider.DigitSubstitution + }; + + if (roundedValue.Sign >= 0) + { + if (!TryAppendLeadingPositivePercentPattern(destination, out charsWritten, formatProvider.PercentSymbol, formatProvider.PercentPositivePattern)) + { + return false; + } + + if (!roundedValue.TryFormat(destination[charsWritten..], out var decimalsWritten, "N0", percentFormatInfo)) + { + return false; + } + + charsWritten += decimalsWritten; + + if (!TryAppendTrailingPositivePercentPattern(destination[charsWritten..], out var trailingCharsWritten, formatProvider.PercentSymbol, + formatProvider.PercentPositivePattern)) + { + return false; + } + + charsWritten += trailingCharsWritten; + } + else + { + if (!TryAppendLeadingNegativePercentPattern(destination, out charsWritten, formatProvider.PercentSymbol, formatProvider.NegativeSign, + formatProvider.PercentNegativePattern)) + { + return false; + } + + roundedValue = -roundedValue; + if (!roundedValue.TryFormat(destination[charsWritten..], out var decimalsWritten, "N0", percentFormatInfo)) + { + return false; + } + + charsWritten += decimalsWritten; + + if (!TryAppendTrailingNegativePercentPattern(destination[charsWritten..], out var trailingCharsWritten, formatProvider.PercentSymbol, + formatProvider.NegativeSign, + formatProvider.PercentNegativePattern)) + { + return false; + } + + charsWritten += trailingCharsWritten; + } + } + else + { + var (roundedNumerator, roundedDenominator) = Round(numerator * 100, denominator, maxNbDecimals, DefaultMidpointRoundingMode); + if (roundedNumerator.IsZero) + { + return 0.TryFormat(destination, out charsWritten, format, formatProvider); + } + + var percentFormatInfo = new NumberFormatInfo + { + NumberDecimalSeparator = formatProvider.PercentDecimalSeparator, + NumberGroupSeparator = formatProvider.PercentGroupSeparator, + NumberGroupSizes = formatProvider.PercentGroupSizes, + NativeDigits = formatProvider.NativeDigits, + DigitSubstitution = formatProvider.DigitSubstitution + }; + + if (roundedNumerator.Sign > 0) + { + if (!TryAppendLeadingPositivePercentPattern(destination, out charsWritten, formatProvider.PercentSymbol, formatProvider.PercentPositivePattern)) + { + return false; + } + + if (!TryAppendDecimals(destination[charsWritten..], out var decimalsWritten, roundedNumerator, roundedDenominator, percentFormatInfo, maxNbDecimals, "N0")) + { + return false; + } + + charsWritten += decimalsWritten; + + if (!TryAppendTrailingPositivePercentPattern(destination[charsWritten..], out var trailingCharsWritten, formatProvider.PercentSymbol, + formatProvider.PercentPositivePattern)) + { + return false; + } + + charsWritten += trailingCharsWritten; + } + else + { + if (!TryAppendLeadingNegativePercentPattern(destination, out charsWritten, formatProvider.PercentSymbol, formatProvider.NegativeSign, + formatProvider.PercentNegativePattern)) + { + return false; + } + + roundedNumerator = -roundedNumerator; + if (!TryAppendDecimals(destination[charsWritten..], out var decimalsWritten, roundedNumerator, roundedDenominator, percentFormatInfo, maxNbDecimals, "N0")) + { + return false; + } + + charsWritten += decimalsWritten; + + if (!TryAppendTrailingNegativePercentPattern(destination[charsWritten..], out var trailingCharsWritten, formatProvider.PercentSymbol, + formatProvider.NegativeSign, formatProvider.PercentNegativePattern)) + { + return false; + } + + charsWritten += trailingCharsWritten; + } + } + + return true; + + static bool TryAppendLeadingPositivePercentPattern(Span destination, out int charsWritten, string percentSymbol, int pattern) + { + charsWritten = 0; + switch (pattern) + { + case 0: // n % : no leading addition + case 1: // n% : no leading addition + return true; + case 2: // %n : leading is percentSymbol only + if (!percentSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = percentSymbol.Length; + return true; + default: // % n : leading is percentSymbol + ' ' + if (!percentSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = percentSymbol.Length; + if (destination.Length == charsWritten) + { + return false; + } + + destination[charsWritten] = ' '; + charsWritten++; + return true; + } + } + + static bool TryAppendTrailingPositivePercentPattern(Span destination, out int charsWritten, string percentSymbol, int pattern) + { + charsWritten = 0; + switch (pattern) + { + case 0: // n % : trailing is ' ' + percentSymbol + if (destination.IsEmpty) + { + return false; + } + + destination[0] = ' '; + charsWritten = 1; + if (!percentSymbol.TryCopyTo(destination[charsWritten..])) + { + return false; + } + + charsWritten += percentSymbol.Length; + return true; + case 1: // n% : trailing is percentSymbol only + if (!percentSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = percentSymbol.Length; + return true; + default: // "%n" and "% n" : no trailing addition + return true; + } + } + + static bool TryAppendLeadingNegativePercentPattern(Span destination, out int charsWritten, string percentSymbol, string negativeSignSymbol, int pattern) + { + charsWritten = 0; + switch (pattern) + { + case 0: // -n % + case 1: // -n% + if (!negativeSignSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = negativeSignSymbol.Length; + return true; + case 2: // -%n + if (!negativeSignSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = negativeSignSymbol.Length; + if (!percentSymbol.TryCopyTo(destination[charsWritten..])) + { + return false; + } + + charsWritten += percentSymbol.Length; + return true; + case 3: // %-n + if (!percentSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = percentSymbol.Length; + if (!negativeSignSymbol.TryCopyTo(destination[charsWritten..])) + { + return false; + } + + charsWritten += negativeSignSymbol.Length; + return true; + case 4: // %n- + if (!percentSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = percentSymbol.Length; + return true; + case 5: // n-% + case 6: // n%- + return true; + case 7: // -% n + if (!negativeSignSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = negativeSignSymbol.Length; + if (!percentSymbol.TryCopyTo(destination[charsWritten..])) + { + return false; + } + + charsWritten += percentSymbol.Length; + if (charsWritten == destination.Length) + { + return false; + } + + destination[charsWritten] = ' '; + charsWritten++; + return true; + case 8: // n %- + return true; + case 9: // % n- + if (!percentSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = percentSymbol.Length; + if (charsWritten == destination.Length) + { + return false; + } + + destination[charsWritten] = ' '; + charsWritten++; + return true; + case 10: // % -n + if (!percentSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = percentSymbol.Length; + if (charsWritten == destination.Length) + { + return false; + } + + destination[charsWritten] = ' '; + charsWritten++; + + if (!negativeSignSymbol.TryCopyTo(destination[charsWritten..])) + { + return false; + } + + charsWritten += negativeSignSymbol.Length; + return true; + default: // n- % + // No leading part required for other patterns + return true; + } + } + + static bool TryAppendTrailingNegativePercentPattern(Span destination, out int charsWritten, string percentSymbol, string negativeSignSymbol, int pattern) + { + charsWritten = 0; + switch (pattern) + { + case 0: // -n %: trailing is " " + percentSymbol + if (destination.IsEmpty) + { + return false; + } + + destination[0] = ' '; + charsWritten = 1; + if (!percentSymbol.TryCopyTo(destination[charsWritten..])) + { + return false; + } + + charsWritten += percentSymbol.Length; + return true; + case 1: // -n%: trailing is percentSymbol + if (!percentSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = percentSymbol.Length; + return true; + case 2: // -%n: no trailing addition + case 3: // %-n: no trailing addition + return true; + case 4: // %n-: trailing is negativeSignSymbol + if (!negativeSignSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = negativeSignSymbol.Length; + return true; + case 5: // n-%: trailing is negativeSignSymbol + percentSymbol + if (!negativeSignSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = negativeSignSymbol.Length; + if (!percentSymbol.TryCopyTo(destination[charsWritten..])) + { + return false; + } + + charsWritten += percentSymbol.Length; + return true; + case 6: // n%-: trailing is percentSymbol + negativeSignSymbol + if (!percentSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = percentSymbol.Length; + if (!negativeSignSymbol.TryCopyTo(destination[charsWritten..])) + { + return false; + } + + charsWritten += negativeSignSymbol.Length; + return true; + case 7: // -% n: no trailing addition + return true; + case 8: // n %-: trailing is " " + percentSymbol + negativeSignSymbol + if (destination.Length < 1 + percentSymbol.Length + negativeSignSymbol.Length) + { + return false; + } + + destination[0] = ' '; + charsWritten = 1; + percentSymbol.CopyTo(destination[charsWritten..]); + charsWritten += percentSymbol.Length; + negativeSignSymbol.CopyTo(destination[charsWritten..]); + charsWritten += negativeSignSymbol.Length; + return true; + case 9: // % n-: trailing is negativeSignSymbol + if (!negativeSignSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = negativeSignSymbol.Length; + return true; + case 10: // % -n: no trailing addition + return true; + default: // n- %: trailing is negativeSignSymbol + " " + percentSymbol + if (!negativeSignSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = negativeSignSymbol.Length; + if (destination.Length == charsWritten) + { + return false; + } + + destination[charsWritten] = ' '; + charsWritten++; + if (!percentSymbol.TryCopyTo(destination[charsWritten..])) + { + return false; + } + + charsWritten += percentSymbol.Length; + return true; + } + } + } + + /// + /// The "C" (or currency) format specifier converts a number to a string that represents a currency amount. The + /// precision specifier indicates the desired number of decimal places in the result string. If the precision specifier + /// is omitted, the default precision is defined by the property. + /// + /// + /// If the value to be formatted has more than the specified or default number of decimal places, the fractional + /// value is rounded in the result string. If the value to the right of the number of specified decimal places is 5 or + /// greater, the last digit in the result string is rounded away from zero. + /// + private static string FormatWithCurrencyFormat(BigInteger numerator, BigInteger denominator, string format, NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.ToString(format, formatProvider); + } + + if (denominator.IsOne) + { + return numerator.ToString(format, formatProvider); + } + + if (!TryGetPrecisionDigits(format, formatProvider.CurrencyDecimalDigits, out var maxNbDecimals)) + { + // not a valid "C" format: assuming a custom format + return FormatWithCustomFormat(numerator, denominator, format, formatProvider); + } + + Span buffer = stackalloc char[StackLimit]; // Use stack memory + int charsWritten; + while (!TryFormatWithCurrencyFormat(buffer, out charsWritten, numerator, denominator, format, formatProvider, maxNbDecimals)) + { + buffer = new char[buffer.Length * 2]; // Use heap if needed + } + + return new string(buffer[..charsWritten]); + } + + private static bool TryFormatWithCurrencyFormat(Span destination, out int charsWritten, BigInteger numerator, BigInteger denominator, ReadOnlySpan format, + NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.TryFormat(destination, out charsWritten, format, formatProvider); + } + + if (denominator.IsOne) + { + return numerator.TryFormat(destination, out charsWritten, format, formatProvider); + } + + if (!TryGetPrecisionDigits(format, formatProvider.CurrencyDecimalDigits, out var maxNbDecimals)) + { + // not a valid "C" format: assuming a custom format + return TryFormatWithCustomFormat(destination, out charsWritten, numerator, denominator, format, formatProvider); + } + + return TryFormatWithCurrencyFormat(destination, out charsWritten, numerator, denominator, format, formatProvider, maxNbDecimals); + } + + private static bool TryFormatWithCurrencyFormat(Span destination, out int charsWritten, BigInteger numerator, BigInteger denominator, ReadOnlySpan format, + NumberFormatInfo formatProvider, + int maxNbDecimals) + { + if (maxNbDecimals == 0) + { + var roundedValue = RoundToBigInteger(numerator, denominator, DefaultMidpointRoundingMode); + return roundedValue.TryFormat(destination, out charsWritten, format, formatProvider); + } + + var (roundedNumerator, roundedDenominator) = Round(numerator, denominator, maxNbDecimals, DefaultMidpointRoundingMode); + if (roundedNumerator.IsZero) + { + return 0.TryFormat(destination, out charsWritten, format, formatProvider); + } + + var currencyFormatInfo = new NumberFormatInfo + { + NumberDecimalSeparator = formatProvider.CurrencyDecimalSeparator, + NumberGroupSeparator = formatProvider.CurrencyGroupSeparator, + NumberGroupSizes = formatProvider.CurrencyGroupSizes, + NativeDigits = formatProvider.NativeDigits, + DigitSubstitution = formatProvider.DigitSubstitution + }; + + if (roundedNumerator.Sign > 0) + { + if (!TryAppendLeadingSymbolsWithPositivePattern(destination, out charsWritten, formatProvider.CurrencySymbol, formatProvider.CurrencyPositivePattern)) + { + return false; + } + + if (!TryAppendDecimals(destination[charsWritten..], out var decimalsWritten, roundedNumerator, roundedDenominator, currencyFormatInfo, maxNbDecimals, "N0")) + { + return false; + } + + charsWritten += decimalsWritten; + if (!TryAppendTrailingSymbolsWithPositivePattern(destination[charsWritten..], out var trailingCharsWritten, formatProvider.CurrencySymbol, + formatProvider.CurrencyPositivePattern)) + { + return false; + } + + charsWritten += trailingCharsWritten; + } + else + { + if (!TryAppendLeadingSymbolsWithNegativePattern(destination, out charsWritten, formatProvider.CurrencySymbol, formatProvider.NegativeSign, + formatProvider.CurrencyNegativePattern)) + { + return false; + } + + roundedNumerator = -roundedNumerator; + if (!TryAppendDecimals(destination[charsWritten..], out var decimalsWritten, roundedNumerator, roundedDenominator, currencyFormatInfo, maxNbDecimals, "N0")) + { + return false; + } + + charsWritten += decimalsWritten; + if (!TryAppendTrailingSymbolsWithNegativePattern(destination[charsWritten..], out var trailingCharsWritten, formatProvider.CurrencySymbol, + formatProvider.NegativeSign, + formatProvider.CurrencyNegativePattern)) + { + return false; + } + + charsWritten += trailingCharsWritten; + } + + return true; + + static bool TryAppendLeadingSymbolsWithPositivePattern(Span destination, out int charsWritten, string currencySymbol, int pattern) + { + charsWritten = 0; + switch (pattern) + { + case 0: // $n + if (!currencySymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = currencySymbol.Length; + return true; + case 1: // n$ + return true; + case 2: // $ n + if (destination.Length < currencySymbol.Length + 1) + { + return false; + } + + currencySymbol.CopyTo(destination); + destination[currencySymbol.Length] = ' '; + charsWritten = currencySymbol.Length + 1; + return true; + default: // n $ + return true; + } + } + + static bool TryAppendTrailingSymbolsWithPositivePattern(Span destination, out int charsWritten, string currencySymbol, int pattern) + { + charsWritten = 0; + switch (pattern) + { + case 0: // $n + return true; + case 1: // n$ + if (!currencySymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = currencySymbol.Length; + return true; + case 2: // $ n + return true; + default: // n $ + if (destination.Length < currencySymbol.Length + 1) + { + return false; + } + + destination[0] = ' '; + currencySymbol.CopyTo(destination[1..]); + charsWritten = currencySymbol.Length + 1; + return true; + } + } + + static bool TryAppendLeadingSymbolsWithNegativePattern(Span destination, out int charsWritten, string currencySymbol, string negativeSignSymbol, int pattern) + { + charsWritten = 0; + switch (pattern) + { + case 0: // ($n) + if (destination.Length < currencySymbol.Length + 3) + { + return false; + } + + destination[0] = '('; + currencySymbol.CopyTo(destination[1..]); + charsWritten = currencySymbol.Length + 1; + return true; + case 1: // -$n + if (destination.Length < currencySymbol.Length + negativeSignSymbol.Length + 1) + { + return false; + } + + negativeSignSymbol.CopyTo(destination); + currencySymbol.CopyTo(destination[negativeSignSymbol.Length..]); + charsWritten = negativeSignSymbol.Length + currencySymbol.Length; + return true; + case 2: // $-n + if (destination.Length < currencySymbol.Length + negativeSignSymbol.Length + 1) + { + return false; + } + + currencySymbol.CopyTo(destination); + negativeSignSymbol.CopyTo(destination[currencySymbol.Length..]); + charsWritten = currencySymbol.Length + negativeSignSymbol.Length; + return true; + case 3: // $n- + if (destination.Length < currencySymbol.Length + negativeSignSymbol.Length + 1) + { + return false; + } + + currencySymbol.CopyTo(destination); + charsWritten = currencySymbol.Length; + return true; + case 4: // (n$) + if (destination.Length < currencySymbol.Length + 3) + { + return false; + } + + destination[0] = '('; + charsWritten = 1; + return true; + case 5: // -n$ + if (destination.Length < currencySymbol.Length + negativeSignSymbol.Length + 1) + { + return false; + } + + negativeSignSymbol.CopyTo(destination); + charsWritten = negativeSignSymbol.Length; + return true; + case 6: // n-$ + case 7: // n$- + return true; + case 8: // -n $ + if (destination.Length < currencySymbol.Length + negativeSignSymbol.Length + 2) + { + return false; + } + + negativeSignSymbol.CopyTo(destination); + charsWritten = negativeSignSymbol.Length; + return true; + case 9: // -$ n + if (destination.Length < negativeSignSymbol.Length + currencySymbol.Length + 2) + { + return false; + } + + negativeSignSymbol.CopyTo(destination); + currencySymbol.CopyTo(destination[negativeSignSymbol.Length..]); + destination[negativeSignSymbol.Length + currencySymbol.Length] = ' '; + charsWritten = negativeSignSymbol.Length + currencySymbol.Length + 1; + return true; + case 10: // n $- + return true; + case 11: // $ n- + if (destination.Length < currencySymbol.Length + negativeSignSymbol.Length + 2) + { + return false; + } + + currencySymbol.CopyTo(destination); + destination[currencySymbol.Length] = ' '; + charsWritten = currencySymbol.Length + 1; + return true; + case 12: // $ -n + if (destination.Length < currencySymbol.Length + negativeSignSymbol.Length + 2) + { + return false; + } + + currencySymbol.CopyTo(destination); + destination[currencySymbol.Length] = ' '; + negativeSignSymbol.CopyTo(destination[(currencySymbol.Length + 1)..]); + charsWritten = currencySymbol.Length + negativeSignSymbol.Length + 1; + return true; + case 13: // n- $ + return true; + case 14: // ($ n) + if (destination.Length < currencySymbol.Length + 4) + { + return false; + } + + destination[0] = '('; + currencySymbol.CopyTo(destination[1..]); + destination[currencySymbol.Length + 1] = ' '; + charsWritten = currencySymbol.Length + 2; + return true; + case 15: // (n $) + if (destination.Length < currencySymbol.Length + 4) + { + return false; + } + + destination[0] = '('; + charsWritten = 1; + return true; + default: // $- n + if (destination.Length < currencySymbol.Length + negativeSignSymbol.Length + 2) + { + return false; + } + + currencySymbol.CopyTo(destination); + negativeSignSymbol.CopyTo(destination[currencySymbol.Length..]); + destination[currencySymbol.Length + negativeSignSymbol.Length] = ' '; + charsWritten = currencySymbol.Length + negativeSignSymbol.Length + 1; + return true; + } + } + + static bool TryAppendTrailingSymbolsWithNegativePattern(Span destination, out int charsWritten, string currencySymbol, string negativeSignSymbol, int pattern) + { + charsWritten = 0; + switch (pattern) + { + case 0: // ($n) + if (destination.IsEmpty) + { + return false; + } + + destination[0] = ')'; + charsWritten = 1; + return true; + case 1: // -$n + return true; + case 2: // $-n + return true; + case 3: // $n- + if (!negativeSignSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = negativeSignSymbol.Length; + return true; + case 4: // (n$) + if (destination.Length < currencySymbol.Length + 1) + { + return false; + } + + currencySymbol.CopyTo(destination); + destination[currencySymbol.Length] = ')'; + charsWritten = currencySymbol.Length + 1; + return true; + case 5: // -n$ + if (!currencySymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = currencySymbol.Length; + return true; + case 6: // n-$ + if (destination.Length < negativeSignSymbol.Length + currencySymbol.Length) + { + return false; + } + + negativeSignSymbol.CopyTo(destination); + currencySymbol.CopyTo(destination[negativeSignSymbol.Length..]); + charsWritten = negativeSignSymbol.Length + currencySymbol.Length; + return true; + case 7: // n$- + if (destination.Length < currencySymbol.Length + negativeSignSymbol.Length) + { + return false; + } + + currencySymbol.CopyTo(destination); + negativeSignSymbol.CopyTo(destination[currencySymbol.Length..]); + charsWritten = currencySymbol.Length + negativeSignSymbol.Length; + return true; + case 8: // -n $ + if (destination.Length < currencySymbol.Length + 1) + { + return false; + } + + destination[0] = ' '; + currencySymbol.CopyTo(destination[1..]); + charsWritten = currencySymbol.Length + 1; + return true; + case 9: // -$ n + return true; + case 10: // n $- + if (destination.Length < 1 + currencySymbol.Length + negativeSignSymbol.Length) + { + return false; + } + + destination[0] = ' '; + currencySymbol.CopyTo(destination[1..]); + negativeSignSymbol.CopyTo(destination[(currencySymbol.Length + 1)..]); + charsWritten = 1 + currencySymbol.Length + negativeSignSymbol.Length; + return true; + case 11: // $ n- + if (!negativeSignSymbol.TryCopyTo(destination)) + { + return false; + } + + charsWritten = negativeSignSymbol.Length; + return true; + case 12: // $ -n + return true; + case 13: // n- $ + if (destination.Length < negativeSignSymbol.Length + 1 + currencySymbol.Length) + { + return false; + } + + negativeSignSymbol.CopyTo(destination); + destination[negativeSignSymbol.Length] = ' '; + currencySymbol.CopyTo(destination[(negativeSignSymbol.Length + 1)..]); + charsWritten = negativeSignSymbol.Length + 1 + currencySymbol.Length; + return true; + case 14: // ($ n) + if (destination.IsEmpty) + { + return false; + } + + destination[0] = ')'; + charsWritten = 1; + return true; + case 15: // (n $) + if (destination.Length < currencySymbol.Length + 2) + { + return false; + } + + destination[0] = ' '; + currencySymbol.CopyTo(destination[1..]); + destination[1 + currencySymbol.Length] = ')'; + charsWritten = 1 + currencySymbol.Length + 1; + return true; + default: // $- n + return true; + } + } + } + + /// + /// Exponential format specifier (E) + /// The exponential ("E") format specifier converts a number to a string of the form "-d.ddd…E+ddd" or "-d.ddd…e+ddd", + /// where each "d" indicates a digit (0-9). The string starts with a minus sign if the number is negative. Exactly one + /// digit always precedes the decimal point. + /// + /// + /// The precision specifier indicates the desired number of digits after the decimal point. If the precision specifier + /// is omitted, a default of six digits after the decimal point is used. + /// The case of the format specifier indicates whether to prefix the exponent with an "E" or an "e". The exponent + /// always consists of a plus or minus sign and a minimum of three digits. The exponent is padded with zeros to meet + /// this minimum, if required. + /// + private static string FormatWithScientificFormat(BigInteger numerator, BigInteger denominator, string format, NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.ToString(format, formatProvider); + } + + if (denominator.IsOne) + { + return numerator.ToString(format, formatProvider); + } + + if (!TryGetPrecisionDigits(format, DefaultScientificFormatPrecision, out var maxNbDecimals)) + { + // not a valid "E" format: assuming a custom format + return FormatWithCustomFormat(numerator, denominator, format, formatProvider); + } + + // worst case: -1.23E+123456 + var significantDigitsLength = maxNbDecimals + 1; + // assuming a maximum exponent equal to 10^999999 + var exponentDigitsLength = 1 + int.Max(formatProvider.NegativeSign.Length, formatProvider.PositiveSign.Length) + 6; + var maxLength = formatProvider.NegativeSign.Length + formatProvider.NumberDecimalSeparator.Length + significantDigitsLength + exponentDigitsLength; + + var buffer = maxLength <= StackLimit + ? stackalloc char[maxLength] // Use stack memory + : new char[maxLength]; // Use heap if needed + + TryFormatWithScientificFormat(buffer, out var charsWritten, numerator, denominator, formatProvider, maxNbDecimals, format[0]); + return new string(buffer[..charsWritten]); + } + + private static bool TryFormatWithScientificFormat(Span destination, out int charsWritten, BigInteger numerator, BigInteger denominator, ReadOnlySpan format, + NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.TryFormat(destination, out charsWritten, format, formatProvider); + } + + if (denominator.IsOne) + { + return numerator.TryFormat(destination, out charsWritten, format, formatProvider); + } + + if (!TryGetPrecisionDigits(format, DefaultScientificFormatPrecision, out var maxNbDecimals)) + { + // not a valid "E" format: assuming a custom format + return TryFormatWithCustomFormat(destination, out charsWritten, numerator, denominator, format, formatProvider); + } + + return TryFormatWithScientificFormat(destination, out charsWritten, numerator, denominator, formatProvider, maxNbDecimals, format[0]); + } + + private static bool TryFormatWithScientificFormat(Span destination, out int charsWritten, BigInteger numerator, BigInteger denominator, + NumberFormatInfo formatProvider, int maxNbDecimals, char exponentSymbol) + { + charsWritten = 0; + if (numerator.Sign < 0) + { + if (!formatProvider.NegativeSign.TryCopyTo(destination)) + { + return false; + } + + charsWritten += formatProvider.NegativeSign.Length; + numerator = -numerator; + } + + var exponent = GetExponentPower(numerator, denominator, out var exponentTerm); + var mantissa = exponent switch + { + 0 => Round(numerator, denominator, maxNbDecimals, DefaultMidpointRoundingMode), + > 0 => Round(numerator, denominator * exponentTerm, maxNbDecimals, DefaultMidpointRoundingMode), + _ => Round(numerator * exponentTerm, denominator, maxNbDecimals, DefaultMidpointRoundingMode) + }; + + if (mantissa.Denominator.IsOne) + { + Span formatSpan = stackalloc char[11]; // "F" + up to 10 digits + formatSpan[0] = 'F'; + maxNbDecimals.TryFormat(formatSpan[1..], out var formatCharsWritten, default, CultureInfo.InvariantCulture); + if (!mantissa.Numerator.TryFormat(destination[charsWritten..], out var written, formatSpan[..(formatCharsWritten + 1)], formatProvider)) + { + return false; + } + + charsWritten += written; + } + else + { + if (!TryAppendDecimals(destination[charsWritten..], out var written, mantissa.Numerator, mantissa.Denominator, formatProvider, maxNbDecimals, "F0")) + { + return false; + } + + charsWritten += written; + } + + if (charsWritten == destination.Length) + { + return false; + } + + destination[charsWritten] = exponentSymbol; + charsWritten++; + if (exponent >= 0) + { + if (!formatProvider.PositiveSign.TryCopyTo(destination[charsWritten..])) + { + return false; + } + + charsWritten += formatProvider.PositiveSign.Length; + } + + // note: for the standard numeric types this is fixed to "D3" (but we could go higher) + ReadOnlySpan exponentFormat = exponent < 1000 ? "D3" : Span.Empty; + if (!exponent.TryFormat(destination[charsWritten..], out var exponentCharsWritten, exponentFormat, formatProvider)) + { + return false; + } + + charsWritten += exponentCharsWritten; + return true; + } + + /// + /// The general ("G") format specifier converts a number to the more compact of either fixed-point or scientific + /// notation, depending on the type of the number and whether a precision specifier is present. + /// + /// + /// The precision specifier + /// defines the maximum number of significant digits that can appear in the result string. If the precision specifier + /// is omitted or zero, the type of the number determines the default precision. + /// + private static string FormatGeneral(BigInteger numerator, BigInteger denominator, string format, NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.ToString(format, formatProvider); + } + + if (!TryGetPrecisionDigits(format, DefaultGeneralFormatPrecision, out var maxNbDecimals)) + { + // not a valid "G" format: assuming a custom format + return FormatWithCustomFormat(numerator, denominator, format, formatProvider); + } + + if (maxNbDecimals == 0) + { + maxNbDecimals = DefaultGeneralFormatPrecision; + } + + // worst case: -1.23E+123456 + var significantDigitsLength = maxNbDecimals; + // assuming a maximum exponent equal to 10^999999 + var exponentDigitsLength = 1 + int.Max(formatProvider.NegativeSign.Length, formatProvider.PositiveSign.Length) + 6; + var maxLength = formatProvider.NegativeSign.Length + formatProvider.NumberDecimalSeparator.Length + significantDigitsLength + exponentDigitsLength; + + var buffer = maxLength <= StackLimit + ? stackalloc char[maxLength] // Use stack memory + : new char[maxLength]; // Use heap if needed + + TryFormatGeneral(buffer, out var charsWritten, numerator, denominator, formatProvider, maxNbDecimals, format[0] is 'g'); + return new string(buffer[..charsWritten]); + } + + private static bool TryFormatGeneral(Span destination, out int charsWritten, BigInteger numerator, BigInteger denominator, ReadOnlySpan format, + NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.TryFormat(destination, out charsWritten, format, formatProvider); + } + + if (!TryGetPrecisionDigits(format, DefaultGeneralFormatPrecision, out var maxNbDecimals)) + { + // not a valid "G" format: assuming a custom format + return TryFormatWithCustomFormat(destination, out charsWritten, numerator, denominator, format, formatProvider); + } + + if (maxNbDecimals == 0) + { + maxNbDecimals = DefaultGeneralFormatPrecision; + } + + return TryFormatGeneral(destination, out charsWritten, numerator, denominator, formatProvider, maxNbDecimals, format[0] == 'g'); + } + + private static bool TryFormatGeneral(Span destination, out int charsWritten, BigInteger numerator, BigInteger denominator, NumberFormatInfo formatProvider, + int maxNbDecimals, bool lowerCase) + { + charsWritten = 0; + if (numerator.Sign < 0) + { + if (!formatProvider.NegativeSign.TryCopyTo(destination)) + { + return false; + } + + charsWritten += formatProvider.NegativeSign.Length; + numerator = -numerator; + } + + var exponent = GetExponentPower(numerator, denominator, out var exponentTerm); + + if (exponent == maxNbDecimals - 1) + { + // integral result: both 123400 (1.234e5) and 123400.01 (1.234001e+005) result in "123400" with the "G6" format + var roundedValue = RoundToBigInteger(numerator, denominator, DefaultMidpointRoundingMode); + if (!roundedValue.TryFormat(destination[charsWritten..], out var written)) + { + return false; + } + + charsWritten += written; + return true; + } + + if (exponent > maxNbDecimals - 1) + { + // we are required to shorten down a number of the form 123400 (1.234E+05) + if (maxNbDecimals == 1) + { + var roundedValue = RoundToBigInteger(numerator, denominator * exponentTerm, DefaultMidpointRoundingMode); + if (!roundedValue.TryFormat(destination[charsWritten..], out var written)) + { + return false; + } + + charsWritten += written; + } + else + { + var mantissa = Round(numerator, denominator * exponentTerm, maxNbDecimals - 1, DefaultMidpointRoundingMode); + if (!TryAppendSignificantDecimals(destination[charsWritten..], out var written, mantissa, formatProvider, maxNbDecimals - 1, "F0")) + { + return false; + } + + charsWritten += written; + } + + if (!TryAppendExponentWithSignificantDigits(destination[charsWritten..], out var exponentCharsWritten, exponent, formatProvider, lowerCase ? 'e' : 'E')) + { + return false; + } + + charsWritten += exponentCharsWritten; + return true; + } + + if (exponent <= -5) + { + // the largest value would have the form: 1.23e-5 (0.0000123) + var mantissa = Round(numerator * exponentTerm, denominator, maxNbDecimals - 1, DefaultMidpointRoundingMode); + if (!TryAppendSignificantDecimals(destination[charsWritten..], out var written, mantissa, formatProvider, maxNbDecimals - 1, "F0")) + { + return false; + } + + charsWritten += written; + if (!TryAppendExponentWithSignificantDigits(destination[charsWritten..], out written, exponent, formatProvider, lowerCase ? 'e' : 'E')) + { + return false; + } + + charsWritten += written; + } + else + { + // the smallest value would have the form: 1.23e-4 (0.000123) + var roundedDecimal = Round(numerator, denominator, maxNbDecimals - exponent - 1, DefaultMidpointRoundingMode); + if (!TryAppendSignificantDecimals(destination[charsWritten..], out var written, roundedDecimal, formatProvider, maxNbDecimals - exponent - 1, "F0")) + { + return false; + } + + charsWritten += written; + } + + return true; + } + + /// + /// Formats a fraction as a string with a specified number of significant digits after the radix point. + /// + /// The numerator of the fraction. + /// The denominator of the fraction. + /// + /// The format string to use, which specifies the maximum number of digits after the radix point. + /// + /// An object that provides culture-specific formatting information. + /// + /// A string representation of the fraction, formatted with the specified number of significant digits after the + /// radix point. + /// + /// + /// The method determines the formatting style based on the magnitude of the fraction: + /// + /// + /// For values greater than 1e5, the fraction is formatted in scientific notation (e.g., 1.23e6 for 1230000). + /// + /// + /// For values less than or equal to 1e-4, the fraction is formatted in scientific notation (e.g., 1.23e-4 for + /// 0.000123). + /// + /// + /// For values between 1e-3 and 1e5, the fraction is formatted as a decimal number. + /// + /// + /// + private static string FormatWithSignificantDigitsAfterRadix(BigInteger numerator, BigInteger denominator, string format, NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.ToString(formatProvider); + } + + if (!TryGetPrecisionDigits(format, 2, out var maxDigitsAfterRadix)) + { + // not a valid "S" format: assuming a custom format + return FormatWithCustomFormat(numerator, denominator, format, formatProvider); + } + + // typical worst case: -1.23E+123456 + var significantDigitsLength = maxDigitsAfterRadix; + // assuming a maximum exponent equal to 10^999999 + var exponentDigitsLength = 1 + int.Max(formatProvider.NegativeSign.Length, formatProvider.PositiveSign.Length) + 6; + // worst case for grouping is "1_2_3_0_0_0" with every '_' representing a group separator (up to 9 characters) + var maxGroupsLength = 5 * formatProvider.NumberGroupSeparator.Length; + var maxLength = formatProvider.NegativeSign.Length + formatProvider.NumberDecimalSeparator.Length + significantDigitsLength + + int.Max(maxGroupsLength, exponentDigitsLength); // we can either have groups or an exponent + + var buffer = maxLength <= StackLimit + ? stackalloc char[maxLength] // Use stack memory + : new char[maxLength]; // Use heap if needed + + TryFormatWithSignificantDigitsAfterRadix(buffer, out var charsWritten, numerator, denominator, formatProvider, maxDigitsAfterRadix, format[0] is 's'); + return new string(buffer[..charsWritten]); + } + + private static bool TryFormatWithSignificantDigitsAfterRadix(Span destination, out int charsWritten, BigInteger numerator, BigInteger denominator, + ReadOnlySpan format, NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.TryFormat(destination, out charsWritten, default, formatProvider); + } + + if (!TryGetPrecisionDigits(format, 2, out var maxDigitsAfterRadix)) + { + // not a valid "S" format: assuming a custom format + return TryFormatWithCustomFormat(destination, out charsWritten, numerator, denominator, format, formatProvider); + } + + return TryFormatWithSignificantDigitsAfterRadix(destination, out charsWritten, numerator, denominator, formatProvider, maxDigitsAfterRadix, format[0] is 's'); + } + + private static bool TryFormatWithSignificantDigitsAfterRadix(Span destination, out int charsWritten, BigInteger numerator, BigInteger denominator, + NumberFormatInfo formatProvider, int maxDigitsAfterRadix, bool lowerCase) + { + charsWritten = 0; + if (numerator.Sign < 0) + { + if (!formatProvider.NegativeSign.TryCopyTo(destination)) + { + return false; + } + + charsWritten += formatProvider.NegativeSign.Length; + numerator = -numerator; + } + + const string quotientFormat = "N0"; + var exponent = GetExponentPower(numerator, denominator, out var exponentTerm); + QuantityValue mantissa; + switch (exponent) + { + case > 5: + { + // the smallest value would have the form: 1.23e6 (1230000) + mantissa = Round(numerator, denominator * exponentTerm, maxDigitsAfterRadix, DefaultMidpointRoundingMode); + if (!TryAppendSignificantDecimals(destination[charsWritten..], out var written, mantissa, formatProvider, maxDigitsAfterRadix, quotientFormat)) + { + return false; + } + + charsWritten += written; + if (!TryAppendExponentWithSignificantDigits(destination[charsWritten..], out written, exponent, formatProvider, lowerCase ? 'e' : 'E')) + { + return false; + } + + charsWritten += written; + return true; + } + case <= -4: + { + // the largest value would have the form: 1.23e-4 (0.000123) + mantissa = Round(numerator * exponentTerm, denominator, maxDigitsAfterRadix, DefaultMidpointRoundingMode); + if (!TryAppendSignificantDecimals(destination[charsWritten..], out var written, mantissa, formatProvider, maxDigitsAfterRadix, quotientFormat)) + { + return false; + } + + charsWritten += written; + if (!TryAppendExponentWithSignificantDigits(destination[charsWritten..], out written, exponent, formatProvider, lowerCase ? 'e' : 'E')) + { + return false; + } + + charsWritten += written; + return true; + } + case < 0: + { + // the smallest value would have the form: 1.23e-3 (0.00123) + var leadingZeroes = -exponent; + maxDigitsAfterRadix += leadingZeroes - 1; + mantissa = Round(numerator, denominator, maxDigitsAfterRadix, DefaultMidpointRoundingMode); + if (!TryAppendSignificantDecimals(destination[charsWritten..], out var written, mantissa, formatProvider, maxDigitsAfterRadix, quotientFormat)) + { + return false; + } + + charsWritten += written; + return true; + } + default: + { + // the largest value would have the form: 1.23e5 (123000) + mantissa = Round(numerator, denominator, maxDigitsAfterRadix, DefaultMidpointRoundingMode); + if (!TryAppendSignificantDecimals(destination[charsWritten..], out var written, mantissa, formatProvider, maxDigitsAfterRadix, quotientFormat)) + { + return false; + } + + charsWritten += written; + return true; + } + } + } + + private static string FormatWithCustomFormat(BigInteger numerator, BigInteger denominator, string format, NumberFormatInfo formatProvider) + { + return new QuantityValue(numerator, denominator).ToDouble().ToString(format, formatProvider); + } + + private static bool TryFormatWithCustomFormat(Span destination, out int charsWritten, BigInteger numerator, BigInteger denominator, ReadOnlySpan format, + NumberFormatInfo formatProvider) + { + return new QuantityValue(numerator, denominator).ToDouble().TryFormat(destination, out charsWritten, format, formatProvider); + } + + /// + /// Attempts to append the decimal representation of a fraction to the specified destination span. + /// + /// + /// The of characters to which the decimal representation will be appended. + /// + /// + /// When this method returns, contains the number of characters written to the . + /// + /// + /// The numerator of the fraction. + /// + /// + /// The denominator of the fraction. It should be a power of 10, corresponding to the specified + /// . + /// + /// + /// The that provides culture-specific formatting information. + /// + /// + /// The maximum number of decimal places to include in the representation. + /// + /// + /// An optional format string for formatting the quotient part of the fraction. Defaults to "F0". + /// + /// + /// true if the decimal representation was successfully appended to the ; + /// otherwise, false. + /// + /// + /// This method calculates the decimal representation of the given fraction by dividing the numerator + /// by the denominator and appending the result to the . It ensures that the specified + /// number of decimal places is respected by padding with "0" if necessary. + /// + /// The fraction must represent a value with a denominator that is a power of 10, corresponding to the specified + /// . + /// + /// + private static bool TryAppendDecimals(Span destination, out int charsWritten, BigInteger numerator, BigInteger denominator, NumberFormatInfo formatProvider, + int nbDecimals, ReadOnlySpan quotientFormat) + { + if (denominator <= long.MaxValue / 10 && numerator <= long.MaxValue && numerator >= long.MinValue) + { + return TryAppendDecimals(destination, out charsWritten, (long)numerator, (long)denominator, formatProvider, nbDecimals, quotientFormat); + } + + var quotient = BigInteger.DivRem(numerator, denominator, out var remainder); + + if (!quotient.TryFormat(destination, out charsWritten, quotientFormat, formatProvider)) + { + return false; + } + + if (!formatProvider.NumberDecimalSeparator.TryCopyTo(destination[charsWritten..])) + { + return false; + } + + charsWritten += formatProvider.NumberDecimalSeparator.Length; + + var decimalsAdded = 0; + while (!remainder.IsZero && decimalsAdded++ < nbDecimals - 1) + { + if (charsWritten == destination.Length) + { + return false; + } + + denominator = PreviousPowerOfTen(denominator, nbDecimals - decimalsAdded + 1); + var digit = (char)('0' + (int)BigInteger.DivRem(remainder, denominator, out remainder)); + destination[charsWritten] = digit; + charsWritten ++; + } + + if (remainder.IsZero) + { + var zerosRemaining = nbDecimals - decimalsAdded; + if (charsWritten + zerosRemaining > destination.Length) + { + return false; + } + + destination.Slice(charsWritten, zerosRemaining).Fill('0'); + charsWritten += zerosRemaining; + } + else if (charsWritten == destination.Length) + { + return false; + } + else + { + var digit = (char)('0' + (int)remainder); + destination[charsWritten] = digit; + charsWritten ++; + } + + return true; + } + + private static bool TryAppendDecimals(Span destination, out int charsWritten, long numerator, long denominator, NumberFormatInfo formatProvider, + int nbDecimals, ReadOnlySpan quotientFormat) + { + var (quotient, remainder) = long.DivRem(numerator, denominator); + + if (!quotient.TryFormat(destination, out charsWritten, quotientFormat, formatProvider)) + { + return false; + } + + if (!formatProvider.NumberDecimalSeparator.TryCopyTo(destination[charsWritten..])) + { + return false; + } + + charsWritten += formatProvider.NumberDecimalSeparator.Length; + + var decimalsAdded = 0; + while (remainder != 0 && decimalsAdded++ < nbDecimals) + { + if (charsWritten == destination.Length) + { + return false; + } + + (var digit, remainder) = long.DivRem(remainder * 10, denominator); + destination[charsWritten] = (char)(digit + '0'); + charsWritten++; + } + + if (remainder == 0) + { + var zerosRemaining = nbDecimals - decimalsAdded; + if (charsWritten + zerosRemaining > destination.Length) + { + return false; + } + + destination.Slice(charsWritten, zerosRemaining).Fill('0'); + charsWritten += zerosRemaining; + } + + return true; + } + + /// + /// Attempts to append the significant decimal digits of a fractional number to the specified destination span. + /// + /// + /// The of characters to which the significant decimal digits will be appended. + /// + /// + /// When this method returns, contains the number of characters written to the . + /// + /// + /// The fractional number whose significant decimal digits are to be appended. + /// The denominator of this fraction must be a power of 10, corresponding to the . + /// + /// + /// The that provides culture-specific formatting information. + /// + /// + /// The maximum number of decimal digits to append. + /// + /// + /// An optional format string that specifies the format of the quotient. + /// + /// + /// if the significant decimal digits were successfully appended; otherwise, + /// . + /// + /// + /// This method calculates and appends the significant decimal digits of the given fractional number. + /// It ensures that the number of appended decimal digits does not exceed the specified maximum. + /// + /// The must represent a value with a denominator that is a power of 10, + /// equal to the specified . + /// + /// + /// The method writes the quotient to the span using the specified + /// and appends the decimal separator followed by the significant decimal + /// digits. + /// + /// + private static bool TryAppendSignificantDecimals(Span destination, out int charsWritten, QuantityValue decimalFraction, NumberFormatInfo formatProvider, + int maxNbDecimals, ReadOnlySpan quotientFormat) + { + var numerator = decimalFraction.Numerator; + var denominator = decimalFraction.Denominator; + if (denominator <= long.MaxValue / 10 && numerator <= long.MaxValue && numerator >= long.MinValue) + { + return TryAppendSignificantDecimals(destination, out charsWritten, (long)numerator, (long)denominator, formatProvider, maxNbDecimals, quotientFormat); + } + + var quotient = BigInteger.DivRem(numerator, denominator, out var remainder); + + if (!quotient.TryFormat(destination, out charsWritten, quotientFormat, formatProvider)) + { + return false; + } + + if (remainder.IsZero) + { + return true; + } + + if (!formatProvider.NumberDecimalSeparator.TryCopyTo(destination[charsWritten..])) + { + return false; + } + + charsWritten += formatProvider.NumberDecimalSeparator.Length; + + var decimalsRemaining = maxNbDecimals; + do + { + if (charsWritten == destination.Length) + { + return false; + } + + denominator = PreviousPowerOfTen(denominator, decimalsRemaining); + var digit = (char)('0' + (int)BigInteger.DivRem(remainder, denominator, out remainder)); + destination[charsWritten] = digit; + charsWritten ++; + decimalsRemaining--; + } while (!remainder.IsZero && decimalsRemaining > 0); + + return true; + } + + private static bool TryAppendSignificantDecimals(Span destination, out int charsWritten, long numerator, long denominator, NumberFormatInfo formatProvider, + int maxNbDecimals, ReadOnlySpan quotientFormat) + { + var (quotient, remainder) = long.DivRem(numerator, denominator); + + if (!quotient.TryFormat(destination, out charsWritten, quotientFormat, formatProvider)) + { + return false; + } + + if (remainder == 0) + { + return true; + } + + if (!formatProvider.NumberDecimalSeparator.TryCopyTo(destination[charsWritten..])) + { + return false; + } + + charsWritten += formatProvider.NumberDecimalSeparator.Length; + + var decimalsRemaining = maxNbDecimals; + do + { + if (charsWritten == destination.Length) + { + return false; + } + + (var digit, remainder) = long.DivRem(remainder * 10, denominator); + destination[charsWritten++] = (char)(digit + '0'); + decimalsRemaining--; + } while (remainder != 0 && decimalsRemaining > 0); + + return true; + } + + private static bool TryAppendExponentWithSignificantDigits(Span destination, out int charsWritten, int exponent, + NumberFormatInfo formatProvider, char exponentSymbol) + { + charsWritten = 0; + if (destination.IsEmpty) + { + return false; + } + + destination[0] = exponentSymbol; + charsWritten++; + switch (exponent) + { + case <= -1000: + { + if (!exponent.TryFormat(destination[charsWritten..], out var written, default, formatProvider)) + { + return false; + } + + charsWritten += written; + return true; + } + case <= 0: + { + if (!exponent.TryFormat(destination[charsWritten..], out var written, "D2", formatProvider)) + { + return false; + } + + charsWritten += written; + return true; + } + } + + // exponent > 0 + if (!formatProvider.PositiveSign.TryCopyTo(destination[charsWritten..])) + { + return false; + } + + charsWritten += formatProvider.PositiveSign.Length; + ReadOnlySpan exponentFormat = exponent switch + { + < 100 => "D2", + < 1000 => "D3", + _ => Span.Empty + }; + + if (!exponent.TryFormat(destination[charsWritten..], out var exponentCharsWritten, exponentFormat, formatProvider)) + { + return false; + } + + charsWritten += exponentCharsWritten; + return true; + } + + /// + /// Calculates the exponent power for the given fraction terms. + /// + /// The numerator of the fraction. + /// The denominator of the fraction. + /// + /// Output parameter that returns the power of ten that corresponds to the calculated exponent + /// power. + /// + /// The exponent power for the given fraction. + /// It is expected that both terms have the same sign (i.e. the Fraction is positive) + private static int GetExponentPower(BigInteger numerator, BigInteger denominator, out BigInteger powerOfTen) + { + // Preconditions: numerator > 0, denominator > 0. + var numLen = numerator.GetBitLength(); + var denLen = denominator.GetBitLength(); + // If the two numbers have equal bit-length, then their ratio is in [1,2) if numerator >= denominator, + // or in (0,1) if numerator < denominator. In these cases the scientific exponent is fixed. + if (numLen == denLen) + { + if (numerator >= denominator) + { + powerOfTen = BigInteger.One; // 10^0 + return 0; + } + + // When numerator < denominator, ratio < 1, and normalization requires multiplying by 10 once. + powerOfTen = Ten; // 10^1, leading to an exponent of -1. + return -1; + } + + if (numLen > denLen) + { + // Case: number >= 1, so the scientific exponent is positive. + // The adjusted candidate uses (diffBits - 1) because an L-bit number is at least 2^(L-1). + var diffBits = numLen - denLen; + var exponent = (int)Math.Floor((diffBits - 1) * Log10Of2) + 1; + powerOfTen = PowerOfTen(exponent); + + // Adjustment: if our candidate powerOfTen is too high, + // then the quotient doesn't reach that many digits. + if (numerator >= denominator * powerOfTen) + { + return exponent; + } + + powerOfTen = PreviousPowerOfTen(powerOfTen, exponent); + return exponent - 1; + } + else + { + // Case: number < 1, so the scientific exponent is negative. + // We need the smallest k such that numerator * 10^k >= denominator. + var diffBits = denLen - numLen; + var exponent = (int)Math.Ceiling(diffBits * Log10Of2) - 1; + powerOfTen = PowerOfTen(exponent); + + // First, check if one fewer factor of Ten would suffice. + if (numerator * powerOfTen >= denominator) + { + return -exponent; + } + + // Select the next guess as 10^exponent + powerOfTen = NextPowerOfTen(powerOfTen, exponent++); + + // Then, check if our candidate is too low. + if (numerator * powerOfTen < denominator) + { + powerOfTen = NextPowerOfTen(powerOfTen, exponent++); + } + + // For numbers < 1, the scientific exponent is -k. + return -exponent; + } + } + + private static BigInteger PreviousPowerOfTen(BigInteger powerOfTen, int exponent) + { + return exponent <= PowersOfTen.Length ? PowersOfTen[exponent - 1] : powerOfTen / Ten; + } + + private static BigInteger NextPowerOfTen(BigInteger powerOfTen, int exponent) + { + return exponent + 1 < PowersOfTen.Length ? PowersOfTen[exponent + 1] : powerOfTen * Ten; + } + } + +#else + /// + /// Provides functionality to format the value of a QuantityValue object into a decimal string representation following + /// the + /// standard numeric formats, as implemented by the double type. + /// + private static class DecimalNotationFormatter + { + /// + /// + /// + /// On .NET Framework and .NET Core up to .NET Core 2.0, the runtime selects the result with the greater least + /// significant digit (that is, using ). + /// + /// + /// On .NET Core 2.1 and later, the runtime selects the result with an even least significant digit (that is, + /// using ). + /// + /// + /// + private const MidpointRounding DefaultMidpointRoundingMode = MidpointRounding.AwayFromZero; + + /// + /// The default precision used for the general format specifier (G) + /// + private const int DefaultGeneralFormatPrecision = +#if NETCOREAPP2_0_OR_GREATER + 16; +#else + 15; +#endif + + /// + /// The default precision used for the exponential (scientific) format specifier (E) + /// + private const int DefaultScientificFormatPrecision = 6; + + private static readonly double Log10Of2 = Math.Log10(2); + + + /// + /// Formats the value of the specified Fraction as a string using the specified format. + /// + /// A standard or custom numeric format string. + /// The Fraction object to be formatted. + /// An object that supplies culture-specific formatting information. + /// + /// The string representation of the value of the Fraction object as specified by the format and formatProvider + /// parameters. + /// + /// + /// This method supports the following format strings: + /// + /// + /// + /// + /// 'G' + /// or 'g' + /// + /// : General format. Example: 400/3 formatted with 'G2' gives "1.3E+02". + /// + /// + /// + /// + /// + /// 'F' + /// or 'f' + /// + /// : Fixed-point format. Example: 12345/10 formatted with 'F2' gives "1234.50". + /// + /// + /// + /// + /// + /// 'N' + /// or 'n' + /// + /// : Standard Numeric format. Example: 1234567/1000 formatted with 'N2' gives "1,234.57". + /// + /// + /// + /// + /// + /// 'E' + /// or 'e' + /// + /// : Scientific format. Example: 1234567/1000 formatted with 'E2' gives "1.23E+003". + /// + /// + /// + /// + /// + /// 'P' + /// or 'p' + /// + /// : Percent format. Example: 2/3 formatted with 'P2' gives "66.67 %". + /// + /// + /// + /// + /// + /// 'C' + /// or 'c' + /// + /// : Currency format. Example: 1234567/1000 formatted with 'C2' gives "$1,234.57". + /// + /// + /// + /// + /// + /// 'R' + /// or 'r' + /// + /// : Round-trip format. Example: 1234567/1000 formatted with 'R' gives "1234.567". + /// + /// + /// + /// + /// + /// 'S' + /// or 's' + /// + /// : Significant Digits After Radix format. Example: 400/3 formatted with 'S2' gives + /// "133.33". + /// + /// + /// + /// Note: The 'R' format and custom formats do not support precision specifiers and are handed over to the `double` + /// type for formatting, which may result in a loss of precision. + /// For more information about the formatter, see the + /// + /// DecimalNotationFormatter + /// section + /// + /// in the GitHub README. + /// + public static string Format(QuantityValue fraction, string? format, IFormatProvider? formatProvider) + { + formatProvider ??= CultureInfo.CurrentCulture; + var numberFormatInfo = (NumberFormatInfo)formatProvider.GetFormat(typeof(NumberFormatInfo))!; + + var numerator = fraction.Numerator; + var denominator = fraction.Denominator; + if (denominator.Sign == 0) + { + return numerator.Sign switch + { + 1 => numberFormatInfo.PositiveInfinitySymbol, + -1 => numberFormatInfo.NegativeInfinitySymbol, + _ => numberFormatInfo.NaNSymbol + }; + } + + if (string.IsNullOrEmpty(format)) + { + return FormatGeneral(numerator, denominator, "G", numberFormatInfo); + } + + var formatCharacter = format![0]; + return formatCharacter switch + { + 'G' or 'g' => FormatGeneral(numerator, denominator, format, numberFormatInfo), + 'F' or 'f' => FormatWithFixedPointFormat(numerator, denominator, format, numberFormatInfo), + 'N' or 'n' => FormatWithStandardNumericFormat(numerator, denominator, format, numberFormatInfo), + 'E' or 'e' => FormatWithScientificFormat(numerator, denominator, format, numberFormatInfo), + 'P' or 'p' => FormatWithPercentFormat(numerator, denominator, format, numberFormatInfo), + 'C' or 'c' => FormatWithCurrencyFormat(numerator, denominator, format, numberFormatInfo), + 'S' or 's' => FormatWithSignificantDigitsAfterRadix(numerator, denominator, format, numberFormatInfo), + _ => // 'R', 'r' and the custom formats are handed over to the double (possible loss of precision) + fraction.ToDouble().ToString(format, formatProvider) + }; + } + + private static bool TryGetPrecisionDigits(string format, int defaultPrecision, out int maxNbDecimals) + { + if (format.Length == 1) + { + // The number of digits is not specified, use default precision. + maxNbDecimals = defaultPrecision; + return true; + } + +#if NET + if (int.TryParse(format.AsSpan(1), out maxNbDecimals)) + { + return true; + } +#else + if (int.TryParse(format.Substring(1), out maxNbDecimals)) + { + return true; + } +#endif + + // Seems to be some kind of custom format we do not understand, fallback to default precision. + maxNbDecimals = defaultPrecision; + return false; + } + + /// + /// The fixed-point ("F") format specifier converts a number to a string of the form "-ddd.ddd…" where each "d" + /// indicates a digit (0-9). The string starts with a minus sign if the number is negative. + /// + /// + /// The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the + /// current property supplies the numeric precision. + /// + private static string FormatWithFixedPointFormat(BigInteger numerator, BigInteger denominator, string format, NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.ToString(format, formatProvider); + } + + if (denominator.IsOne) + { + return numerator.ToString(format, formatProvider)!; + } + + if (!TryGetPrecisionDigits(format, formatProvider.NumberDecimalDigits, out var maxNbDecimalsAfterRadix)) + { + // not a valid "F" format: assuming a custom format + return FormatWithCustomFormat(numerator, denominator, format, formatProvider); + } + + if (maxNbDecimalsAfterRadix == 0) + { + return RoundToBigInteger(numerator, denominator, DefaultMidpointRoundingMode).ToString(format, formatProvider)!; + } + + var (roundedNumerator, roundedDenominator) = Round(numerator, denominator, maxNbDecimalsAfterRadix, DefaultMidpointRoundingMode); + bool isPositive; + switch (roundedNumerator.Sign) + { + case 0: + return 0.ToString(format, formatProvider); + case 1: + isPositive = true; + break; + default: + isPositive = false; + roundedNumerator = -roundedNumerator; + break; + } + + var sb = new StringBuilder(12 + maxNbDecimalsAfterRadix); + if (!isPositive) + { + sb.Append(formatProvider.NegativeSign); + } + + return AppendDecimals(sb, roundedNumerator, roundedDenominator, formatProvider, maxNbDecimalsAfterRadix).ToString(); + } + + /// + /// The numeric ("N") format specifier converts a number to a string of the form "-d,ddd,ddd.ddd…", where "-" + /// indicates + /// a negative number symbol if required, "d" indicates a digit (0-9), "," indicates a group separator, and "." + /// indicates a decimal point symbol. + /// + /// + /// The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, the + /// current property supplies the numeric precision. + /// + private static string FormatWithStandardNumericFormat(BigInteger numerator, BigInteger denominator, string format, NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.ToString(format, formatProvider); + } + + if (denominator.IsOne) + { + return numerator.ToString(format, formatProvider)!; + } + + if (!TryGetPrecisionDigits(format, formatProvider.NumberDecimalDigits, out var maxNbDecimals)) + { + // not a valid "N" format: assuming a custom format + return FormatWithCustomFormat(numerator, denominator, format, formatProvider); + } + + if (maxNbDecimals == 0) + { + var roundedValue = RoundToBigInteger(numerator, denominator, DefaultMidpointRoundingMode); + return roundedValue.ToString(format, formatProvider)!; + } + + var (roundedNumerator, roundedDenominator) = Round(numerator, denominator, maxNbDecimals, DefaultMidpointRoundingMode); + bool isPositive; + switch (roundedNumerator.Sign) + { + case 0: + return 0.ToString(format, formatProvider); + case 1: + isPositive = true; + break; + default: + isPositive = false; + roundedNumerator = -roundedNumerator; + break; + } + + var sb = AppendDecimals(new StringBuilder(6 + maxNbDecimals), roundedNumerator, roundedDenominator, formatProvider, maxNbDecimals, "N0"); + return isPositive + ? sb.ToString() + : WithNegativeSign(sb, formatProvider.NegativeSign, formatProvider.NumberNegativePattern); + + static string WithNegativeSign(StringBuilder sb, string negativeSignSymbol, int pattern) + { + return pattern switch + { + 0 => // (n) + sb.Insert(0, '(').Append(')').ToString(), + 1 => // -n + sb.Insert(0, negativeSignSymbol).ToString(), + 2 => // - n + sb.Insert(0, negativeSignSymbol + ' ').ToString(), + 3 => // n- + sb.Append(negativeSignSymbol).ToString(), + _ => // n - + sb.Append(' ').Append(negativeSignSymbol).ToString() + }; + } + } + + /// + /// The percent ("P") format specifier multiplies a number by 100 and converts it to a string that represents a + /// percentage. + /// + /// + /// The precision specifier indicates the desired number of decimal places. If the precision specifier is omitted, + /// the default numeric precision supplied by the current property + /// is used. + /// + private static string FormatWithPercentFormat(BigInteger numerator, BigInteger denominator, string format, NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.ToString(format, formatProvider); + } + + if (denominator.IsOne) + { + return numerator.ToString(format, formatProvider)!; + } + + if (!TryGetPrecisionDigits(format, formatProvider.PercentDecimalDigits, out var maxNbDecimals)) + { + // not a valid "P" format: assuming a custom format + return FormatWithCustomFormat(numerator, denominator, format, formatProvider); + } + + StringBuilder sb; + bool isPositive; + if (maxNbDecimals == 0) + { + var roundedValue = RoundToBigInteger(numerator * 100, denominator, DefaultMidpointRoundingMode); + switch (roundedValue.Sign) + { + case 0: + return 0.ToString(format, formatProvider); + case 1: + isPositive = true; + break; + default: + isPositive = false; + roundedValue = -roundedValue; + break; + } + + var percentFormatInfo = new NumberFormatInfo + { + NumberDecimalSeparator = formatProvider.PercentDecimalSeparator, + NumberGroupSeparator = formatProvider.PercentGroupSeparator, + NumberGroupSizes = formatProvider.PercentGroupSizes, + NativeDigits = formatProvider.NativeDigits, + DigitSubstitution = formatProvider.DigitSubstitution + }; + sb = new StringBuilder(roundedValue.ToString("N0", percentFormatInfo)); + } + else + { + var (roundedNumerator, roundedDenominator) = Round(numerator * 100, denominator, maxNbDecimals, DefaultMidpointRoundingMode); + switch (roundedNumerator.Sign) + { + case 0: + return 0.ToString(format, formatProvider); + case 1: + isPositive = true; + break; + default: + isPositive = false; + roundedNumerator = -roundedNumerator; + break; + } + + var percentFormatInfo = new NumberFormatInfo + { + NumberDecimalSeparator = formatProvider.PercentDecimalSeparator, + NumberGroupSeparator = formatProvider.PercentGroupSeparator, + NumberGroupSizes = formatProvider.PercentGroupSizes, + NativeDigits = formatProvider.NativeDigits, + DigitSubstitution = formatProvider.DigitSubstitution + }; + sb = AppendDecimals(new StringBuilder(8 + maxNbDecimals), roundedNumerator, roundedDenominator, percentFormatInfo, maxNbDecimals, "N0"); + } + + return isPositive + ? WithPositiveSign(sb, formatProvider.PercentSymbol, formatProvider.PercentPositivePattern) + : WithNegativeSign(sb, formatProvider.PercentSymbol, formatProvider.NegativeSign, formatProvider.PercentNegativePattern); + + static string WithPositiveSign(StringBuilder sb, string percentSymbol, int pattern) + { + return pattern switch + { + 0 => // n % + sb.Append(' ').Append(percentSymbol).ToString(), + 1 => // n% + sb.Append(percentSymbol).ToString(), + 2 => // %n + sb.Insert(0, percentSymbol).ToString(), + _ => // % n + sb.Insert(0, percentSymbol + ' ').ToString() + }; + } + + static string WithNegativeSign(StringBuilder sb, string percentSymbol, string negativeSignSymbol, int pattern) + { + return pattern switch + { + 0 => // -n % + sb.Insert(0, negativeSignSymbol).Append(' ').Append(percentSymbol).ToString(), + 1 => // -n% + sb.Insert(0, negativeSignSymbol).Append(percentSymbol).ToString(), + 2 => // -%n + sb.Insert(0, negativeSignSymbol + percentSymbol).ToString(), + 3 => // %-n + sb.Insert(0, percentSymbol + negativeSignSymbol).ToString(), + 4 => // %n- + sb.Insert(0, percentSymbol).Append(negativeSignSymbol).ToString(), + 5 => // n-% + sb.Append(negativeSignSymbol).Append(percentSymbol).ToString(), + 6 => // n%- + sb.Append(percentSymbol).Append(negativeSignSymbol).ToString(), + 7 => // -% n + sb.Insert(0, negativeSignSymbol + percentSymbol + ' ').ToString(), + 8 => // n %- + sb.Append(' ').Append(percentSymbol).Append(negativeSignSymbol).ToString(), + 9 => // % n- + sb.Insert(0, percentSymbol + ' ').Append(negativeSignSymbol).ToString(), + 10 => // % -n + sb.Insert(0, percentSymbol + ' ').Insert(2, negativeSignSymbol).ToString(), + _ => // n- % + sb.Append(negativeSignSymbol).Append(' ').Append(percentSymbol).ToString() + }; + } + } + + + /// + /// The "C" (or currency) format specifier converts a number to a string that represents a currency amount. The + /// precision specifier indicates the desired number of decimal places in the result string. If the precision specifier + /// is omitted, the default precision is defined by the property. + /// + /// + /// If the value to be formatted has more than the specified or default number of decimal places, the fractional + /// value is rounded in the result string. If the value to the right of the number of specified decimal places is 5 or + /// greater, the last digit in the result string is rounded away from zero. + /// + private static string FormatWithCurrencyFormat(BigInteger numerator, BigInteger denominator, string format, NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.ToString(format, formatProvider); + } + + if (denominator.IsOne) + { + return numerator.ToString(format, formatProvider)!; + } + + if (!TryGetPrecisionDigits(format, formatProvider.CurrencyDecimalDigits, out var maxNbDecimals)) + { + // not a valid "C" format: assuming a custom format + return FormatWithCustomFormat(numerator, denominator, format, formatProvider); + } + + if (maxNbDecimals == 0) + { + var roundedValue = RoundToBigInteger(numerator, denominator, DefaultMidpointRoundingMode); + return roundedValue.ToString(format, formatProvider)!; + } + + var (roundedNumerator, roundedDenominator) = Round(numerator, denominator, maxNbDecimals, DefaultMidpointRoundingMode); + + bool isPositive; + switch (roundedNumerator.Sign) + { + case 0: + return 0.ToString(format, formatProvider); + case 1: + isPositive = true; + break; + default: + isPositive = false; + roundedNumerator = -roundedNumerator; + break; + } + + var currencyFormatInfo = new NumberFormatInfo + { + NumberDecimalSeparator = formatProvider.CurrencyDecimalSeparator, + NumberGroupSeparator = formatProvider.CurrencyGroupSeparator, + NumberGroupSizes = formatProvider.CurrencyGroupSizes, + NativeDigits = formatProvider.NativeDigits, + DigitSubstitution = formatProvider.DigitSubstitution + }; + + var sb = AppendDecimals(new StringBuilder(8 + maxNbDecimals), roundedNumerator, roundedDenominator, currencyFormatInfo, maxNbDecimals, "N0"); + return isPositive + ? WithPositiveSign(sb, formatProvider.CurrencySymbol, formatProvider.CurrencyPositivePattern) + : WithNegativeSign(sb, formatProvider.CurrencySymbol, formatProvider.NegativeSign, + formatProvider.CurrencyNegativePattern); + + static string WithPositiveSign(StringBuilder sb, string currencySymbol, int pattern) + { + return pattern switch + { + 0 => // $n + sb.Insert(0, currencySymbol).ToString(), + 1 => // n$ + sb.Append(currencySymbol).ToString(), + 2 => // $ n + sb.Insert(0, currencySymbol + ' ').ToString(), + _ => // n $ + sb.Append(' ').Append(currencySymbol).ToString() + }; + } + + static string WithNegativeSign(StringBuilder sb, string currencySymbol, string negativeSignSymbol, + int pattern) + { + return pattern switch + { + 0 => // ($n) + sb.Insert(0, '(').Insert(1, currencySymbol).Append(')').ToString(), + 1 => // -$n + sb.Insert(0, negativeSignSymbol + currencySymbol).ToString(), + 2 => // $-n + sb.Insert(0, currencySymbol + negativeSignSymbol).ToString(), + 3 => // $n- + sb.Insert(0, currencySymbol).Append(negativeSignSymbol).ToString(), + 4 => // (n$) + sb.Insert(0, '(').Append(currencySymbol).Append(')').ToString(), + 5 => // -n$ + sb.Insert(0, negativeSignSymbol).Append(currencySymbol).ToString(), + 6 => // n-$ + sb.Append(negativeSignSymbol).Append(currencySymbol).ToString(), + 7 => // n$- + sb.Append(currencySymbol).Append(negativeSignSymbol).ToString(), + 8 => // -n $ + sb.Insert(0, negativeSignSymbol).Append(' ').Append(currencySymbol).ToString(), + 9 => // -$ n + sb.Insert(0, negativeSignSymbol + currencySymbol + ' ').ToString(), + 10 => // n $- + sb.Append(' ').Append(currencySymbol).Append(negativeSignSymbol).ToString(), + 11 => // $ n- + sb.Insert(0, currencySymbol + ' ').Append(negativeSignSymbol).ToString(), + 12 => // $ -n + sb.Insert(0, currencySymbol + ' ' + negativeSignSymbol).ToString(), + 13 => // n- $ + sb.Append(negativeSignSymbol).Append(' ').Append(currencySymbol).ToString(), + 14 => // ($ n) + sb.Insert(0, '(').Insert(1, currencySymbol + ' ').Append(')').ToString(), +#if NETSTANDARD + _ => // (n $) + sb.Insert(0, '(').Append(' ').Append(currencySymbol).Append(')').ToString(), +#else + 15 => // (n $) + sb.Insert(0, '(').Append(' ').Append(currencySymbol).Append(')').ToString(), + _ => // $- n + sb.Insert(0, currencySymbol + negativeSignSymbol + ' ').ToString(), +#endif + }; + } + } + + /// + /// Exponential format specifier (E) + /// The exponential ("E") format specifier converts a number to a string of the form "-d.ddd…E+ddd" or "-d.ddd…e+ddd", + /// where each "d" indicates a digit (0-9). The string starts with a minus sign if the number is negative. Exactly one + /// digit always precedes the decimal point. + /// + /// + /// The precision specifier indicates the desired number of digits after the decimal point. If the precision specifier + /// is omitted, a default of six digits after the decimal point is used. + /// The case of the format specifier indicates whether to prefix the exponent with an "E" or an "e". The exponent + /// always consists of a plus or minus sign and a minimum of three digits. The exponent is padded with zeros to meet + /// this minimum, if required. + /// + private static string FormatWithScientificFormat(BigInteger numerator, BigInteger denominator, string format, NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.ToString(format, formatProvider); + } + + if (denominator.IsOne) + { + return numerator.ToString(format, formatProvider)!; + } + + if (!TryGetPrecisionDigits(format, DefaultScientificFormatPrecision, out var maxNbDecimals)) + { + // not a valid "E" format: assuming a custom format + return FormatWithCustomFormat(numerator, denominator, format, formatProvider); + } + + var sb = new StringBuilder(DefaultScientificFormatPrecision + maxNbDecimals); + + if (numerator.Sign < 0) + { + sb.Append(formatProvider.NegativeSign); + numerator = -numerator; + } + + var exponent = GetExponentPower(numerator, denominator, out var exponentTerm); + var mantissa = exponent switch + { + 0 => Round(numerator, denominator, maxNbDecimals, DefaultMidpointRoundingMode), + > 0 => Round(numerator, denominator * exponentTerm, maxNbDecimals, DefaultMidpointRoundingMode), + _ => Round(numerator * exponentTerm, denominator, maxNbDecimals, DefaultMidpointRoundingMode) + }; + + if (mantissa.Denominator.IsOne) + { + sb.Append(mantissa.Numerator.ToString($"F{maxNbDecimals}", formatProvider)); + } + else + { + AppendDecimals(sb, mantissa.Numerator, mantissa.Denominator, formatProvider, maxNbDecimals); + } + + return WithAppendedExponent(sb, exponent, formatProvider, format[0]); + + static string WithAppendedExponent(StringBuilder sb, int exponent, NumberFormatInfo numberFormat, + char exponentSymbol) + { + return exponent >= 0 + ? sb.Append(exponentSymbol).Append(numberFormat.PositiveSign) + .Append(exponent.ToString("D3", numberFormat)).ToString() + : sb.Append(exponentSymbol).Append(exponent.ToString("D3", numberFormat)).ToString(); + } + } + + /// + /// The general ("G") format specifier converts a number to the more compact of either fixed-point or scientific + /// notation, depending on the type of the number and whether a precision specifier is present. + /// + /// + /// The precision specifier + /// defines the maximum number of significant digits that can appear in the result string. If the precision specifier + /// is omitted or zero, the type of the number determines the default precision. + /// + private static string FormatGeneral(BigInteger numerator, BigInteger denominator, string format, NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.ToString(format, formatProvider); + } + + if (!TryGetPrecisionDigits(format, DefaultGeneralFormatPrecision, out var maxNbDecimals)) + { + // not a valid "G" format: assuming a custom format + return FormatWithCustomFormat(numerator, denominator, format, formatProvider); + } + + if (maxNbDecimals == 0) + { + maxNbDecimals = DefaultGeneralFormatPrecision; + } + + var sb = new StringBuilder(3 + maxNbDecimals); + + if (numerator.Sign < 0) + { + sb.Append(formatProvider.NegativeSign); + numerator = -numerator; + } + + var exponent = GetExponentPower(numerator, denominator, out var exponentTerm); + + if (exponent == maxNbDecimals - 1) + { + // integral result: both 123400 (1.234e5) and 123400.01 (1.234001e+005) result in "123400" with the "G6" format + return sb.Append(RoundToBigInteger(numerator, denominator, DefaultMidpointRoundingMode)).ToString(); + } + + if (exponent > maxNbDecimals - 1) + { + // we are required to shorten down a number of the form 123400 (1.234E+05) + if (maxNbDecimals == 1) + { + sb.Append(RoundToBigInteger(numerator, denominator * exponentTerm, DefaultMidpointRoundingMode)); + } + else + { + var mantissa = Round(numerator, denominator * exponentTerm, maxNbDecimals - 1, DefaultMidpointRoundingMode); + AppendSignificantDecimals(sb, mantissa, formatProvider, maxNbDecimals - 1); + } + + return AppendExponentWithSignificantDigits(sb, exponent, formatProvider, format[0] is 'g' ? 'e' : 'E').ToString(); + } + + if (exponent <= -5) + { + // the largest value would have the form: 1.23e-5 (0.0000123) + var mantissa = Round(numerator * exponentTerm, denominator, maxNbDecimals - 1, DefaultMidpointRoundingMode); + AppendSignificantDecimals(sb, mantissa, formatProvider, maxNbDecimals - 1); + return AppendExponentWithSignificantDigits(sb, exponent, formatProvider, format[0] is 'g' ? 'e' : 'E') + .ToString(); + } + + // the smallest value would have the form: 1.23e-4 (0.000123) + var roundedDecimal = Round(numerator, denominator, maxNbDecimals - exponent - 1, DefaultMidpointRoundingMode); + return AppendSignificantDecimals(sb, roundedDecimal, formatProvider, maxNbDecimals - exponent - 1) + .ToString(); + } + + private static string FormatWithCustomFormat(BigInteger numerator, BigInteger denominator, string format, NumberFormatInfo formatProvider) + { + return new QuantityValue(numerator, denominator).ToDouble().ToString(format, formatProvider); + } + + /// + /// Formats a fraction as a string with a specified number of significant digits after the radix point. + /// + /// The numerator of the fraction. + /// The denominator of the fraction. + /// + /// The format string to use, which specifies the maximum number of digits after the radix point. + /// + /// An object that provides culture-specific formatting information. + /// + /// A string representation of the fraction, formatted with the specified number of significant digits after the + /// radix point. + /// + /// + /// The method determines the formatting style based on the magnitude of the fraction: + /// + /// + /// For values greater than 1e5, the fraction is formatted in scientific notation (e.g., 1.23e6 for 1230000). + /// + /// + /// For values less than or equal to 1e-4, the fraction is formatted in scientific notation (e.g., 1.23e-4 for + /// 0.000123). + /// + /// + /// For values between 1e-3 and 1e5, the fraction is formatted as a decimal number. + /// + /// + /// + private static string FormatWithSignificantDigitsAfterRadix(BigInteger numerator, BigInteger denominator, string format, NumberFormatInfo formatProvider) + { + if (numerator.IsZero) + { + return 0.ToString(formatProvider); + } + + const string quotientFormat = "N0"; + + if (!TryGetPrecisionDigits(format, 2, out var maxDigitsAfterRadix)) + { + // not a valid "S" format: assuming a custom format + return FormatWithCustomFormat(numerator, denominator, format, formatProvider); + } + + var sb = new StringBuilder(3 + maxDigitsAfterRadix); + + if (numerator.Sign < 0) + { + sb.Append(formatProvider.NegativeSign); + numerator = -numerator; + } + + var exponent = GetExponentPower(numerator, denominator, out var exponentTerm); + QuantityValue mantissa; + switch (exponent) + { + case > 5: + // the smallest value would have the form: 1.23e6 (1230000) + mantissa = Round(numerator, denominator * exponentTerm, maxDigitsAfterRadix, DefaultMidpointRoundingMode); + AppendSignificantDecimals(sb, mantissa, formatProvider, maxDigitsAfterRadix, quotientFormat); + return AppendExponentWithSignificantDigits(sb, exponent, formatProvider, format[0] is 's' ? 'e' : 'E') + .ToString(); + case <= -4: + // the largest value would have the form: 1.23e-4 (0.000123) + mantissa = Round(numerator * exponentTerm, denominator, maxDigitsAfterRadix, DefaultMidpointRoundingMode); + AppendSignificantDecimals(sb, mantissa, formatProvider, maxDigitsAfterRadix, quotientFormat); + return AppendExponentWithSignificantDigits(sb, exponent, formatProvider, format[0] is 's' ? 'e' : 'E') + .ToString(); + case < 0: + // the smallest value would have the form: 1.23e-3 (0.00123) + var leadingZeroes = -exponent; + maxDigitsAfterRadix += leadingZeroes - 1; + mantissa = Round(numerator, denominator, maxDigitsAfterRadix, DefaultMidpointRoundingMode); + return AppendSignificantDecimals(sb, mantissa, formatProvider, maxDigitsAfterRadix, quotientFormat) + .ToString(); + default: + // the largest value would have the form: 1.23e5 (123000) + mantissa = Round(numerator, denominator, maxDigitsAfterRadix, DefaultMidpointRoundingMode); + return AppendSignificantDecimals(sb, mantissa, formatProvider, maxDigitsAfterRadix, quotientFormat) + .ToString(); + } + } + + /// + /// Appends the decimal representation of a fraction to the specified . + /// + /// The to which the decimal representation will be appended. + /// The numerator of the fraction. + /// + /// The denominator of the fraction: should be a power of 10, equal to the specified + /// + /// + /// The that provides culture-specific formatting information. + /// The maximum number of decimal places to include in the representation. + /// + /// An optional format string for formatting the quotient part of the fraction. + /// Defaults to "F0". + /// + /// The with the appended decimal representation. + /// + /// This method calculates the decimal representation of the given fraction by dividing the numerator + /// by the denominator and appending the result to the , padding with "0" to ensure the specified + /// number of decimal places is respected. + /// + /// The fraction must represent a value with a denominator that is a power of 10, equal to the specified + /// . + /// + /// + private static StringBuilder AppendDecimals(StringBuilder sb, BigInteger numerator, BigInteger denominator, NumberFormatInfo formatProvider, + int nbDecimals, string quotientFormat = "F0") + { + if (denominator <= long.MaxValue / 10 && numerator <= long.MaxValue && numerator >= long.MinValue) + { + return AppendDecimals(sb, (long)numerator, (long)denominator, formatProvider, nbDecimals, quotientFormat); + } + + var quotient = BigInteger.DivRem(numerator, denominator, out var remainder); + + sb.Append(quotient.ToString(quotientFormat, formatProvider)).Append(formatProvider.NumberDecimalSeparator); + + var decimalsAdded = 0; + while (!remainder.IsZero && decimalsAdded++ < nbDecimals - 1) + { + denominator = PreviousPowerOfTen(denominator, nbDecimals - decimalsAdded + 1); + var digit = (char)('0' + (int)BigInteger.DivRem(remainder, denominator, out remainder)); + sb.Append(digit); + } + + if (remainder.IsZero) + { + sb.Append('0', nbDecimals - decimalsAdded); + } + else + { + sb.Append((char)('0' + (int)remainder)); + } + + return sb; + } + + private static StringBuilder AppendDecimals(StringBuilder sb, long numerator, long denominator, NumberFormatInfo formatProvider, + int nbDecimals, string quotientFormat = "F0") + { + var quotient = numerator / denominator; + var remainder = numerator % denominator; + + sb.Append(quotient.ToString(quotientFormat, formatProvider)).Append(formatProvider.NumberDecimalSeparator); + + var decimalsAdded = 0; + while (remainder != 0 && decimalsAdded++ < nbDecimals) + { + sb.Append((char)('0' + remainder * 10 / denominator)); + remainder = remainder * 10 % denominator; + } + + if (remainder == 0) + { + sb.Append('0', nbDecimals - decimalsAdded); + } + + return sb; + } + + /// + /// Appends the significant decimal digits of a fractional number to the specified . + /// + /// The to which the significant decimal digits will be appended. + /// + /// The fractional number whose significant decimal digits are to be appended. + /// The denominator of this fraction must be a power of 10, corresponding to the . + /// + /// The that provides culture-specific formatting information. + /// The maximum number of decimal digits to append. + /// + /// An optional format string that specifies the format of the quotient. Defaults to "F0". + /// + /// + /// The instance with the appended significant decimal digits. + /// + /// + /// This method calculates and appends the significant decimal digits of the given fractional number. + /// It ensures that the number of appended decimal digits does not exceed the specified maximum. + /// + /// The must represent a value with a denominator that is a power of 10, + /// equal to the specified . + /// + /// + private static StringBuilder AppendSignificantDecimals(StringBuilder sb, QuantityValue decimalFraction, NumberFormatInfo formatProvider, + int maxNbDecimals, string quotientFormat = "F0") + { + var numerator = decimalFraction.Numerator; + var denominator = decimalFraction.Denominator; + if (denominator <= long.MaxValue / 10 && numerator <= long.MaxValue && numerator >= long.MinValue) + { + return AppendSignificantDecimals(sb, (long)numerator, (long)denominator, formatProvider, maxNbDecimals, quotientFormat); + } + + var quotient = BigInteger.DivRem(numerator, denominator, out var remainder); + + sb.Append(quotient.ToString(quotientFormat, formatProvider)); + + if (remainder.IsZero) + { + return sb; + } + + sb.Append(formatProvider.NumberDecimalSeparator); + + var decimalsRemaining = maxNbDecimals; + do + { + denominator = PreviousPowerOfTen(denominator, decimalsRemaining); + var digit = (char)('0' + (int)BigInteger.DivRem(remainder, denominator, out remainder)); + sb.Append(digit); + decimalsRemaining--; + } while (!remainder.IsZero && decimalsRemaining > 0); + + return sb; + } + + private static StringBuilder AppendSignificantDecimals(StringBuilder sb, long numerator, long denominator, NumberFormatInfo formatProvider, + int maxNbDecimals, string quotientFormat = "F0") + { + var quotient = numerator / denominator; + var remainder = numerator % denominator; + + sb.Append(quotient.ToString(quotientFormat, formatProvider)); + + if (remainder == 0) + { + return sb; + } + + sb.Append(formatProvider.NumberDecimalSeparator); + + var decimalsRemaining = maxNbDecimals; + do + { + sb.Append((char)('0' + remainder * 10 / denominator)); + remainder = remainder * 10 % denominator; + decimalsRemaining--; + } while (remainder != 0 && decimalsRemaining > 0); + + return sb; + } + + private static StringBuilder AppendExponentWithSignificantDigits(StringBuilder sb, int exponent, NumberFormatInfo formatProvider, char exponentSymbol) + { + return exponent switch + { + <= -1000 => sb.Append(exponentSymbol).Append(exponent.ToString(formatProvider)), + <= 0 => sb.Append(exponentSymbol).Append(exponent.ToString("D2", formatProvider)), + < 100 => sb.Append(exponentSymbol).Append(formatProvider.PositiveSign) + .Append(exponent.ToString("D2", formatProvider)), + < 1000 => sb.Append(exponentSymbol).Append(formatProvider.PositiveSign) + .Append(exponent.ToString("D3", formatProvider)), + _ => sb.Append(exponentSymbol).Append(formatProvider.PositiveSign).Append(exponent.ToString(formatProvider)) + }; + } + + /// + /// Calculates the exponent power for the given fraction terms. + /// + /// The numerator of the fraction. + /// The denominator of the fraction. + /// + /// Output parameter that returns the power of ten that corresponds to the calculated exponent + /// power. + /// + /// The exponent power for the given fraction. + /// It is expected that both terms have the same sign (i.e. the Fraction is positive) + private static int GetExponentPower(BigInteger numerator, BigInteger denominator, out BigInteger powerOfTen) + { + // Preconditions: numerator > 0, denominator > 0. +#if NET + var numLen = numerator.GetBitLength(); + var denLen = denominator.GetBitLength(); +#else + var numLen = GetBitLength(numerator); + var denLen = GetBitLength(denominator); +#endif + // If the two numbers have equal bit-length, then their ratio is in [1,2) if numerator >= denominator, + // or in (0,1) if numerator < denominator. In these cases the scientific exponent is fixed. + if (numLen == denLen) + { + if (numerator >= denominator) + { + powerOfTen = BigInteger.One; // 10^0 + return 0; + } + + // When numerator < denominator, ratio < 1, and normalization requires multiplying by 10 once. + powerOfTen = Ten; // 10^1, leading to an exponent of -1. + return -1; + } + + if (numLen > denLen) + { + // Case: number >= 1, so the scientific exponent is positive. + // The adjusted candidate uses (diffBits - 1) because an L-bit number is at least 2^(L-1). + var diffBits = numLen - denLen; + var exponent = (int)Math.Floor((diffBits - 1) * Log10Of2) + 1; + powerOfTen = PowerOfTen(exponent); + + // Adjustment: if our candidate powerOfTen is too high, + // then the quotient doesn't reach that many digits. + if (numerator >= denominator * powerOfTen) + { + return exponent; + } + + powerOfTen = PreviousPowerOfTen(powerOfTen, exponent); + return exponent - 1; + } + else + { + // Case: number < 1, so the scientific exponent is negative. + // We need the smallest k such that numerator * 10^k >= denominator. + var diffBits = denLen - numLen; + var exponent = (int)Math.Ceiling(diffBits * Log10Of2) - 1; + powerOfTen = PowerOfTen(exponent); + + // First, check if one fewer factor of Ten would suffice. + if (numerator * powerOfTen >= denominator) + { + return -exponent; + } + + // Select the next guess as 10^exponent + powerOfTen = NextPowerOfTen(powerOfTen, exponent++); + + // Then, check if our candidate is too low. + if (numerator * powerOfTen < denominator) + { + powerOfTen = NextPowerOfTen(powerOfTen, exponent++); + } + + // For numbers < 1, the scientific exponent is -k. + return -exponent; + } + +#if NETSTANDARD + static long GetBitLength(BigInteger value) + { + // Using BigInteger.Log(value, 2) avoids creating a byte array. + // Note: For value > 0 this returns a double that we floor and add 1. + return (long)Math.Floor(BigInteger.Log(value, 2)) + 1; + } +#endif + } + + private static BigInteger PreviousPowerOfTen(BigInteger powerOfTen, int exponent) + { + return exponent <= PowersOfTen.Length ? PowersOfTen[exponent - 1] : powerOfTen / Ten; + } + + private static BigInteger NextPowerOfTen(BigInteger powerOfTen, int exponent) + { + return exponent + 1 < PowersOfTen.Length ? PowersOfTen[exponent + 1] : powerOfTen * Ten; + } + } + + +#endif +} diff --git a/UnitsNet/CustomCode/Value/QuantityValue.ConvertToType.cs b/UnitsNet/CustomCode/Value/QuantityValue.ConvertToType.cs new file mode 100644 index 0000000000..6f486c7bb0 --- /dev/null +++ b/UnitsNet/CustomCode/Value/QuantityValue.ConvertToType.cs @@ -0,0 +1,156 @@ +// 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. + +namespace UnitsNet; + +public partial struct QuantityValue +{ + #region Implementation of IConvertible + + TypeCode IConvertible.GetTypeCode() + { + return TypeCode.Object; + } + + bool IConvertible.ToBoolean(IFormatProvider? provider) + { + throw ExceptionHelper.CreateInvalidCastException(); + } + + byte IConvertible.ToByte(IFormatProvider? provider) + { + return (byte)this; + } + + char IConvertible.ToChar(IFormatProvider? provider) + { + throw ExceptionHelper.CreateInvalidCastException(); + } + + DateTime IConvertible.ToDateTime(IFormatProvider? provider) + { + throw ExceptionHelper.CreateInvalidCastException(); + } + + decimal IConvertible.ToDecimal(IFormatProvider? provider) + { + return ToDecimal(); + } + + double IConvertible.ToDouble(IFormatProvider? provider) + { + return ToDouble(); + } + + short IConvertible.ToInt16(IFormatProvider? provider) + { + return (short)this; + } + + int IConvertible.ToInt32(IFormatProvider? provider) + { + return (int)this; + } + + long IConvertible.ToInt64(IFormatProvider? provider) + { + return (long)this; + } + + sbyte IConvertible.ToSByte(IFormatProvider? provider) + { + return (sbyte)this; + } + + float IConvertible.ToSingle(IFormatProvider? provider) + { + return (float)this; + } + + ushort IConvertible.ToUInt16(IFormatProvider? provider) + { + return (ushort)this; + } + + uint IConvertible.ToUInt32(IFormatProvider? provider) + { + return (uint)this; + } + + ulong IConvertible.ToUInt64(IFormatProvider? provider) + { + return (ulong)this; + } + + object IConvertible.ToType(Type conversionType, IFormatProvider? provider) + { + if (conversionType == null) + { + throw new ArgumentNullException(nameof(conversionType)); + } + + if (conversionType == typeof(string)) + { + return ToString(provider); + } + + if (conversionType == typeof(double)) + { + return ToDouble(); + } + + if (conversionType == typeof(decimal)) + { + return ToDecimal(); + } + + if (conversionType == typeof(float)) + { + return (float)this; + } + + if (conversionType == typeof(long)) + { + return (long)this; + } + + if (conversionType == typeof(ulong)) + { + return (ulong)this; + } + + if (conversionType == typeof(int)) + { + return (int)this; + } + + if (conversionType == typeof(uint)) + { + return (uint)this; + } + + if (conversionType == typeof(short)) + { + return (short)this; + } + + if (conversionType == typeof(ushort)) + { + return (ushort)this; + } + + if (conversionType == typeof(byte)) + { + return (byte)this; + } + + if (conversionType == typeof(sbyte)) + { + return (sbyte)this; + } + + throw ExceptionHelper.CreateInvalidCastException(conversionType); + } + + #endregion +} diff --git a/UnitsNet/CustomCode/Value/QuantityValue.DebugView.cs b/UnitsNet/CustomCode/Value/QuantityValue.DebugView.cs new file mode 100644 index 0000000000..71ac038312 --- /dev/null +++ b/UnitsNet/CustomCode/Value/QuantityValue.DebugView.cs @@ -0,0 +1,48 @@ +using System.Diagnostics; +using System.Numerics; + +namespace UnitsNet; + +public partial struct QuantityValue +{ + internal readonly struct QuantityValueDebugView(QuantityValue value) + { + public BigInteger A => value.Numerator; + public BigInteger B => value.Denominator; + public bool IsReduced => A.IsZero || B.IsZero || BigInteger.GreatestCommonDivisor(A, B).IsOne; +#if NET + public long NbBits => A.GetBitLength() + B.GetBitLength(); +#else + public long NbBits => (A.IsZero ? 0 : (int)BigInteger.Log(BigInteger.Abs(A), 2) + 1) + + (B.IsZero ? 0 : (int)(BigInteger.Log(B, 2) + 1)); +#endif + public StringFormatsView StringFormats => new(value); + public NumericFormatsView ValueFormats => new(value); + + [DebuggerDisplay("{ShortFormat}")] + internal readonly struct StringFormatsView(QuantityValue value) + { + public string GeneralFormat => value.ToString("G"); + + public string ShortFormat => value.ToString("S"); + + public string SimplifiedFraction + { + get + { + var (numerator, denominator) = Reduce(value); + return $"{numerator}/{denominator}"; + } + } + } + + [DebuggerDisplay("{Double}")] + internal readonly struct NumericFormatsView(QuantityValue value) + { + public int Integer => (int)value; + public long Long => (long)value; + public decimal Decimal => value.ToDecimal(); + public double Double => value.ToDouble(); + } + } +} \ No newline at end of file diff --git a/UnitsNet/CustomCode/Value/QuantityValue.Equality.cs b/UnitsNet/CustomCode/Value/QuantityValue.Equality.cs new file mode 100644 index 0000000000..727d8bdb7d --- /dev/null +++ b/UnitsNet/CustomCode/Value/QuantityValue.Equality.cs @@ -0,0 +1,200 @@ +// 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.Numerics; +using System.Runtime.CompilerServices; + +namespace UnitsNet; + +public partial struct QuantityValue +{ + /// + /// Determines whether this QuantityValue instance is equal to another QuantityValue instance. + /// + /// The QuantityValue to compare with this instance. + /// True if the two QuantityValue instances are equal, false otherwise. + public bool Equals(QuantityValue other) + { + var numerator1 = Numerator; + var denominator1 = Denominator; + var numerator2 = other.Numerator; + var denominator2 = other.Denominator; + + if (denominator1 == denominator2) + { + return denominator1.IsZero + ? numerator1.Sign == numerator2.Sign // both fractions represent infinities + : numerator1 == numerator2; + } + + if (denominator1.IsZero || denominator2.IsZero) + { + // either x or y is NaN or infinity. + return false; + } + + if (numerator1.IsZero) + { + return numerator2.IsZero; // if TRUE, both values are 0 + } + + if (numerator2.IsZero) + { + return false; + } + + var firstNumeratorSign = numerator1.Sign; + var secondNumeratorSign = numerator2.Sign; + if (firstNumeratorSign != secondNumeratorSign) + { + return false; // different signs + } + + // both values are non-zero fractions with different denominators + if (denominator1 < denominator2) + { + // reverse the comparison from x == y to y == x + Swap(ref numerator1, ref numerator2); + Swap(ref denominator1, ref denominator2); + } + + // from here [denominator1 > denominator2 > 0] applies + if (firstNumeratorSign == 1) + { + // both fractions are greater than 0 (positive) + + // After the swap, [numerator1 > numerator2 > 0] is expected if both fractions were equal. + // example: {10/10} and {1/1} or {10/100} and {1/10} + if (numerator1 <= numerator2) + { + return false; + } + + if (numerator2.IsOne) + { + return denominator2.IsOne + ? numerator1 == denominator1 // if equal, then {n/n} == {1/1} + : numerator1 * denominator2 == denominator1; // if equal, then {a/(a*b)} == {1/b} + } + } + else + { + // both fractions are less than 0 (negative) + + // After the swap, [numerator1 < numerator2 < 0] is expected if both fractions were equal. + // example: {-10/10} and {-1/1} or {-10/100} and {-1/10} + if (numerator1 >= numerator2) + { + return false; + } + + if (numerator2 == BigInteger.MinusOne) + { + return denominator2.IsOne + ? numerator1 == -denominator1 // if equal, then {-a/a} == {-1/1} + : numerator1 * -denominator2 == denominator1; // if equal, then {a/(a*-b)} == {-1/b} + } + } + + if (denominator2.IsOne) + { + return numerator1 == numerator2 * denominator1; // if equal, then {(b*a)/a} == {b/1} + } + + /* + * The following algorithm checks whether both fractions have the same ratio between numerator and denominator. + * + * Assumed that + * x = {n1/d1} + * y = {n2/d2} + * + * If x / y == 1 then x == y. + * + * This gives us: + * {n1/d1} / {n2/d2} == {(n1*d2) / (d1*n2)} == {n1/n2} / {d2/d1} + * + * If both fractions are equal their ratio is exactly 1: + * {n1/n2} / {d2/d1} == 1 + * And from this it follows: + * {n1/n2} == {d1/d2} + */ + + var numeratorQuotient = BigInteger.DivRem(numerator1, numerator2, out var remainderNumerators); + var denominatorQuotient = BigInteger.DivRem(denominator1, denominator2, out var remainderDenominators); + + // If the fractions are equal: numeratorQuotient should be equal to denominatorQuotient. + if (numeratorQuotient != denominatorQuotient) + { + return false; + } + + // if the fractions are equal: {remainderNumerators / numerator2} should be equal to {remainderDenominators / denominator2} + if (remainderDenominators.IsZero) + { + return remainderNumerators.IsZero; // if equal, then both values must be 0 + } + + if (remainderNumerators.IsZero) + { + return false; // if equal, then both values must be 0 + } + + /* + * Since the decimal places disappear when dividing integer data types, the formula must be converted into a multiplication: + * {rN / n2} == {rD / d2} + * can be written as: + * (rN * d2) == (rD * n2) + */ + return remainderNumerators * denominator2 == remainderDenominators * numerator2; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + private static void Swap(ref BigInteger a, ref BigInteger b) + { + (a, b) = (b, a); + } + + /// + /// Determines whether this QuantityValue instance is equal to another object. + /// + /// The object to compare with this instance. + /// True if the object is a QuantityValue instance and is equal to this instance, false otherwise. + public override bool Equals(object? obj) + { + return obj is QuantityValue other && Equals(other); + } + + /// + /// Returns the hash code for this QuantityValue instance. + /// + /// The hash code. + public override int GetHashCode() + { + var fraction = Reduce(this); + unchecked { + return (fraction.Denominator.GetHashCode() * 397) ^ fraction.Numerator.GetHashCode(); + } + } + + /// + /// Compares two QuantityValue instances for equality. + /// + /// The first QuantityValue. + /// The second QuantityValue. + /// True if the two QuantityValue instances are equal, false otherwise. + public static bool operator ==(QuantityValue a, QuantityValue b) + { + return a.Equals(b) && !IsNaN(a) && !IsNaN(b); + } + + /// + /// Compares two QuantityValue instances for inequality. + /// + /// The first QuantityValue. + /// The second QuantityValue. + /// True if the two QuantityValue instances are not equal, false otherwise. + public static bool operator !=(QuantityValue a, QuantityValue b) + { + return !a.Equals(b) || IsNaN(a) || IsNaN(b); + } +} \ No newline at end of file diff --git a/UnitsNet/CustomCode/Value/QuantityValue.Fraction.cs b/UnitsNet/CustomCode/Value/QuantityValue.Fraction.cs new file mode 100644 index 0000000000..c8b0075def --- /dev/null +++ b/UnitsNet/CustomCode/Value/QuantityValue.Fraction.cs @@ -0,0 +1,70 @@ +using System.Numerics; + +namespace UnitsNet; + +public readonly partial struct QuantityValue +{ + /// + /// Deconstructs the QuantityValue object into its numerator and denominator components. + /// + /// Output parameter for the numerator component. + /// Output parameter for the denominator component. + public void Deconstruct(out BigInteger numerator, out BigInteger denominator) + { + numerator = Numerator; + denominator = Denominator; + } + + /// + /// Calculates and returns the reciprocal of the specified . + /// + /// A whose reciprocal is to be calculated. + /// A new that is the reciprocal of the input value. + /// + /// In mathematics, a multiplicative inverse or reciprocal for a number x, denoted by 1/x or x^-1, is a + /// number + /// which when multiplied by x yields the multiplicative identity, 1. The multiplicative inverse of a fraction a/b is + /// b/a. For the multiplicative inverse of a real number, divide 1 by the number. For example, the reciprocal of 5 is + /// one fifth (1/5 or 0.2), and the reciprocal of 0.25 is 1 divided by 0.25, or 4. + /// + public static QuantityValue Inverse(QuantityValue value) + { + return FromTerms(value.Denominator, value.Numerator); + } + + /// + /// Reduces the specified to its simplest form. + /// + /// The to be reduced. + /// A new that is the reduced form of the input value. + public static QuantityValue Reduce(QuantityValue value) + { + var numerator = value.Numerator; + var denominator = value.Denominator; + if (denominator.IsZero) + { + return numerator.Sign switch + { + 1 => PositiveInfinity, + -1 => NegativeInfinity, + _ => NaN + }; + } + + if (numerator.IsZero) + { + return Zero; + } + + if (numerator.IsOne || denominator.IsOne || numerator == BigInteger.MinusOne) + { + return new QuantityValue(numerator, denominator); + } + + var gcd = BigInteger.GreatestCommonDivisor(numerator, denominator); + + return gcd.IsOne + ? new QuantityValue(numerator, denominator) + : new QuantityValue(numerator / gcd, denominator / gcd); + } +} diff --git a/UnitsNet/CustomCode/Value/QuantityValue.Number.cs b/UnitsNet/CustomCode/Value/QuantityValue.Number.cs new file mode 100644 index 0000000000..b99aebb58d --- /dev/null +++ b/UnitsNet/CustomCode/Value/QuantityValue.Number.cs @@ -0,0 +1,379 @@ +using System.Numerics; + +namespace UnitsNet; + +public readonly partial struct QuantityValue +{ + /// + /// Gets the QuantityValue representing the value zero. + /// + public static QuantityValue Zero { get; } = new(BigInteger.Zero); + + /// + /// Gets the QuantityValue representing the number one. + /// + public static QuantityValue One { get; } = new(BigInteger.One); + + /// + /// Gets the constant value representing negative one (-1) as a . + /// + /// + /// This property is useful for operations requiring a predefined representation of negative one + /// in the context of arithmetic or comparisons. + /// + public static QuantityValue MinusOne { get; } = new(BigInteger.MinusOne); + + /// + /// The value representing the positive infinity. + /// + public static QuantityValue PositiveInfinity { get; } = new(BigInteger.One, BigInteger.Zero); + + /// + /// The value representing the negative infinity. + /// + public static QuantityValue NegativeInfinity { get; } = new(BigInteger.MinusOne, BigInteger.Zero); + + /// + /// The value representing the result of dividing zero by zero. + /// + public static QuantityValue NaN { get; } = new(BigInteger.Zero, BigInteger.Zero); + + /// + /// Represents the PI constant as a rational fraction, representing the number 3.141592653589793. + /// + /// This is equivalent to calling FromDoubleRounded(Math.PI, 16) + public static readonly QuantityValue PI = new(3141592653589793, 1000000000000000); + + internal static readonly BigInteger Ten = new(10); // TODO see about this one + + +#if NET7_0_OR_GREATER + static int INumberBase.Radix => 10; + static QuantityValue ISignedNumber.NegativeOne => MinusOne; + static QuantityValue IAdditiveIdentity.AdditiveIdentity => Zero; + static QuantityValue IMultiplicativeIdentity.MultiplicativeIdentity => One; + + static bool INumberBase.IsNormal(QuantityValue value) + { + return IsFinite(value); + } + + static bool INumberBase.IsRealNumber(QuantityValue value) + { + return !IsNaN(value); + } + + static bool INumberBase.IsComplexNumber(QuantityValue value) + { + return false; + } + + static bool INumberBase.IsImaginaryNumber(QuantityValue value) + { + return false; + } + + static bool INumberBase.IsSubnormal(QuantityValue value) + { + return false; + } + +#endif + + /// + /// Determines whether the given QuantityValue is in canonical form. + /// + /// The QuantityValue to check. + /// True if the QuantityValue is in canonical form, otherwise false. + /// + /// A QuantityValue is considered to be in canonical form if its denominator is one, + /// or if its numerator and denominator are coprime numbers (their greatest common divisor is one). + /// + public static bool IsCanonical(QuantityValue value) + { + var (numerator, denominator) = value; + if (denominator.IsOne) + { + return true; + } + + if (numerator.IsZero) + { + return denominator.IsZero; // if we want to consider NaN as "canonical" + } + + if (denominator.IsZero) + { + return numerator.IsOne || numerator == BigInteger.MinusOne; + } + + return BigInteger.GreatestCommonDivisor(numerator, denominator).IsOne; + } + + /// + /// Determines whether the given has a finite decimal expansion. + /// + /// The to evaluate. + /// + /// true if the has a finite decimal expansion; otherwise, false. + /// + /// + /// A has a finite decimal expansion if its denominator, when reduced to its lowest terms, + /// is composed only of the prime factors 2 and/or 5. + /// + public static bool HasFiniteDecimalExpansion(QuantityValue value) + { + BigInteger denominator = Reduce(value).Denominator; + return HasNonDecimalFactors(denominator); + } + + /// + /// Determines whether the given denominator contains factors other than 2 and 5, + /// which are the prime factors of decimal numbers. + /// + /// The denominator to check for non-decimal factors. + /// + /// if the denominator contains only factors of 2 and 5; + /// otherwise, . + /// + /// + /// This method is used to verify if a number has a finite decimal expansion + /// by analyzing its denominator in reduced fractional form. + /// + public static bool HasNonDecimalFactors(BigInteger denominator) + { + if (denominator.IsOne) + { + return true; + } + + if (denominator.IsZero) + { + return false; + } + + BigInteger divisor = Ten; + while (true) + { + var quotient = BigInteger.DivRem(denominator, divisor, out BigInteger remainder); + if (remainder.IsZero) + { + if (quotient.IsOne) + { + return true; + } + + denominator = quotient; + } + else + { + break; + } + } + + divisor = 5; + while (true) + { + var quotient = BigInteger.DivRem(denominator, divisor, out BigInteger remainder); + if (remainder.IsZero) + { + if (quotient.IsOne) + { + return true; + } + + denominator = quotient; + } + else + { + break; + } + } + + divisor = 2; + while (true) + { + var quotient = BigInteger.DivRem(denominator, divisor, out BigInteger remainder); + if (remainder.IsZero) + { + if (quotient.IsOne) + { + return true; + } + + denominator = quotient; + } + else + { + break; + } + } + + return false; + } + + /// Determines if a value represents an even integral number. + /// The value to be checked. + /// + /// if is an even integer; otherwise, . + /// + public static bool IsEvenInteger(QuantityValue value) + { + var (numerator, denominator) = value; + if (denominator.IsOne) + { + return numerator.IsEven; + } + + if (denominator.IsZero) + { + return false; + } + + // TODO see about first checking the magnitudes + var quotient = BigInteger.DivRem(numerator, denominator, out var remainder); + return remainder.IsZero && quotient.IsEven; + } + + /// Determines if a value is finite. + /// The value to be checked. + /// + /// if is finite; otherwise, . + /// + public static bool IsFinite(QuantityValue value) + { + return !value.Denominator.IsZero; + } + + /// Determines if a value is infinite. + /// The value to be checked. + /// + /// if is infinite; otherwise, . + /// + public static bool IsInfinity(QuantityValue value) + { + return value.Denominator.IsZero && !value.Numerator.IsZero; + } + + /// Determines if a value represents an integral number. + /// The value to be checked. + /// + /// if is an integer; otherwise, . + /// + public static bool IsInteger(QuantityValue value) + { + var denominator = value.Denominator; + if (denominator.IsOne) + { + return true; + } + + if (denominator.IsZero) + { + return false; + } + + var numerator = BigInteger.Abs(value.Numerator); + if (numerator.IsZero) + { + return true; + } + + return numerator >= denominator && (numerator % denominator).IsZero; + } + + /// Determines if a value is NaN. + /// The value to be checked. + /// + /// if is NaN; otherwise, . + /// + public static bool IsNaN(QuantityValue value) + { + return value.Denominator.IsZero && value.Numerator.IsZero; + } + + /// Determines if a value represents a negative real number. + /// The value to be checked. + /// + /// if represents negative zero or a negative real number; otherwise, + /// . + /// + public static bool IsNegative(QuantityValue value) + { + return value.Numerator.Sign < 0; + } + + /// Determines if a value is negative infinity. + /// The value to be checked. + /// + /// if is negative infinity; otherwise, . + /// + public static bool IsNegativeInfinity(QuantityValue value) + { + return value.Denominator.IsZero && value.Numerator.Sign < 0; + } + + /// Determines if a value represents an odd integral number. + /// The value to be checked. + /// + /// if is an odd integer; otherwise, . + /// + public static bool IsOddInteger(QuantityValue value) + { + var (numerator, denominator) = value; + if (denominator.IsOne) + { + return !numerator.IsEven; + } + + if (denominator.IsZero) + { + return false; + } + + // TODO see about first checking the magnitudes + var quotient = BigInteger.DivRem(numerator, denominator, out var remainder); + return remainder.IsZero && !quotient.IsEven; + } + + /// Determines if a value represents zero or a positive real number. + /// The value to be checked. + /// + /// if represents (positive) zero or a positive real number; + /// otherwise, . + /// + public static bool IsPositive(QuantityValue value) + { + return value.Numerator.Sign > 0; + } + + /// Determines if a value is positive infinity. + /// The value to be checked. + /// + /// if is positive infinity; otherwise, . + /// + public static bool IsPositiveInfinity(QuantityValue value) + { + return value.Denominator.IsZero && value.Numerator.Sign > 0; + } + + /// Determines if a value is zero. + /// The value to be checked. + /// + /// if is zero; otherwise, . + /// + public static bool IsZero(QuantityValue value) + { + return value.Numerator.IsZero && !value.Denominator.IsZero; + } + + /// + /// Returns the absolute value of a specified . + /// + /// A . + /// The absolute value of . + public static QuantityValue Abs(QuantityValue value) + { + return new QuantityValue(BigInteger.Abs(value.Numerator), value.Denominator); + } +} diff --git a/UnitsNet/CustomCode/Value/QuantityValue.PowerMath.cs b/UnitsNet/CustomCode/Value/QuantityValue.PowerMath.cs new file mode 100644 index 0000000000..4d50ba7865 --- /dev/null +++ b/UnitsNet/CustomCode/Value/QuantityValue.PowerMath.cs @@ -0,0 +1,409 @@ +using System; +using System.Numerics; +using System.Runtime.CompilerServices; + +namespace UnitsNet; + +public readonly partial struct QuantityValue +{ + internal static readonly BigInteger[] PowersOfTen = [ + BigInteger.One, // 10^0 = 1 + new(10), // 10^1 = 10 + new(100), // 10^2 = 100 + new(1000), // 10^3 = 1,000 + new(10000), // 10^4 = 10,000 + new(100000), // 10^5 = 100,000 + new(1000000), // 10^6 = 1,000,000 + new(10000000), // 10^7 = 10,000,000 + new(100000000), // 10^8 = 100,000,000 + new(1000000000), // 10^9 = 1,000,000,000 + new(10000000000), // 10^10 = 10,000,000,000 + new(100000000000), // 10^11 = 100,000,000,000 + new(1000000000000), // 10^12 = 1,000,000,000,000 + new(10000000000000), // 10^13 = 10,000,000,000,000 + new(100000000000000), // 10^14 = 100,000,000,000,000 + new(1000000000000000), // 10^15 = 1,000,000,000,000,000 + new(10000000000000000), // 10^16 = 10,000,000,000,000,000 + new(100000000000000000), // 10^17 = 100,000,000,000,000,000 + new(1000000000000000000) // 10^18 = 1,000,000,000,000,000,000 + ]; + + /// + /// Computes the power of ten for a given exponent. + /// + /// The exponent to which ten is raised. + /// + /// A representing 10 raised to the power of . + /// + /// + /// If the is within the precomputed range, the result is retrieved from a cached array + /// for better performance. Otherwise, is used to calculate the result. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + internal static BigInteger PowerOfTen(int exponent) + { + if (exponent < PowersOfTen.Length) + { + return PowersOfTen[exponent]; + } + + var maxExponent = PowersOfTen.Length - 1; + if (exponent > 3 * maxExponent) + { + return BigInteger.Pow(Ten, exponent); // the exponent is > 54 + } + + var maxPowerOfTen = PowersOfTen[maxExponent]; + var result = maxPowerOfTen; + exponent -= maxExponent; // the exponent no more than 2 * maxExponent (36) + if (exponent > maxExponent) + { + result *= maxPowerOfTen; + exponent -= maxExponent; // the exponent is no more than maxExponent (18) + } + + if (exponent == maxExponent) + { + return result * maxPowerOfTen; + } + + return result * PowersOfTen[exponent]; + } + + /// + /// Raises a QuantityValue to the specified power. + /// + /// The QuantityValue to raise to the power. + /// The power to raise the QuantityValue to. + /// The QuantityValue raised to the specified power. + public static QuantityValue Pow(QuantityValue x, int power) + { + BigInteger numerator, denominator; + switch (power) + { + case > 0: + (numerator, denominator) = x; + break; + case < 0 when IsZero(x): + return PositiveInfinity; + case < 0: + power = -power; + (numerator, denominator) = Inverse(x); + break; + default: + // x^0 == 1 + return One; + } + + return new QuantityValue( + BigInteger.Pow(numerator, power), + BigInteger.Pow(denominator, power)); + } + + /// + /// Calculates the square root of a given QuantityValue. + /// + /// The QuantityValue for which to calculate the square root. + /// The number of significant digits of accuracy for the square root calculation. Default is 30. + /// A new QuantityValue that is the square root of the input QuantityValue. + /// Thrown when the accuracy is less than or equal to zero. + /// + /// The implementation is based on the work by + /// SunsetQuest. + /// + /// It uses the Babylonian method of computing square roots, making sure that the relative difference with the true + /// value is smaller than 1/10^accuracy. + /// + /// + /// Note: the resulting value is not rounded and may contain additional digits (up to 20%), which have a relatively + /// high likelihood of being correct, however no strong guarantees can be made. + /// + /// + public static QuantityValue Sqrt(QuantityValue x, int accuracy = 30) + { + if (accuracy <= 0) + { + throw new ArgumentOutOfRangeException(nameof(accuracy), "The accuracy must be a positive integer."); + } + + if (IsNaN(x) || IsNegative(x)) + { + return NaN; + } + + if (x.Numerator.IsZero || x.Denominator.IsZero) // IsZero || IsInfinity) + { + return x; + } + + if (x.Numerator == x.Denominator) + { + return One; + } + + // BigInteger square root implementation based on https://github.com/SunsetQuest/NewtonPlus-Fast-BigInteger-and-BigFloat-Square-Root + return GetSqrtWithPrecision(Reduce(x), accuracy * 4); + + static QuantityValue GetSqrtWithPrecision(QuantityValue fraction, int precisionBits) + { + // BigFloatingPoint square root implementation based on https://github.com/SunsetQuest/NewtonPlus-Fast-BigInteger-and-BigFloat-Square-Root/blob/master/BigFloatingPointSquareRoot.cs + var (numerator, numeratorShift) = SqrtWithShift(fraction.Numerator, precisionBits); + var (denominator, denominatorShift) = SqrtWithShift(fraction.Denominator, precisionBits); + var shift = numeratorShift - denominatorShift; + switch (shift) + { + case < 0: + denominator >>= shift; + break; + case > 0: + numerator >>= -shift; + break; + } + + return new QuantityValue(numerator, denominator); + } + + static (BigInteger val, int shift) SqrtWithShift(BigInteger x, int precisionBits) + { + if (x.IsOne) + { + return (x, 0); + } + + if (x < 144838757784765629) // 1.448e17 = ~1<<57 + { + var longX = (ulong)x; + var vInt = (uint)Math.Sqrt(longX); + if (vInt * vInt == longX) + { + return (vInt, 0); + } + } +#if NET + var totalLen = (int)x.GetBitLength(); +#else + var totalLen = (int)BigInteger.Log(x, 2); +#endif + + var needToShiftInputBy = 2 * precisionBits - totalLen - (totalLen & 1); + var val = SqrtBigInt(x << needToShiftInputBy); + var retShift = (totalLen + (totalLen > 0 ? 1 : 0)) / 2 - precisionBits; + return (val, retShift); + } + + static BigInteger SqrtBigInt(BigInteger x) + { + // BigInteger square root implementation based on https://github.com/SunsetQuest/NewtonPlus-Fast-BigInteger-and-BigFloat-Square-Root/blob/master/BigIntegerSquareRoot.cs + if (x < 144838757784765629) // 1.448e17 = ~1<<57 + { + var vInt = (uint)Math.Sqrt((ulong)x); + return vInt; + } + + var xAsDub = (double)x; + if (xAsDub < 8.5e37) // 8.5e37 is V2long.max * long.max + { + var vInt = (ulong)Math.Sqrt(xAsDub); + BigInteger v = (vInt + (ulong)(x / vInt)) >> 1; + return v; + } + + if (xAsDub < 4.3322e127) + { + var v = (BigInteger)Math.Sqrt(xAsDub); + v = (v + x / v) >> 1; + if (xAsDub > 2e63) + { + v = (v + x / v) >> 1; + } + + return v; + } + +#if NET + var xLen = (int)x.GetBitLength(); +#else + var xLen = (int)BigInteger.Log(x, 2) + 1; +#endif + var wantedPrecision = (xLen + 1) / 2; + var xLenMod = xLen + (xLen & 1) + 1; + + //////// Do the first Sqrt on hardware //////// + var tempX = (long)(x >> (xLenMod - 63)); + var tempSqrt1 = Math.Sqrt(tempX); + var valLong = (ulong)BitConverter.DoubleToInt64Bits(tempSqrt1) & 0x1fffffffffffffL; + if (valLong == 0) + { + valLong = 1UL << 53; + } + + //////// Classic Newton Iterations //////// + var val = ((BigInteger)valLong << 52) + (x >> (xLenMod - 3 * 53)) / valLong; + + val = (val << (106 - 1)) + (x >> (xLenMod - 3 * 106)) / val; + val = (val << (212 - 1)) + (x >> (xLenMod - 3 * 212)) / val; + var size = 424; + + if (xAsDub > 4e254) // 1 << 845 + { +#if NET + var numOfNewtonSteps = BitOperations.Log2((uint)(wantedPrecision / size)) + 2; +#else + var numOfNewtonSteps = (int)Math.Log((uint)(wantedPrecision / size), 2) + 2; +#endif + + ////// Apply Starting Size //////// + var startingSize = (wantedPrecision >> numOfNewtonSteps) + 2; + var needToShiftBy = size - startingSize; + val >>= needToShiftBy; + size = startingSize; + do { + //////// Newton Plus Iterations //////// + var shiftX = xLenMod - 3 * size; + var valSqrd = (val * val) << (size - 1); + var valSU = (x >> shiftX) - valSqrd; + val = (val << size) + valSU / val; + size <<= 1; + } while (size < wantedPrecision); + } + + //////// Shrink result to wanted Precision //////// + val >>= size - wantedPrecision; + + return val; + } + } + + /// + /// Raises a to the power of another with a specified + /// accuracy. + /// + /// The base to be raised to a power. + /// The exponent . + /// The number of decimal places of accuracy for the square root calculation. Default is 30. + /// + /// A new representing the result of raising to the power + /// of . + /// + /// + /// Uses Babylonian Method of computing square roots: increasing the accuracy would result in longer calculation + /// times. + /// + internal static QuantityValue Pow(QuantityValue number, QuantityValue power, int accuracy = 30) + { + if (power == One) + { + return number; + } + + if (number == One) + { + return number; + } + + power = Reduce(power); + var denominator = power.Denominator; + if (denominator.IsOne) + { + return Round(Pow(number, (int)power), accuracy); + } + + var numeratorRaised = Pow(number, (int)power.Numerator); + return RootN(numeratorRaised, (int)denominator, accuracy); + } + + /// + /// Calculates the n-th root of a given with a specified accuracy. + /// + /// The for which to calculate the root. + /// The degree of the root. + /// The number of decimal places of accuracy for the square root calculation. Default is 15. + /// The n-th root of the given . + /// Thrown when is less than or equal to zero. + internal static QuantityValue RootN(QuantityValue number, int n, int accuracy = 15) + { + if (accuracy <= 0) + { + throw new ArgumentOutOfRangeException(nameof(accuracy), accuracy, "The accuracy must be positive"); + } + + if (n == 0) + { + return NaN; + } + + if (n == 1) + { + return Round(number, accuracy); + } + + if (number == One || IsNaN(number)) + { + return number; + } + + if (IsZero(number)) + { + return n < 0 ? PositiveInfinity : number; + } + + if (IsPositiveInfinity(number)) + { + return n < 0 ? Zero : PositiveInfinity; + } + + if (IsNegativeInfinity(number)) + { + if ((n & 1) == 0) // is even integer + { + return NaN; + } + + return n < 0 ? Zero : number; + } + + if (n > 0) + { + if (IsPositive(number)) + { + return Root(number, n, accuracy); + } + + if ((n & 1) == 0) // is even integer + { + return NaN; + } + + return -Root(-number, n, accuracy); + } + + // n < 0 + if (IsPositive(number)) + { + return Root(Inverse(number), -n, accuracy); + } + + if ((n & 1) == 0) // is even integer + { + return NaN; + } + + return -Root(-Inverse(number), -n, accuracy); + + static QuantityValue Root(QuantityValue number, int n, int accuracy) + { + var precision = PowerOfTen(accuracy); + // Initial guess + var x = FromDoubleRounded(Math.Pow(number.ToDouble(), 1.0 / n), (byte)Math.Min(accuracy, 17)); + QuantityValue xPrev; + var minChange = new QuantityValue(1, precision); + do + { + xPrev = x; + x = ((n - 1) * x + number / Pow(x, n - 1)) / n; + } while (Abs(x - xPrev) > minChange); + + return Round(x, accuracy); + } + } +} diff --git a/UnitsNet/CustomCode/Value/QuantityValue.Rounding.cs b/UnitsNet/CustomCode/Value/QuantityValue.Rounding.cs new file mode 100644 index 0000000000..ad95b8e776 --- /dev/null +++ b/UnitsNet/CustomCode/Value/QuantityValue.Rounding.cs @@ -0,0 +1,158 @@ +using System.Numerics; + +namespace UnitsNet; + +public readonly partial struct QuantityValue +{ + /// + /// Rounds the given QuantityValue to the specified number of digits. + /// + /// The QuantityValue to be rounded. + /// The number of decimal places in the return value. + /// A new QuantityValue that is the nearest number with the specified number of digits. + public static QuantityValue Round(QuantityValue x, int nbDigits) + { + return Round(x, nbDigits, MidpointRounding.ToEven); + } + + /// + /// Rounds the given QuantityValue to the specified precision using the specified rounding strategy. + /// + /// The QuantityValue to be rounded. + /// The number of significant decimal places (precision) in the return value. + /// Specifies the strategy that mathematical rounding methods should use to round a number. + /// + /// The number that is rounded to using the rounding strategy and + /// with a precision of . If the precision of is less than + /// , is returned unchanged. + /// + /// If is less than 0 + public static QuantityValue Round(QuantityValue x, int decimals, MidpointRounding mode) + { +#if NET + ArgumentOutOfRangeException.ThrowIfNegative(decimals); +#else + if (decimals < 0) + { + throw new ArgumentOutOfRangeException(nameof(decimals)); + } +#endif + return Round(x.Numerator, x.Denominator, decimals, mode); + } + + internal static QuantityValue Round(BigInteger numerator, BigInteger denominator, int decimals, MidpointRounding mode) + { + if (numerator.IsZero) + { + return new QuantityValue(numerator, denominator); + } + + if (denominator.IsOne || denominator.IsZero) + { + return new QuantityValue(numerator, denominator); + } + + var factor = PowerOfTen(decimals); + var roundedNumerator = RoundToBigInteger(numerator * factor, denominator, mode); + return new QuantityValue(roundedNumerator, factor); + } + + /// + /// Rounds the given QuantityValue to the specified precision using the specified rounding strategy. + /// + /// The QuantityValue to be rounded. + /// Specifies the strategy that mathematical rounding methods should use to round a number. + /// + /// The number as that is rounded to using the + /// rounding strategy. + /// + /// Thrown when the input is , or . + public static BigInteger Round(QuantityValue fraction, MidpointRounding mode) + { + return RoundToBigInteger(fraction.Numerator, fraction.Denominator, mode); + } + + /// + /// Rounds the given QuantityValue to the specified precision using the specified rounding strategy. + /// + /// The numerator of the fraction to be rounded. + /// The denominator of the fraction to be rounded. + /// Specifies the strategy that mathematical rounding methods should use to round a number. + /// The number rounded to using the rounding strategy. + /// Thrown when given Zero for the denominator. + private static BigInteger RoundToBigInteger(BigInteger numerator, BigInteger denominator, MidpointRounding mode) + { + if (denominator.IsZero) + { + throw new OverflowException(); + } + + if (numerator.IsZero || denominator.IsOne) + { + return numerator; + } + + return mode switch + { + MidpointRounding.AwayFromZero => RoundAwayFromZero(numerator, denominator), + MidpointRounding.ToEven => RoundToEven(numerator, denominator), +#if NET + MidpointRounding.ToZero => BigInteger.Divide(numerator, denominator), + MidpointRounding.ToPositiveInfinity => RoundToPositiveInfinity(numerator, denominator), + MidpointRounding.ToNegativeInfinity => RoundToNegativeInfinity(numerator, denominator), +#endif + _ => throw new ArgumentOutOfRangeException(nameof(mode)) + }; + + static BigInteger RoundAwayFromZero(BigInteger numerator, BigInteger denominator) + { + var halfDenominator = denominator >> 1; + return numerator.Sign == 1 + ? BigInteger.Divide(numerator + halfDenominator, denominator) + : BigInteger.Divide(numerator - halfDenominator, denominator); + } + + static BigInteger RoundToEven(BigInteger numerator, BigInteger denominator) + { + var quotient = BigInteger.DivRem(numerator, denominator, out var remainder); + if (remainder.IsZero) + { + return quotient; + } + + if (numerator.Sign == 1) + { + // Both values are positive + var midpoint = remainder << 1; + if (midpoint > denominator || (midpoint == denominator && !quotient.IsEven)) + { + return quotient + BigInteger.One; + } + } + else + { + // For negative values + var midpoint = -remainder << 1; + if (midpoint > denominator || (midpoint == denominator && !quotient.IsEven)) + { + return quotient - BigInteger.One; + } + } + + return quotient; + } +#if NET + static BigInteger RoundToPositiveInfinity(BigInteger numerator, BigInteger denominator) + { + var quotient = BigInteger.DivRem(numerator, denominator, out var remainder); + return remainder.Sign == 1 ? quotient + BigInteger.One : quotient; + } + + static BigInteger RoundToNegativeInfinity(BigInteger numerator, BigInteger denominator) + { + var quotient = BigInteger.DivRem(numerator, denominator, out var remainder); + return remainder.Sign == -1 ? quotient - BigInteger.One : quotient; + } +#endif + } +} diff --git a/UnitsNet/CustomCode/Value/QuantityValue.cs b/UnitsNet/CustomCode/Value/QuantityValue.cs new file mode 100644 index 0000000000..d209d5328c --- /dev/null +++ b/UnitsNet/CustomCode/Value/QuantityValue.cs @@ -0,0 +1,201 @@ +// 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.ComponentModel; +using System.Diagnostics; +using System.Numerics; +using System.Runtime.Serialization; +#if NET +using System.Buffers.Binary; +#endif + +namespace UnitsNet; + +/// +/// Represents a numeric value used in the UnitsNet library to provide precise representation of numbers +/// with unbounded scale and precision, unlike standard numeric types such as or +/// . +/// +/// +/// This implementation is derived from the Fractions library: . +/// Internally, it uses a fraction represented by two values +/// (numerator and denominator) to ensure arbitrary precision without loss of accuracy. +/// +/// +/// The struct can be used to represent precise numeric values for unit conversions +/// and calculations in the UnitsNet library. +/// +[DataContract] +[Serializable] +[TypeConverter(typeof(QuantityValueTypeConverter))] +[DebuggerDisplay("{ToString(), nq}")] +[DebuggerTypeProxy(typeof(QuantityValueDebugView))] +public readonly partial struct QuantityValue : +#if NET7_0_OR_GREATER + INumber, ISignedNumber, IConvertible +#else + IFormattable, IConvertible, IEquatable, IComparable, IComparable +#endif +{ + + [DataMember(Name = "N", Order = 1)] + private readonly BigInteger _numerator; + + [DataMember(Name = "D", Order = 2)] + private readonly BigInteger? _denominator; + + /// + /// Gets the numerator of the fraction representing the . + /// + /// + /// The numerator is a that, together with the denominator, + /// defines the value of the fraction stored in this . + /// + internal BigInteger Numerator => _numerator; + + /// + /// Gets the denominator of the fraction representing the value of this . + /// + /// + /// The denominator is part of the internal fractional representation of the value, which ensures + /// high precision and supports arbitrary values without loss of accuracy. + /// + internal BigInteger Denominator => _denominator.GetValueOrDefault(BigInteger.One); + + + /// + /// Construct using a value and . + /// + /// Numerator + /// Denominator + internal QuantityValue(BigInteger numerator, BigInteger denominator) + { + _numerator = numerator; + _denominator = denominator; + } + + /// + /// Initializes a new instance of the struct with the specified numerator, denominator, + /// and a power of ten exponent. + /// + /// The numerator of the fraction representing the value. + /// The denominator of the fraction representing the value. + /// + /// The power of ten to adjust the value. A positive exponent multiplies the numerator by 10 raised to the power, + /// while a negative exponent multiplies the denominator by 10 raised to the absolute value of the power. + /// + /// + /// This constructor enables precise representation of values using a fraction and a power of ten, + /// corresponding to the scientific notation: (numerator/denominator) * 10 ^ powerOfTen. + /// + internal QuantityValue(BigInteger numerator, BigInteger denominator, int powerOfTen) + { + if (powerOfTen > 0) + { + _numerator = numerator * PowerOfTen(powerOfTen); + _denominator = denominator; + } + else + { + _numerator = numerator; + _denominator = denominator * PowerOfTen(-powerOfTen); + } + } + + /// + /// Creates a normalized fraction using a signed 32bit integer. + /// + /// integer value that will be used for the numerator. The denominator will be 1. + public QuantityValue(int value) + { + _numerator = new BigInteger(value); + _denominator = BigInteger.One; + } + + /// + /// Creates a normalized fraction using a signed 64bit integer. + /// + /// integer value that will be used for the numerator. The denominator will be 1. + public QuantityValue(long value) + { + _numerator = new BigInteger(value); + _denominator = BigInteger.One; + } + + /// + /// Creates a normalized fraction using a unsigned 32bit integer. + /// + /// integer value that will be used for the numerator. The denominator will be 1. + [CLSCompliant(false)] + public QuantityValue(uint value) + { + _numerator = new BigInteger(value); + _denominator = BigInteger.One; + } + + /// + /// Creates a normalized fraction using a unsigned 64bit integer. + /// + /// integer value that will be used for the numerator. The denominator will be 1. + [CLSCompliant(false)] + public QuantityValue(ulong value) + { + _numerator = new BigInteger(value); + _denominator = BigInteger.One; + } + + /// + /// Creates a normalized fraction using a big integer. + /// + /// big integer value that will be used for the numerator. The denominator will be 1. + public QuantityValue(BigInteger value) + { + _numerator = value; + _denominator = BigInteger.One; + } + + /// + /// Initializes a new instance of the struct using a value. + /// + /// The decimal value to initialize the with. + /// + /// This constructor converts the provided into a fraction represented by a numerator + /// and a denominator using for precise representation without loss of precision. + /// + public QuantityValue(decimal value) + { +#if NET + Span bits = stackalloc int[4]; + decimal.GetBits(value, bits); + Span buffer = stackalloc byte[16]; + // Assume BitConverter.IsLittleEndian = true + BinaryPrimitives.WriteInt32LittleEndian(buffer[..4], bits[0]); + BinaryPrimitives.WriteInt32LittleEndian(buffer.Slice(4, 4), bits[1]); + BinaryPrimitives.WriteInt32LittleEndian(buffer.Slice(8, 4), bits[2]); + BinaryPrimitives.WriteInt32LittleEndian(buffer.Slice(12, 4), bits[3]); + var exp = buffer[14]; + var positiveSign = (buffer[15] & 0x80) == 0; + // Pass false to the isBigEndian parameter + var numerator = new BigInteger(buffer[..13]); +#else + var bits = decimal.GetBits(value); + var low = BitConverter.GetBytes(bits[0]); + var middle = BitConverter.GetBytes(bits[1]); + var high = BitConverter.GetBytes(bits[2]); + var scale = BitConverter.GetBytes(bits[3]); + + var exp = scale[2]; + var positiveSign = (scale[3] & 0x80) == 0; + + // value = 0x00,high,middle,low / 10^exp + var numerator = new BigInteger([ + low[0], low[1], low[2], low[3], + middle[0], middle[1], middle[2], middle[3], + high[0], high[1], high[2], high[3], + 0x00 + ]); +#endif + _numerator = positiveSign ? numerator : -numerator; + _denominator = PowerOfTen(exp); + } +} diff --git a/UnitsNet/CustomCode/Value/QuantityValueExtensions.cs b/UnitsNet/CustomCode/Value/QuantityValueExtensions.cs new file mode 100644 index 0000000000..37fcbedba5 --- /dev/null +++ b/UnitsNet/CustomCode/Value/QuantityValueExtensions.cs @@ -0,0 +1,139 @@ +// 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 System.Collections.Generic; +using System.Linq; + +namespace UnitsNet; + +/// +/// Provides extension methods for performing operations on instances. +/// +public static class QuantityValueExtensions +{ + /// + /// Sums a collection of instances. + /// + /// The collection of instances to sum. + /// The sum of the instances. + public static QuantityValue Sum(this IEnumerable values) + { + return values.Aggregate(QuantityValue.Zero, (total, value) => total + value); + } + + /// + /// Calculates the average of a collection of instances. + /// + /// The collection of instances to average. + /// The average of the instances. + /// Thrown when the sequence contains no elements. + public static QuantityValue Average(this IEnumerable values) + { + using IEnumerator e = values.GetEnumerator(); + if (!e.MoveNext()) + { + throw new InvalidOperationException("Sequence contains no elements"); + // throw ExceptionHelper.CreateInvalidOperationOnEmptyCollectionException(); + } + + QuantityValue sum = e.Current; + if (!e.MoveNext()) + { + return sum; + } + + long count = 1; + do + { + sum += e.Current; + count++; + } while (e.MoveNext()); + + return sum / count; + } + + /// + /// Converts a logarithmic value to its linear space equivalent. + /// + /// The logarithmic value to be converted. + /// The scaling factor used in the conversion. Default is 10. + /// The linear space equivalent of the logarithmic value. + /// + /// Most logarithmic operators need a simple scaling factor of 10. However, certain units such as the power ratio + /// need to use 20 instead. + /// + internal static double ToLinearSpace(this QuantityValue logValue, QuantityValue scalingFactor) + { + return Math.Pow(10, (logValue / scalingFactor).ToDouble()); + } + + internal static QuantityValue ToLinearSpace(this QuantityValue logValue, QuantityValue scalingFactor, byte significantDigits) + { + return QuantityValue.FromDoubleRounded(logValue.ToLinearSpace(scalingFactor), significantDigits); + } + + /// + /// Converts a linear value to its logarithmic space equivalent. + /// + /// The linear value to convert. + /// The scaling factor to apply. Default is 10. + /// The number of significant digits to retain in the result. Default is 15. + /// The logarithmic space equivalent of the input value. + /// + /// Most logarithmic operators need a simple scaling factor of 10. However, certain units such as the power ratio + /// need to use 20 instead. + /// + internal static QuantityValue ToLogSpace(this double value, QuantityValue scalingFactor, byte significantDigits = 15) + { + return scalingFactor * QuantityValue.FromDoubleRounded(Math.Log10(value), significantDigits); + } + + /// + internal static QuantityValue ToLogSpace(this QuantityValue value, QuantityValue scalingFactor, byte significantDigits = 15) + { + return value.ToDouble().ToLogSpace(scalingFactor, significantDigits); + } + + /// + /// Adds two instances using logarithmic scaling. + /// + /// The first to add. + /// The second to add. + /// The scaling factor to use for the logarithmic scaling. Default is 10. + /// The number of significant digits to use for the result. Default is 15. + /// The sum of the two instances, scaled logarithmically. + /// + /// Formula: scalingFactor * log10(10^(thisValue/scalingFactor) + 10^(otherValue/scalingFactor)) + /// + /// Most logarithmic operators need a simple scaling factor of 10. However, certain units such as the power ratio + /// need to use 20 instead. + /// + /// + internal static QuantityValue AddWithLogScaling(QuantityValue leftValue, QuantityValue rightValue, QuantityValue scalingFactor, byte significantDigits = 15) + { + return (leftValue.ToLinearSpace(scalingFactor) + rightValue.ToLinearSpace(scalingFactor)) + .ToLogSpace(scalingFactor, significantDigits); + } + + /// + /// Subtract two instances using logarithmic scaling. + /// + /// The to subtract from. + /// The to subtract. + /// The scaling factor to use for the logarithmic scaling. Default is 10. + /// The number of significant digits to use for the result. Default is 15. + /// The sum of the two instances, scaled logarithmically. + /// + /// Formula: scalingFactor * log10(10^(thisValue/scalingFactor) - 10^(otherValue/scalingFactor)) + /// + /// Most logarithmic operators need a simple scaling factor of 10. However, certain units such as the power ratio + /// need to use 20 instead. + /// + /// + internal static QuantityValue SubtractWithLogScaling(QuantityValue leftValue, QuantityValue rightValue, QuantityValue scalingFactor, byte significantDigits = 15) + { + return (leftValue.ToLinearSpace(scalingFactor) - rightValue.ToLinearSpace(scalingFactor)) + .ToLogSpace(scalingFactor, significantDigits); + } +} diff --git a/UnitsNet/CustomCode/Value/QuantityValueTypeConverter.cs b/UnitsNet/CustomCode/Value/QuantityValueTypeConverter.cs new file mode 100644 index 0000000000..7d1543113a --- /dev/null +++ b/UnitsNet/CustomCode/Value/QuantityValueTypeConverter.cs @@ -0,0 +1,95 @@ +// 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.ComponentModel; +using System.Globalization; +using System.Numerics; + +namespace UnitsNet; + +/// +/// Provides a type converter to convert object data types to and from various other data types for QuantityValue. +/// +/// +/// This class inherits from the class and provides methods to +/// convert +/// objects of one type to another type within the context of QuantityValue. It is used for type conversions required +/// for +/// property values, data binding, and other services. +/// +public class QuantityValueTypeConverter : TypeConverter +{ + /// + public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destinationType) + { + return destinationType switch + { + _ when destinationType == typeof(string) => true, + _ when destinationType == typeof(int) => true, + _ when destinationType == typeof(long) => true, + _ when destinationType == typeof(decimal) => true, + _ when destinationType == typeof(double) => true, + _ when destinationType == typeof(QuantityValue) => true, + _ when destinationType == typeof(BigInteger) => true, + _ => false + }; + } + + /// + public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) + { + return sourceType switch + { + _ when sourceType == typeof(string) => true, + _ when sourceType == typeof(int) => true, + _ when sourceType == typeof(long) => true, + _ when sourceType == typeof(decimal) => true, + _ when sourceType == typeof(double) => true, + _ when sourceType == typeof(QuantityValue) => true, + _ when sourceType == typeof(BigInteger) => true, + _ => false + }; + } + + /// + public override object? ConvertTo(ITypeDescriptorContext? context, CultureInfo? culture, object? value, Type destinationType) + { + if (value is QuantityValue quantityValue) + { + return destinationType switch + { + _ when destinationType == typeof(string) => quantityValue.ToString(culture), + _ when destinationType == typeof(int) => (int)quantityValue, + _ when destinationType == typeof(long) => (long)quantityValue, + _ when destinationType == typeof(decimal) => quantityValue.ToDecimal(), + _ when destinationType == typeof(double) => quantityValue.ToDouble(), + _ when destinationType == typeof(BigInteger) => (BigInteger)quantityValue, + _ when destinationType == typeof(QuantityValue) => quantityValue, + _ => base.ConvertTo(context, culture, value, destinationType) + }; + } + + return base.ConvertTo(context, culture, value, destinationType); + } + + /// + public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object? value) + { + if (value is null) + { + return QuantityValue.Zero; + } + + return value switch + { + string s => QuantityValue.Parse(s, culture), + int i => new QuantityValue(i), + long l => new QuantityValue(l), + decimal d => new QuantityValue(d), + double dbl => QuantityValue.FromDoubleRounded(dbl), + BigInteger bigInteger => new QuantityValue(bigInteger), + QuantityValue quantityValue => quantityValue, + _ => base.ConvertFrom(context, culture, value) + }; + } +} \ No newline at end of file diff --git a/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs b/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs index 84d4e5e276..7b3b613136 100644 --- a/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs +++ b/UnitsNet/CustomCode/Wrappers/ReferencePressure.cs @@ -29,7 +29,7 @@ public struct ReferencePressure /// public Pressure AtmosphericPressure { get; set; } - private static readonly Pressure DefaultAtmosphericPressure = new Pressure(1, PressureUnit.Atmosphere); + private static readonly Pressure DefaultAtmosphericPressure = new(1, PressureUnit.Atmosphere); /// /// Gets a list of options: , @@ -98,26 +98,26 @@ public ReferencePressure(Pressure pressure, PressureReference reference, Pressur /// Get Gauge . /// It references pressure level above Atmospheric pressure. /// - public Pressure Gauge => As(PressureReference.Gauge); + public readonly Pressure Gauge => As(PressureReference.Gauge); /// /// Get Absolute . /// It is zero-referenced pressure to the perfect vacuum. /// - public Pressure Absolute => As(PressureReference.Absolute); + public readonly Pressure Absolute => As(PressureReference.Absolute); /// /// Get Vacuum . /// It is a negative Gauge pressure when Absolute pressure is below Atmospheric pressure. /// - public Pressure Vacuum => As(PressureReference.Vacuum); + public readonly Pressure Vacuum => As(PressureReference.Vacuum); /// /// Converts to at /// /// The to convert to. /// The at the specified - private Pressure As(PressureReference reference) + private readonly Pressure As(PressureReference reference) { var converted = AsBaseNumericType(reference); @@ -129,7 +129,7 @@ private Pressure As(PressureReference reference) /// /// The to convert to. /// The value of pressure at - private double AsBaseNumericType(PressureReference reference) + private readonly QuantityValue AsBaseNumericType(PressureReference reference) { var baseReferenceValue = AsBaseReference(); @@ -140,14 +140,13 @@ private double AsBaseNumericType(PressureReference reference) var negatingValue = Reference == PressureReference.Vacuum ? -1 : 1; - switch (reference) + return reference switch { - case PressureReference.Absolute: return baseReferenceValue; - case PressureReference.Gauge: return baseReferenceValue - AtmosphericPressure.ToUnit(Pressure.Unit).Value; - case PressureReference.Vacuum: return AtmosphericPressure.ToUnit(Pressure.Unit).Value - negatingValue * baseReferenceValue; - default: - throw new NotImplementedException($"Can't convert {Reference} to {reference}."); - } + PressureReference.Absolute => baseReferenceValue, + PressureReference.Gauge => baseReferenceValue - AtmosphericPressure.ToUnit(Pressure.Unit).Value, + PressureReference.Vacuum => AtmosphericPressure.ToUnit(Pressure.Unit).Value - negatingValue * baseReferenceValue, + _ => throw new NotImplementedException($"Can't convert {Reference} to {reference}.") + }; } /// @@ -155,7 +154,7 @@ private double AsBaseNumericType(PressureReference reference) /// /// /// The value of pressure at the - private double AsBaseReference() + private readonly QuantityValue AsBaseReference() { switch (Reference) { diff --git a/UnitsNet/Exceptions/InvalidConversionException.cs b/UnitsNet/Exceptions/InvalidConversionException.cs new file mode 100644 index 0000000000..3c78fc03f1 --- /dev/null +++ b/UnitsNet/Exceptions/InvalidConversionException.cs @@ -0,0 +1,48 @@ +// 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; + +namespace UnitsNet; + +/// +/// The conversion to the specified is not supported. This is typically thrown for dynamic conversions, +/// such as . +/// +public class InvalidConversionException : UnitsNetException +{ + /// + public InvalidConversionException() + { + } + + /// + public InvalidConversionException(string message) : base(message) + { + } + + /// + public InvalidConversionException(string message, Exception innerException) : base(message, innerException) + { + } + + internal static InvalidConversionException CreateImplicitConversionException(QuantityInfo sourceQuantity, QuantityInfo targetQuantity) + { + return new InvalidConversionException($"No implicit conversion exists for the quantities: source = '{sourceQuantity}', target = '{targetQuantity}'"); + } + + internal static InvalidConversionException CreateIncompatibleDimensionsException(BaseDimensions sourceDimensions, BaseDimensions targetDimensions) + { + return new InvalidConversionException($"The conversion expression cannot be determined from the base dimensions: source = '{sourceDimensions}', target = '{targetDimensions}'"); + } + + internal static InvalidConversionException CreateIncompatibleDimensionsException(QuantityInfo sourceQuantityInfo, QuantityInfo targetQuantityInfo) + { + return new InvalidConversionException($"The dimensions of the source quantity '{sourceQuantityInfo}' are not compatible with the dimensions of the target quantity '{targetQuantityInfo}'."); + } + + internal static InvalidConversionException CreateIncompatibleUnitsException(UnitInfo sourceUnitInfo, QuantityInfo targetQuantityInfo) + { + return new InvalidConversionException($"No compatible base units found for the conversion from '{sourceUnitInfo}' to '{targetQuantityInfo}'"); + } +} diff --git a/UnitsNet/Exceptions/UnitNotFoundException.cs b/UnitsNet/Exceptions/UnitNotFoundException.cs index 0a1001e273..a520bd7621 100644 --- a/UnitsNet/Exceptions/UnitNotFoundException.cs +++ b/UnitsNet/Exceptions/UnitNotFoundException.cs @@ -1,4 +1,4 @@ -// Licensed under MIT No Attribution, see LICENSE file at the root. +// 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; diff --git a/UnitsNet/Extensions/AffineQuantityExtensions.cs b/UnitsNet/Extensions/AffineQuantityExtensions.cs index 3477b5b47e..2cb88830db 100644 --- a/UnitsNet/Extensions/AffineQuantityExtensions.cs +++ b/UnitsNet/Extensions/AffineQuantityExtensions.cs @@ -1,10 +1,6 @@ // 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. -#if NET -using System.Numerics; -#endif - namespace UnitsNet; /// @@ -62,13 +58,13 @@ private static bool EqualsAbsolute(this TQuantity quantity, where TQuantity : IAffineQuantity, ISubtractionOperators where TOffset : IQuantityOfType, IAdditiveIdentity { - if (double.IsNegative(tolerance.Value)) + if (QuantityValue.IsNegative(tolerance.Value)) { throw ExceptionHelper.CreateArgumentOutOfRangeExceptionForNegativeTolerance(nameof(tolerance)); } TOffset difference = quantity - other; - return double.Abs(difference.Value) <= tolerance.GetValue(difference.UnitKey); + return QuantityValue.Abs(difference.Value) <= tolerance.GetValue(difference.UnitKey); } #else /// @@ -99,13 +95,13 @@ private static bool EqualsAbsolute(this TQuantity quantity, /// public static bool Equals(this Temperature quantity, Temperature other, TemperatureDelta tolerance) { - if (tolerance.Value < 0) + if (QuantityValue.IsNegative(tolerance.Value)) { throw ExceptionHelper.CreateArgumentOutOfRangeExceptionForNegativeTolerance(nameof(tolerance)); } TemperatureDelta difference = quantity - other; - return Math.Abs(difference.Value) <= tolerance.GetValue(UnitKey.ForUnit(difference.Unit)); + return QuantityValue.Abs(difference.Value) <= tolerance.GetValue(UnitKey.ForUnit(difference.Unit)); } /// diff --git a/UnitsNet/Extensions/LinearQuantityExtensions.cs b/UnitsNet/Extensions/LinearQuantityExtensions.cs index 8431c4f5ae..adc0fc60d3 100644 --- a/UnitsNet/Extensions/LinearQuantityExtensions.cs +++ b/UnitsNet/Extensions/LinearQuantityExtensions.cs @@ -88,14 +88,14 @@ public static TQuantity Sum(this IEnumerable quantities) { return default!; } - + return (TQuantity)UnitsNetSetup.Default.Quantities.GetQuantityInfo(typeof(TQuantity)).Zero; #endif } TQuantity firstQuantity = enumerator.Current!; UnitKey resultUnit = firstQuantity.UnitKey; - var sumOfValues = firstQuantity.Value; + QuantityValue sumOfValues = firstQuantity.Value; while (enumerator.MoveNext()) { sumOfValues += enumerator.Current!.GetValue(resultUnit); @@ -107,7 +107,7 @@ public static TQuantity Sum(this IEnumerable quantities) return firstQuantity.QuantityInfo.Create(sumOfValues, resultUnit); #endif } - + /// /// Computes the sum of a sequence of quantities by applying a specified selector function to each element of the /// sequence. @@ -148,15 +148,15 @@ public static TQuantity Sum(this IEnumerable quanti if (!enumerator.MoveNext()) { #if NET - return TQuantity.From(0, unit); + return TQuantity.From(QuantityValue.Zero, unit); #else - return (TQuantity)Quantity.From(0, UnitKey.ForUnit(unit)); + return (TQuantity)Quantity.From(QuantityValue.Zero, UnitKey.ForUnit(unit)); #endif } var unitKey = UnitKey.ForUnit(unit); TQuantity firstQuantity = enumerator.Current!; - var resultValue = firstQuantity.GetValue(unitKey); + QuantityValue resultValue = firstQuantity.GetValue(unitKey); while (enumerator.MoveNext()) { resultValue += enumerator.Current!.GetValue(unitKey); diff --git a/UnitsNet/Extensions/LogarithmicQuantityExtensions.cs b/UnitsNet/Extensions/LogarithmicQuantityExtensions.cs index 7f28720e05..6b1b309451 100644 --- a/UnitsNet/Extensions/LogarithmicQuantityExtensions.cs +++ b/UnitsNet/Extensions/LogarithmicQuantityExtensions.cs @@ -11,25 +11,6 @@ namespace UnitsNet; /// public static class LogarithmicQuantityExtensions { - internal static double ToLinearSpace(this double logValue, double scalingFactor) - { - return Math.Pow(10, logValue / scalingFactor); - } - - internal static double ToLogSpace(this double value, double scalingFactor) - { - return scalingFactor * Math.Log10(value); - } - - private static double RootN(double number, int n) - { -#if NET - return double.RootN(number, n); -#else - return Math.Pow(number, 1.0 / n); -#endif - } - /// public static bool Equals(this TQuantity quantity, TOther? other, TTolerance tolerance) where TQuantity : ILogarithmicQuantity @@ -86,9 +67,9 @@ private static bool EqualsAbsolute(this TQuantity { UnitKey quantityUnit = quantity.UnitKey; #if NET - var scalingFactor = TQuantity.LogarithmicScalingFactor; + QuantityValue scalingFactor = TQuantity.LogarithmicScalingFactor; #else - var scalingFactor = quantity.LogarithmicScalingFactor; + QuantityValue scalingFactor = quantity.LogarithmicScalingFactor; #endif var valueInLinearSpace = quantity.Value.ToLinearSpace(scalingFactor); var otherValueInLinearSpace = other.GetValue(quantityUnit).ToLinearSpace(scalingFactor); @@ -101,13 +82,14 @@ private static bool EqualsAbsolute(this TQuantity /// /// The type of the logarithmic quantity. /// The sequence of logarithmic quantities to sum. + /// The number of significant digits to retain in the result. Default is 15. /// The sum of the logarithmic quantities in the unit of the first element in the sequence. /// Thrown when the sequence is empty. /// /// When the sequence is not empty, each quantity is converted to linear space (in the unit of the first element), /// summed, and then the result is converted back to logarithmic space using the same unit. /// - public static TQuantity Sum(this IEnumerable quantities) + public static TQuantity Sum(this IEnumerable quantities, byte significantDigits = 15) where TQuantity : ILogarithmicQuantity { if (quantities is null) @@ -123,9 +105,9 @@ public static TQuantity Sum(this IEnumerable quantities) TQuantity firstQuantity = enumerator.Current!; #if NET - var logarithmicScalingFactor = TQuantity.LogarithmicScalingFactor; + QuantityValue logarithmicScalingFactor = TQuantity.LogarithmicScalingFactor; #else - var logarithmicScalingFactor = firstQuantity.LogarithmicScalingFactor; + QuantityValue logarithmicScalingFactor = firstQuantity.LogarithmicScalingFactor; #endif UnitKey resultUnit = firstQuantity.UnitKey; var resultValue = firstQuantity.Value.ToLinearSpace(logarithmicScalingFactor); @@ -134,9 +116,9 @@ public static TQuantity Sum(this IEnumerable quantities) resultValue += enumerator.Current!.GetValue(resultUnit).ToLinearSpace(logarithmicScalingFactor); } #if NET - return TQuantity.Create(resultValue.ToLogSpace(logarithmicScalingFactor), resultUnit); + return TQuantity.Create(resultValue.ToLogSpace(logarithmicScalingFactor, significantDigits), resultUnit); #else - return firstQuantity.QuantityInfo.Create(resultValue.ToLogSpace(logarithmicScalingFactor), resultUnit); + return firstQuantity.QuantityInfo.Create(resultValue.ToLogSpace(logarithmicScalingFactor, significantDigits), resultUnit); #endif } @@ -149,16 +131,17 @@ public static TQuantity Sum(this IEnumerable quantities) /// The type of the quantity elements in the source sequence. /// A sequence of quantities to calculate the sum of. /// A function to transform each element of the source sequence into a quantity. + /// The number of significant digits to retain in the result. Default is 15. /// The sum of the logarithmic quantities in the unit of the first element in the sequence. /// Thrown when the sequence is empty. /// /// When the sequence is not empty, each quantity is converted to linear space (in the unit of the first element), /// summed, and then the result is converted back to logarithmic space using the same unit. /// - public static TQuantity Sum(this IEnumerable source, Func selector) + public static TQuantity Sum(this IEnumerable source, Func selector, byte significantDigits = 15) where TQuantity : ILogarithmicQuantity { - return source.Select(selector).Sum(); + return source.Select(selector).Sum(significantDigits); } /// @@ -169,13 +152,14 @@ public static TQuantity Sum(this IEnumerable source /// The unit type of the logarithmic quantity. /// The sequence of logarithmic quantities to sum. /// The unit in which to express the sum. + /// The number of significant digits to retain in the result. Default is 15. /// The sum of the logarithmic quantities in the specified unit. /// Thrown when the sequence is empty. /// /// This method converts each logarithmic quantity to linear space, sums them, and then converts the result back to /// logarithmic space. /// - public static TQuantity Sum(this IEnumerable quantities, TUnit targetUnit) + public static TQuantity Sum(this IEnumerable quantities, TUnit targetUnit, byte significantDigits = 15) where TQuantity : ILogarithmicQuantity where TUnit : struct, Enum { @@ -193,9 +177,9 @@ public static TQuantity Sum(this IEnumerable quanti var unitKey = UnitKey.ForUnit(targetUnit); TQuantity firstQuantity = enumerator.Current!; #if NET - var logarithmicScalingFactor = TQuantity.LogarithmicScalingFactor; + QuantityValue logarithmicScalingFactor = TQuantity.LogarithmicScalingFactor; #else - var logarithmicScalingFactor = firstQuantity.LogarithmicScalingFactor; + QuantityValue logarithmicScalingFactor = firstQuantity.LogarithmicScalingFactor; #endif var sumInLinearSpace = firstQuantity.GetValue(unitKey).ToLinearSpace(logarithmicScalingFactor); while (enumerator.MoveNext()) @@ -203,7 +187,7 @@ public static TQuantity Sum(this IEnumerable quanti sumInLinearSpace += enumerator.Current!.GetValue(unitKey).ToLinearSpace(logarithmicScalingFactor); } - return firstQuantity.QuantityInfo.From(sumInLinearSpace.ToLogSpace(logarithmicScalingFactor), targetUnit); + return firstQuantity.QuantityInfo.From(sumInLinearSpace.ToLogSpace(logarithmicScalingFactor, significantDigits), targetUnit); } /// @@ -217,17 +201,19 @@ public static TQuantity Sum(this IEnumerable quanti /// A sequence of quantities to calculate the sum of. /// A function to transform each element of the source sequence into a quantity. /// The desired unit type for the resulting quantity + /// The number of significant digits to retain in the result. Default is 15. /// The sum of the projected quantities in the specified unit. /// Thrown if the source or selector is null. /// /// This method converts each logarithmic quantity to linear space, sums them, and then converts the result back to /// logarithmic space. /// - public static TQuantity Sum(this IEnumerable source, Func selector, TUnit targetUnit) + public static TQuantity Sum(this IEnumerable source, Func selector, TUnit targetUnit, + byte significantDigits = 15) where TQuantity : ILogarithmicQuantity where TUnit : struct, Enum { - return source.Select(selector).Sum(targetUnit); + return source.Select(selector).Sum(targetUnit, significantDigits); } /// @@ -235,13 +221,14 @@ public static TQuantity Sum(this IEnumerable /// /// The type of the logarithmic quantity. /// The sequence of logarithmic quantities to average. + /// The number of significant digits to retain in the result. Default is 15. /// The average of the logarithmic quantities in the unit of the first element in the sequence. /// Thrown when the sequence is empty. /// /// When the sequence is not empty, each quantity is converted to linear space (in the unit of the first element), /// averaged, and then the result is converted back to logarithmic space using the same unit. /// - public static TQuantity ArithmeticMean(this IEnumerable quantities) + public static TQuantity ArithmeticMean(this IEnumerable quantities, byte significantDigits = 15) where TQuantity : ILogarithmicQuantity { if (quantities is null) @@ -257,9 +244,9 @@ public static TQuantity ArithmeticMean(this IEnumerable qu TQuantity firstQuantity = enumerator.Current!; #if NET - var logarithmicScalingFactor = TQuantity.LogarithmicScalingFactor; + QuantityValue logarithmicScalingFactor = TQuantity.LogarithmicScalingFactor; #else - var logarithmicScalingFactor = firstQuantity.LogarithmicScalingFactor; + QuantityValue logarithmicScalingFactor = firstQuantity.LogarithmicScalingFactor; #endif UnitKey resultUnit = firstQuantity.UnitKey; var sumInLinearSpace = firstQuantity.Value.ToLinearSpace(logarithmicScalingFactor); @@ -272,9 +259,9 @@ public static TQuantity ArithmeticMean(this IEnumerable qu var avgInLinearSpace = sumInLinearSpace / nbQuantities; #if NET - return TQuantity.Create(avgInLinearSpace.ToLogSpace(logarithmicScalingFactor), resultUnit); + return TQuantity.Create(avgInLinearSpace.ToLogSpace(logarithmicScalingFactor, significantDigits), resultUnit); #else - return firstQuantity.QuantityInfo.Create(avgInLinearSpace.ToLogSpace(logarithmicScalingFactor), resultUnit); + return firstQuantity.QuantityInfo.Create(avgInLinearSpace.ToLogSpace(logarithmicScalingFactor, significantDigits), resultUnit); #endif } @@ -286,16 +273,17 @@ public static TQuantity ArithmeticMean(this IEnumerable qu /// The type of the quantity elements in the source sequence. /// A sequence of quantities to calculate the sum of. /// A function to transform each element of the source sequence into a quantity. + /// The number of significant digits to retain in the result. Default is 15. /// The average of the logarithmic quantities in the unit of the first element in the sequence. /// Thrown when the sequence is empty. /// /// When the sequence is not empty, each quantity is converted to linear space (in the unit of the first element), /// averaged, and then the result is converted back to logarithmic space using the same unit. /// - public static TQuantity ArithmeticMean(this IEnumerable source, Func selector) + public static TQuantity ArithmeticMean(this IEnumerable source, Func selector, byte significantDigits = 15) where TQuantity : ILogarithmicQuantity { - return ArithmeticMean(source.Select(selector)); + return source.Select(selector).ArithmeticMean(significantDigits); } /// @@ -305,13 +293,14 @@ public static TQuantity ArithmeticMean(this IEnumerableThe unit type of the logarithmic quantity. /// The sequence of logarithmic quantities to sum. /// The unit in which to express the sum. + /// The number of significant digits to retain in the result. Default is 15. /// The arithmetic mean of the logarithmic quantities in the specified unit. /// Thrown when the sequence is empty. /// /// When the sequence is not empty, each quantity is converted to linear space (in the specified unit), /// averaged, and then the result is converted back to logarithmic space using the same unit. /// - public static TQuantity ArithmeticMean(this IEnumerable quantities, TUnit unit) + public static TQuantity ArithmeticMean(this IEnumerable quantities, TUnit unit, byte significantDigits = 15) where TQuantity : ILogarithmicQuantity where TUnit : struct, Enum { @@ -329,9 +318,9 @@ public static TQuantity ArithmeticMean(this IEnumerable(this IEnumerable @@ -356,17 +345,19 @@ public static TQuantity ArithmeticMean(this IEnumerableA sequence of quantities to calculate the sum of. /// A function to transform each element of the source sequence into a quantity. /// The desired unit type for the resulting quantity. + /// The number of significant digits to retain in the result. Default is 15. /// The arithmetic mean of the logarithmic quantities in the specified unit. /// Thrown when the sequence is empty. /// /// When the sequence is not empty, each quantity is converted to linear space (in the specified unit), /// averaged, and then the result is converted back to logarithmic space using the same unit. /// - public static TQuantity ArithmeticMean(this IEnumerable source, Func selector, TUnit targetUnit) + public static TQuantity ArithmeticMean(this IEnumerable source, Func selector, TUnit targetUnit, + byte significantDigits = 15) where TQuantity : ILogarithmicQuantity where TUnit : struct, Enum { - return ArithmeticMean(source.Select(selector), targetUnit); + return source.Select(selector).ArithmeticMean(targetUnit, significantDigits); } /// @@ -374,13 +365,17 @@ public static TQuantity ArithmeticMean(this IEnumerab /// /// The type of the logarithmic quantity. /// The sequence of logarithmic quantities to average. + /// + /// The accuracy for the square root calculation, expressed as number of significant digits. Default + /// is 15. + /// /// The geometric mean of the logarithmic quantities in the unit of the first element in the sequence. /// Thrown when the sequence is empty. /// /// When the sequence is not empty, calculates the n-th root of the product of the quantities, which for the /// logarithmic quantities is equal to the sum the values, converted in unit of the first element. /// - public static TQuantity GeometricMean(this IEnumerable quantities) + public static TQuantity GeometricMean(this IEnumerable quantities, int accuracy = 15) where TQuantity : ILogarithmicQuantity { if (quantities is null) @@ -396,7 +391,7 @@ public static TQuantity GeometricMean(this IEnumerable qua TQuantity firstQuantity = enumerator.Current!; UnitKey resultUnit = firstQuantity.UnitKey; - var sumInLogSpace = firstQuantity.Value; + QuantityValue sumInLogSpace = firstQuantity.Value; var nbQuantities = 1; while (enumerator.MoveNext()) { @@ -404,7 +399,7 @@ public static TQuantity GeometricMean(this IEnumerable qua nbQuantities++; } - var geometricMean = RootN(sumInLogSpace, nbQuantities); + var geometricMean = QuantityValue.RootN(sumInLogSpace, nbQuantities, accuracy); #if NET return TQuantity.Create(geometricMean, resultUnit); #else @@ -421,18 +416,20 @@ public static TQuantity GeometricMean(this IEnumerable qua /// The type of the quantity elements in the source sequence. /// A sequence of quantities to calculate the sum of. /// A function to transform each element of the source sequence into a quantity. + /// The number of significant digits to retain in the result. Default is 15. /// The geometric mean of the logarithmic quantities in the unit of the first element in the sequence. /// Thrown when the sequence is empty. /// /// When the sequence is not empty, calculates the n-th root of the product of the quantities, which for the /// logarithmic quantities is equal to the sum the values, converted in unit of the first element. /// - public static TQuantity GeometricMean(this IEnumerable source, Func selector) + public static TQuantity GeometricMean(this IEnumerable source, Func selector, int accuracy = 15) where TQuantity : ILogarithmicQuantity { - return source.Select(selector).GeometricMean(); + return source.Select(selector).GeometricMean(accuracy); } + /// /// Computes the geometric mean of a sequence of logarithmic quantities, such as PowerRatio and AmplitudeRatio, using /// the specified unit. @@ -441,13 +438,14 @@ public static TQuantity GeometricMean(this IEnumerableThe type of the unit of the quantities. /// The sequence of logarithmic quantities to average. /// The desired unit type for the resulting quantity. + /// The number of decimal places of accuracy for the square root calculation. Default is 15. /// The geometric mean of the logarithmic quantities in the unit of the first element in the sequence. /// Thrown when the sequence is empty. /// /// When the sequence is not empty, calculates the n-th root of the product of the quantities, which for the /// logarithmic quantities is equal to the sum the values, converted in unit of the first element. /// - public static TQuantity GeometricMean(this IEnumerable quantities, TUnit targetUnit) + public static TQuantity GeometricMean(this IEnumerable quantities, TUnit targetUnit, int accuracy = 15) where TQuantity : ILogarithmicQuantity where TUnit : struct, Enum { @@ -464,7 +462,7 @@ public static TQuantity GeometricMean(this IEnumerable(this IEnumerable()); } @@ -487,16 +485,18 @@ public static TQuantity GeometricMean(this IEnumerableA sequence of quantities to calculate the sum of. /// A function to transform each element of the source sequence into a quantity. /// The desired unit type for the resulting quantity. + /// The number of decimal places of accuracy for the square root calculation. Default is 15. /// The arithmetic mean of the logarithmic quantities in the specified unit. /// Thrown when the sequence is empty. /// /// When the sequence is not empty, calculates the n-th root of the product of the quantities, which for the /// logarithmic quantities is equal to the sum the values, converted in unit of the first element. /// - public static TQuantity GeometricMean(this IEnumerable source, Func selector, TUnit targetUnit) + public static TQuantity GeometricMean(this IEnumerable source, Func selector, TUnit targetUnit, + int accuracy = 15) where TQuantity : ILogarithmicQuantity where TUnit : struct, Enum { - return source.Select(selector).GeometricMean(targetUnit); + return source.Select(selector).GeometricMean(targetUnit, accuracy); } } diff --git a/UnitsNet/Extensions/QuantityExtensions.cs b/UnitsNet/Extensions/QuantityExtensions.cs index 41f2ace803..5f88d35309 100644 --- a/UnitsNet/Extensions/QuantityExtensions.cs +++ b/UnitsNet/Extensions/QuantityExtensions.cs @@ -10,12 +10,30 @@ namespace UnitsNet; /// public static class QuantityExtensions { - /// - /// This should be using UnitConverter.Default.ConvertValue(quantity, toUnit) - internal static double GetValue(this TQuantity quantity, UnitKey toUnit) + /// + internal static QuantityValue GetValue(this TQuantity quantity, UnitKey toUnit) where TQuantity : IQuantity { - return quantity.As(toUnit); + return UnitConverter.Default.ConvertValue(quantity, toUnit); + } + + /// + internal static QuantityValue ConvertValue(this UnitConverter converter, TQuantity quantity, UnitKey toUnit) + where TQuantity : IQuantity + { + return converter.ConvertValue(quantity.Value, quantity.UnitKey, toUnit); + } + + /// + internal static TQuantity ConvertToUnit(this UnitConverter converter, TQuantity quantity, UnitKey toUnit) + where TQuantity : IQuantityOfType + { + QuantityValue convertedValue = converter.ConvertValue(quantity.Value, quantity.UnitKey, toUnit); +#if NET + return TQuantity.Create(convertedValue, toUnit); +#else + return quantity.QuantityInfo.Create(convertedValue, toUnit); +#endif } /// @@ -80,7 +98,7 @@ internal static TQuantity ArithmeticMean(this IEnumerable TQuantity firstQuantity = enumerator.Current!; UnitKey resultUnit = firstQuantity.UnitKey; - var sumOfValues = firstQuantity.Value; + QuantityValue sumOfValues = firstQuantity.Value; var nbValues = 1; while (enumerator.MoveNext()) { @@ -126,7 +144,7 @@ internal static TQuantity ArithmeticMean(this IEnumerable +/// Provides extension methods for converting quantities in the UnitsNet library to another unit. +/// +public static class UnitConversionExtensions +{ + /// + public static QuantityValue As(this TQuantity quantity, TUnit unit) + where TQuantity : IQuantity + where TUnit : struct, Enum + { + return UnitConverter.Default.ConvertValue(quantity, unit); + } + + /// + /// Gets the value in the unit determined by the given . If multiple units were found for the + /// given , + /// the first match will be used. + /// + /// + /// The to convert the quantity value to. + /// The converted value. + public static QuantityValue As(this TQuantity quantity, UnitSystem unitSystem) + where TQuantity : IQuantity + { + return quantity.GetValue(quantity.QuantityInfo.GetDefaultUnit(unitSystem).UnitKey); + } + + /// + public static TQuantity ToUnit(this TQuantity quantity, TUnit unit) + where TQuantity : IQuantity + where TUnit : struct, Enum + { + return UnitConverter.Default.ConvertToUnit(quantity, unit); + } + + /// + public static TQuantity ToUnit(this TQuantity quantity, TUnit unit, UnitConverter unitConverter) + where TQuantity : IQuantity + where TUnit : struct, Enum + { + return unitConverter.ConvertToUnit(quantity, unit); + } + + /// + public static TQuantity ToUnit(this TQuantity quantity, UnitSystem unitSystem) + where TQuantity : IQuantityOfType + { +#if NET + QuantityInfo quantityInfo = quantity.QuantityInfo; +#else + QuantityInfo quantityInfo = ((IQuantity)quantity).QuantityInfo; +#endif + return UnitConverter.Default.ConvertToUnit(quantity, quantityInfo.GetDefaultUnit(unitSystem).UnitKey); + } +} diff --git a/UnitsNet/GeneratedCode/Quantities/AbsorbedDoseOfIonizingRadiation.g.cs b/UnitsNet/GeneratedCode/Quantities/AbsorbedDoseOfIonizingRadiation.g.cs index fbe9d3a4d5..36bb63d25b 100644 --- a/UnitsNet/GeneratedCode/Quantities/AbsorbedDoseOfIonizingRadiation.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AbsorbedDoseOfIonizingRadiation.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Absorbed_dose /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct AbsorbedDoseOfIonizingRadiation : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly AbsorbedDoseOfIonizingRadiationUnit? _unit; /// @@ -104,7 +103,7 @@ public static AbsorbedDoseOfIonizingRadiationInfo CreateDefault(Func - /// The for is [T^-2][L^2]. + /// The for is T^-2L^2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, -2, 0, 0, 0, 0); @@ -119,31 +118,61 @@ public static AbsorbedDoseOfIonizingRadiationInfo CreateDefault(FuncAn of representing the default unit mappings for AbsorbedDoseOfIonizingRadiation. public static IEnumerable> GetDefaultMappings() { - yield return new (AbsorbedDoseOfIonizingRadiationUnit.Centigray, "Centigray", "Centigrays", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Second)); - yield return new (AbsorbedDoseOfIonizingRadiationUnit.Decigray, "Decigray", "Decigrays", BaseUnits.Undefined); - yield return new (AbsorbedDoseOfIonizingRadiationUnit.Femtogray, "Femtogray", "Femtograys", BaseUnits.Undefined); - yield return new (AbsorbedDoseOfIonizingRadiationUnit.Gigagray, "Gigagray", "Gigagrays", BaseUnits.Undefined); + yield return new (AbsorbedDoseOfIonizingRadiationUnit.Centigray, "Centigray", "Centigrays", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Second), + 100 + ); + yield return new (AbsorbedDoseOfIonizingRadiationUnit.Decigray, "Decigray", "Decigrays", BaseUnits.Undefined, + 10 + ); + yield return new (AbsorbedDoseOfIonizingRadiationUnit.Femtogray, "Femtogray", "Femtograys", BaseUnits.Undefined, + 1000000000000000 + ); + yield return new (AbsorbedDoseOfIonizingRadiationUnit.Gigagray, "Gigagray", "Gigagrays", BaseUnits.Undefined, + new QuantityValue(1, 1000000000) + ); yield return new (AbsorbedDoseOfIonizingRadiationUnit.Gray, "Gray", "Grays", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)); - yield return new (AbsorbedDoseOfIonizingRadiationUnit.Kilogray, "Kilogray", "Kilograys", BaseUnits.Undefined); - yield return new (AbsorbedDoseOfIonizingRadiationUnit.Kilorad, "Kilorad", "Kilorads", BaseUnits.Undefined); - yield return new (AbsorbedDoseOfIonizingRadiationUnit.Megagray, "Megagray", "Megagrays", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second)); - yield return new (AbsorbedDoseOfIonizingRadiationUnit.Megarad, "Megarad", "Megarads", BaseUnits.Undefined); - yield return new (AbsorbedDoseOfIonizingRadiationUnit.Microgray, "Microgray", "Micrograys", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second)); - yield return new (AbsorbedDoseOfIonizingRadiationUnit.Milligray, "Milligray", "Milligrays", BaseUnits.Undefined); - yield return new (AbsorbedDoseOfIonizingRadiationUnit.Millirad, "Millirad", "Millirads", BaseUnits.Undefined); - yield return new (AbsorbedDoseOfIonizingRadiationUnit.Nanogray, "Nanogray", "Nanograys", BaseUnits.Undefined); - yield return new (AbsorbedDoseOfIonizingRadiationUnit.Petagray, "Petagray", "Petagrays", BaseUnits.Undefined); - yield return new (AbsorbedDoseOfIonizingRadiationUnit.Picogray, "Picogray", "Picograys", new BaseUnits(length: LengthUnit.Micrometer, time: DurationUnit.Second)); - yield return new (AbsorbedDoseOfIonizingRadiationUnit.Rad, "Rad", "Rads", BaseUnits.Undefined); - yield return new (AbsorbedDoseOfIonizingRadiationUnit.Teragray, "Teragray", "Teragrays", new BaseUnits(length: LengthUnit.Megameter, time: DurationUnit.Second)); + yield return new (AbsorbedDoseOfIonizingRadiationUnit.Kilogray, "Kilogray", "Kilograys", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (AbsorbedDoseOfIonizingRadiationUnit.Kilorad, "Kilorad", "Kilorads", BaseUnits.Undefined, + new QuantityValue(1, 10) + ); + yield return new (AbsorbedDoseOfIonizingRadiationUnit.Megagray, "Megagray", "Megagrays", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (AbsorbedDoseOfIonizingRadiationUnit.Megarad, "Megarad", "Megarads", BaseUnits.Undefined, + new QuantityValue(1, 10000) + ); + yield return new (AbsorbedDoseOfIonizingRadiationUnit.Microgray, "Microgray", "Micrograys", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second), + 1000000 + ); + yield return new (AbsorbedDoseOfIonizingRadiationUnit.Milligray, "Milligray", "Milligrays", BaseUnits.Undefined, + 1000 + ); + yield return new (AbsorbedDoseOfIonizingRadiationUnit.Millirad, "Millirad", "Millirads", BaseUnits.Undefined, + 100000 + ); + yield return new (AbsorbedDoseOfIonizingRadiationUnit.Nanogray, "Nanogray", "Nanograys", BaseUnits.Undefined, + 1000000000 + ); + yield return new (AbsorbedDoseOfIonizingRadiationUnit.Petagray, "Petagray", "Petagrays", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000000) + ); + yield return new (AbsorbedDoseOfIonizingRadiationUnit.Picogray, "Picogray", "Picograys", new BaseUnits(length: LengthUnit.Micrometer, time: DurationUnit.Second), + 1000000000000 + ); + yield return new (AbsorbedDoseOfIonizingRadiationUnit.Rad, "Rad", "Rads", BaseUnits.Undefined, + 100 + ); + yield return new (AbsorbedDoseOfIonizingRadiationUnit.Teragray, "Teragray", "Teragrays", new BaseUnits(length: LengthUnit.Megameter, time: DurationUnit.Second), + new QuantityValue(1, 1000000000000) + ); } } static AbsorbedDoseOfIonizingRadiation() { - Info = AbsorbedDoseOfIonizingRadiationInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(AbsorbedDoseOfIonizingRadiationInfo.CreateDefault); } /// @@ -151,7 +180,7 @@ static AbsorbedDoseOfIonizingRadiation() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public AbsorbedDoseOfIonizingRadiation(double value, AbsorbedDoseOfIonizingRadiationUnit unit) + public AbsorbedDoseOfIonizingRadiation(QuantityValue value, AbsorbedDoseOfIonizingRadiationUnit unit) { _value = value; _unit = unit; @@ -165,7 +194,7 @@ public AbsorbedDoseOfIonizingRadiation(double value, AbsorbedDoseOfIonizingRadia /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public AbsorbedDoseOfIonizingRadiation(double value, UnitSystem unitSystem) + public AbsorbedDoseOfIonizingRadiation(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -176,7 +205,8 @@ public AbsorbedDoseOfIonizingRadiation(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -205,10 +235,8 @@ public AbsorbedDoseOfIonizingRadiation(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public AbsorbedDoseOfIonizingRadiationUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -247,140 +275,94 @@ public AbsorbedDoseOfIonizingRadiation(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Centigrays => As(AbsorbedDoseOfIonizingRadiationUnit.Centigray); + public QuantityValue Centigrays => this.As(AbsorbedDoseOfIonizingRadiationUnit.Centigray); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Decigrays => As(AbsorbedDoseOfIonizingRadiationUnit.Decigray); + public QuantityValue Decigrays => this.As(AbsorbedDoseOfIonizingRadiationUnit.Decigray); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Femtograys => As(AbsorbedDoseOfIonizingRadiationUnit.Femtogray); + public QuantityValue Femtograys => this.As(AbsorbedDoseOfIonizingRadiationUnit.Femtogray); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigagrays => As(AbsorbedDoseOfIonizingRadiationUnit.Gigagray); + public QuantityValue Gigagrays => this.As(AbsorbedDoseOfIonizingRadiationUnit.Gigagray); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Grays => As(AbsorbedDoseOfIonizingRadiationUnit.Gray); + public QuantityValue Grays => this.As(AbsorbedDoseOfIonizingRadiationUnit.Gray); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilograys => As(AbsorbedDoseOfIonizingRadiationUnit.Kilogray); + public QuantityValue Kilograys => this.As(AbsorbedDoseOfIonizingRadiationUnit.Kilogray); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilorads => As(AbsorbedDoseOfIonizingRadiationUnit.Kilorad); + public QuantityValue Kilorads => this.As(AbsorbedDoseOfIonizingRadiationUnit.Kilorad); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megagrays => As(AbsorbedDoseOfIonizingRadiationUnit.Megagray); + public QuantityValue Megagrays => this.As(AbsorbedDoseOfIonizingRadiationUnit.Megagray); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megarads => As(AbsorbedDoseOfIonizingRadiationUnit.Megarad); + public QuantityValue Megarads => this.As(AbsorbedDoseOfIonizingRadiationUnit.Megarad); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Micrograys => As(AbsorbedDoseOfIonizingRadiationUnit.Microgray); + public QuantityValue Micrograys => this.As(AbsorbedDoseOfIonizingRadiationUnit.Microgray); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Milligrays => As(AbsorbedDoseOfIonizingRadiationUnit.Milligray); + public QuantityValue Milligrays => this.As(AbsorbedDoseOfIonizingRadiationUnit.Milligray); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millirads => As(AbsorbedDoseOfIonizingRadiationUnit.Millirad); + public QuantityValue Millirads => this.As(AbsorbedDoseOfIonizingRadiationUnit.Millirad); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanograys => As(AbsorbedDoseOfIonizingRadiationUnit.Nanogray); + public QuantityValue Nanograys => this.As(AbsorbedDoseOfIonizingRadiationUnit.Nanogray); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Petagrays => As(AbsorbedDoseOfIonizingRadiationUnit.Petagray); + public QuantityValue Petagrays => this.As(AbsorbedDoseOfIonizingRadiationUnit.Petagray); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Picograys => As(AbsorbedDoseOfIonizingRadiationUnit.Picogray); + public QuantityValue Picograys => this.As(AbsorbedDoseOfIonizingRadiationUnit.Picogray); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Rads => As(AbsorbedDoseOfIonizingRadiationUnit.Rad); + public QuantityValue Rads => this.As(AbsorbedDoseOfIonizingRadiationUnit.Rad); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Teragrays => As(AbsorbedDoseOfIonizingRadiationUnit.Teragray); + public QuantityValue Teragrays => this.As(AbsorbedDoseOfIonizingRadiationUnit.Teragray); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: AbsorbedDoseOfIonizingRadiationUnit -> BaseUnit - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Centigray, AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Gray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Decigray, AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Gray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Femtogray, AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Gray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gigagray, AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Gray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Kilogray, AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Gray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Kilorad, AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Gray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Megagray, AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Gray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Megarad, AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Gray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Microgray, AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Gray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Milligray, AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Gray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Millirad, AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Gray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Nanogray, AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Gray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Petagray, AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Gray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Picogray, AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Gray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Rad, AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Gray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Teragray, AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Gray)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Gray, quantity => quantity); - - // Register in unit converter: BaseUnit -> AbsorbedDoseOfIonizingRadiationUnit - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Centigray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Centigray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Decigray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Decigray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Femtogray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Femtogray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Gigagray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Gigagray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Kilogray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Kilogray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Kilorad, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Kilorad)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Megagray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Megagray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Megarad, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Megarad)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Microgray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Microgray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Milligray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Milligray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Millirad, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Millirad)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Nanogray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Nanogray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Petagray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Petagray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Picogray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Picogray)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Rad, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Rad)); - unitConverter.SetConversionFunction(AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Teragray, quantity => quantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit.Teragray)); - } - /// /// Get unit abbreviation string. /// @@ -409,7 +391,7 @@ public static string GetAbbreviation(AbsorbedDoseOfIonizingRadiationUnit unit, I /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromCentigrays(double value) + public static AbsorbedDoseOfIonizingRadiation FromCentigrays(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Centigray); } @@ -417,7 +399,7 @@ public static AbsorbedDoseOfIonizingRadiation FromCentigrays(double value) /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromDecigrays(double value) + public static AbsorbedDoseOfIonizingRadiation FromDecigrays(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Decigray); } @@ -425,7 +407,7 @@ public static AbsorbedDoseOfIonizingRadiation FromDecigrays(double value) /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromFemtograys(double value) + public static AbsorbedDoseOfIonizingRadiation FromFemtograys(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Femtogray); } @@ -433,7 +415,7 @@ public static AbsorbedDoseOfIonizingRadiation FromFemtograys(double value) /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromGigagrays(double value) + public static AbsorbedDoseOfIonizingRadiation FromGigagrays(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Gigagray); } @@ -441,7 +423,7 @@ public static AbsorbedDoseOfIonizingRadiation FromGigagrays(double value) /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromGrays(double value) + public static AbsorbedDoseOfIonizingRadiation FromGrays(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Gray); } @@ -449,7 +431,7 @@ public static AbsorbedDoseOfIonizingRadiation FromGrays(double value) /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromKilograys(double value) + public static AbsorbedDoseOfIonizingRadiation FromKilograys(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Kilogray); } @@ -457,7 +439,7 @@ public static AbsorbedDoseOfIonizingRadiation FromKilograys(double value) /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromKilorads(double value) + public static AbsorbedDoseOfIonizingRadiation FromKilorads(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Kilorad); } @@ -465,7 +447,7 @@ public static AbsorbedDoseOfIonizingRadiation FromKilorads(double value) /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromMegagrays(double value) + public static AbsorbedDoseOfIonizingRadiation FromMegagrays(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Megagray); } @@ -473,7 +455,7 @@ public static AbsorbedDoseOfIonizingRadiation FromMegagrays(double value) /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromMegarads(double value) + public static AbsorbedDoseOfIonizingRadiation FromMegarads(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Megarad); } @@ -481,7 +463,7 @@ public static AbsorbedDoseOfIonizingRadiation FromMegarads(double value) /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromMicrograys(double value) + public static AbsorbedDoseOfIonizingRadiation FromMicrograys(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Microgray); } @@ -489,7 +471,7 @@ public static AbsorbedDoseOfIonizingRadiation FromMicrograys(double value) /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromMilligrays(double value) + public static AbsorbedDoseOfIonizingRadiation FromMilligrays(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Milligray); } @@ -497,7 +479,7 @@ public static AbsorbedDoseOfIonizingRadiation FromMilligrays(double value) /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromMillirads(double value) + public static AbsorbedDoseOfIonizingRadiation FromMillirads(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Millirad); } @@ -505,7 +487,7 @@ public static AbsorbedDoseOfIonizingRadiation FromMillirads(double value) /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromNanograys(double value) + public static AbsorbedDoseOfIonizingRadiation FromNanograys(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Nanogray); } @@ -513,7 +495,7 @@ public static AbsorbedDoseOfIonizingRadiation FromNanograys(double value) /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromPetagrays(double value) + public static AbsorbedDoseOfIonizingRadiation FromPetagrays(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Petagray); } @@ -521,7 +503,7 @@ public static AbsorbedDoseOfIonizingRadiation FromPetagrays(double value) /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromPicograys(double value) + public static AbsorbedDoseOfIonizingRadiation FromPicograys(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Picogray); } @@ -529,7 +511,7 @@ public static AbsorbedDoseOfIonizingRadiation FromPicograys(double value) /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromRads(double value) + public static AbsorbedDoseOfIonizingRadiation FromRads(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Rad); } @@ -537,7 +519,7 @@ public static AbsorbedDoseOfIonizingRadiation FromRads(double value) /// /// Creates a from . /// - public static AbsorbedDoseOfIonizingRadiation FromTeragrays(double value) + public static AbsorbedDoseOfIonizingRadiation FromTeragrays(QuantityValue value) { return new AbsorbedDoseOfIonizingRadiation(value, AbsorbedDoseOfIonizingRadiationUnit.Teragray); } @@ -548,7 +530,7 @@ public static AbsorbedDoseOfIonizingRadiation FromTeragrays(double value) /// Value to convert from. /// Unit to convert from. /// AbsorbedDoseOfIonizingRadiation unit value. - public static AbsorbedDoseOfIonizingRadiation From(double value, AbsorbedDoseOfIonizingRadiationUnit fromUnit) + public static AbsorbedDoseOfIonizingRadiation From(QuantityValue value, AbsorbedDoseOfIonizingRadiationUnit fromUnit) { return new AbsorbedDoseOfIonizingRadiation(value, fromUnit); } @@ -609,10 +591,7 @@ public static AbsorbedDoseOfIonizingRadiation Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static AbsorbedDoseOfIonizingRadiation Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -640,11 +619,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out AbsorbedDoseOfIo /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out AbsorbedDoseOfIonizingRadiation result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -665,7 +640,7 @@ public static AbsorbedDoseOfIonizingRadiationUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -676,7 +651,7 @@ public static AbsorbedDoseOfIonizingRadiationUnit ParseUnit(string str, IFormatP return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out AbsorbedDoseOfIonizingRadiationUnit unit) { return TryParseUnit(str, null, out unit); @@ -691,7 +666,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out AbsorbedDose /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out AbsorbedDoseOfIonizingRadiationUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -710,35 +685,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static AbsorbedDoseOfIonizingRadiation operator +(AbsorbedDoseOfIonizingRadiation left, AbsorbedDoseOfIonizingRadiation right) { - return new AbsorbedDoseOfIonizingRadiation(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new AbsorbedDoseOfIonizingRadiation(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static AbsorbedDoseOfIonizingRadiation operator -(AbsorbedDoseOfIonizingRadiation left, AbsorbedDoseOfIonizingRadiation right) { - return new AbsorbedDoseOfIonizingRadiation(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new AbsorbedDoseOfIonizingRadiation(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static AbsorbedDoseOfIonizingRadiation operator *(double left, AbsorbedDoseOfIonizingRadiation right) + public static AbsorbedDoseOfIonizingRadiation operator *(QuantityValue left, AbsorbedDoseOfIonizingRadiation right) { return new AbsorbedDoseOfIonizingRadiation(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static AbsorbedDoseOfIonizingRadiation operator *(AbsorbedDoseOfIonizingRadiation left, double right) + public static AbsorbedDoseOfIonizingRadiation operator *(AbsorbedDoseOfIonizingRadiation left, QuantityValue right) { return new AbsorbedDoseOfIonizingRadiation(left.Value * right, left.Unit); } /// Get from dividing by value. - public static AbsorbedDoseOfIonizingRadiation operator /(AbsorbedDoseOfIonizingRadiation left, double right) + public static AbsorbedDoseOfIonizingRadiation operator /(AbsorbedDoseOfIonizingRadiation left, QuantityValue right) { return new AbsorbedDoseOfIonizingRadiation(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(AbsorbedDoseOfIonizingRadiation left, AbsorbedDoseOfIonizingRadiation right) + public static QuantityValue operator /(AbsorbedDoseOfIonizingRadiation left, AbsorbedDoseOfIonizingRadiation right) { return left.Grays / right.Grays; } @@ -750,97 +725,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(AbsorbedDoseOfIonizingRadiation left, AbsorbedDoseOfIonizingRadiation right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(AbsorbedDoseOfIonizingRadiation left, AbsorbedDoseOfIonizingRadiation right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(AbsorbedDoseOfIonizingRadiation left, AbsorbedDoseOfIonizingRadiation right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(AbsorbedDoseOfIonizingRadiation left, AbsorbedDoseOfIonizingRadiation right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(AbsorbedDoseOfIonizingRadiation other, AbsorbedDoseOfIonizingRadiation tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(AbsorbedDoseOfIonizingRadiation left, AbsorbedDoseOfIonizingRadiation right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(AbsorbedDoseOfIonizingRadiation other, AbsorbedDoseOfIonizingRadiation tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(AbsorbedDoseOfIonizingRadiation left, AbsorbedDoseOfIonizingRadiation right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(AbsorbedDoseOfIonizingRadiation other, AbsorbedDoseOfIonizingRadiation tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is AbsorbedDoseOfIonizingRadiation otherQuantity)) + if (obj is not AbsorbedDoseOfIonizingRadiation otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(AbsorbedDoseOfIonizingRadiation other, AbsorbedDoseOfIonizingRadiation tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(AbsorbedDoseOfIonizingRadiation other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current AbsorbedDoseOfIonizingRadiation. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(AbsorbedDoseOfIonizingRadiation), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is AbsorbedDoseOfIonizingRadiation otherQuantity)) throw new ArgumentException("Expected type AbsorbedDoseOfIonizingRadiation.", nameof(obj)); + if (obj is not AbsorbedDoseOfIonizingRadiation otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -852,178 +812,24 @@ public int CompareTo(object? obj) /// public int CompareTo(AbsorbedDoseOfIonizingRadiation other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AbsorbedDoseOfIonizingRadiationUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this AbsorbedDoseOfIonizingRadiation to another AbsorbedDoseOfIonizingRadiation with the unit representation . - /// - /// The unit to convert to. - /// A AbsorbedDoseOfIonizingRadiation with the specified unit. - public AbsorbedDoseOfIonizingRadiation ToUnit(AbsorbedDoseOfIonizingRadiationUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A AbsorbedDoseOfIonizingRadiation with the specified unit. - public AbsorbedDoseOfIonizingRadiation ToUnit(AbsorbedDoseOfIonizingRadiationUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(AbsorbedDoseOfIonizingRadiation), Unit, typeof(AbsorbedDoseOfIonizingRadiation), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (AbsorbedDoseOfIonizingRadiation)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(AbsorbedDoseOfIonizingRadiationUnit unit, [NotNullWhen(true)] out AbsorbedDoseOfIonizingRadiation? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - AbsorbedDoseOfIonizingRadiation? convertedOrNull = (Unit, unit) switch - { - // AbsorbedDoseOfIonizingRadiationUnit -> BaseUnit - (AbsorbedDoseOfIonizingRadiationUnit.Centigray, AbsorbedDoseOfIonizingRadiationUnit.Gray) => new AbsorbedDoseOfIonizingRadiation((_value) * 1e-2d, AbsorbedDoseOfIonizingRadiationUnit.Gray), - (AbsorbedDoseOfIonizingRadiationUnit.Decigray, AbsorbedDoseOfIonizingRadiationUnit.Gray) => new AbsorbedDoseOfIonizingRadiation((_value) * 1e-1d, AbsorbedDoseOfIonizingRadiationUnit.Gray), - (AbsorbedDoseOfIonizingRadiationUnit.Femtogray, AbsorbedDoseOfIonizingRadiationUnit.Gray) => new AbsorbedDoseOfIonizingRadiation((_value) * 1e-15d, AbsorbedDoseOfIonizingRadiationUnit.Gray), - (AbsorbedDoseOfIonizingRadiationUnit.Gigagray, AbsorbedDoseOfIonizingRadiationUnit.Gray) => new AbsorbedDoseOfIonizingRadiation((_value) * 1e9d, AbsorbedDoseOfIonizingRadiationUnit.Gray), - (AbsorbedDoseOfIonizingRadiationUnit.Kilogray, AbsorbedDoseOfIonizingRadiationUnit.Gray) => new AbsorbedDoseOfIonizingRadiation((_value) * 1e3d, AbsorbedDoseOfIonizingRadiationUnit.Gray), - (AbsorbedDoseOfIonizingRadiationUnit.Kilorad, AbsorbedDoseOfIonizingRadiationUnit.Gray) => new AbsorbedDoseOfIonizingRadiation((_value / 100) * 1e3d, AbsorbedDoseOfIonizingRadiationUnit.Gray), - (AbsorbedDoseOfIonizingRadiationUnit.Megagray, AbsorbedDoseOfIonizingRadiationUnit.Gray) => new AbsorbedDoseOfIonizingRadiation((_value) * 1e6d, AbsorbedDoseOfIonizingRadiationUnit.Gray), - (AbsorbedDoseOfIonizingRadiationUnit.Megarad, AbsorbedDoseOfIonizingRadiationUnit.Gray) => new AbsorbedDoseOfIonizingRadiation((_value / 100) * 1e6d, AbsorbedDoseOfIonizingRadiationUnit.Gray), - (AbsorbedDoseOfIonizingRadiationUnit.Microgray, AbsorbedDoseOfIonizingRadiationUnit.Gray) => new AbsorbedDoseOfIonizingRadiation((_value) * 1e-6d, AbsorbedDoseOfIonizingRadiationUnit.Gray), - (AbsorbedDoseOfIonizingRadiationUnit.Milligray, AbsorbedDoseOfIonizingRadiationUnit.Gray) => new AbsorbedDoseOfIonizingRadiation((_value) * 1e-3d, AbsorbedDoseOfIonizingRadiationUnit.Gray), - (AbsorbedDoseOfIonizingRadiationUnit.Millirad, AbsorbedDoseOfIonizingRadiationUnit.Gray) => new AbsorbedDoseOfIonizingRadiation((_value / 100) * 1e-3d, AbsorbedDoseOfIonizingRadiationUnit.Gray), - (AbsorbedDoseOfIonizingRadiationUnit.Nanogray, AbsorbedDoseOfIonizingRadiationUnit.Gray) => new AbsorbedDoseOfIonizingRadiation((_value) * 1e-9d, AbsorbedDoseOfIonizingRadiationUnit.Gray), - (AbsorbedDoseOfIonizingRadiationUnit.Petagray, AbsorbedDoseOfIonizingRadiationUnit.Gray) => new AbsorbedDoseOfIonizingRadiation((_value) * 1e15d, AbsorbedDoseOfIonizingRadiationUnit.Gray), - (AbsorbedDoseOfIonizingRadiationUnit.Picogray, AbsorbedDoseOfIonizingRadiationUnit.Gray) => new AbsorbedDoseOfIonizingRadiation((_value) * 1e-12d, AbsorbedDoseOfIonizingRadiationUnit.Gray), - (AbsorbedDoseOfIonizingRadiationUnit.Rad, AbsorbedDoseOfIonizingRadiationUnit.Gray) => new AbsorbedDoseOfIonizingRadiation(_value / 100, AbsorbedDoseOfIonizingRadiationUnit.Gray), - (AbsorbedDoseOfIonizingRadiationUnit.Teragray, AbsorbedDoseOfIonizingRadiationUnit.Gray) => new AbsorbedDoseOfIonizingRadiation((_value) * 1e12d, AbsorbedDoseOfIonizingRadiationUnit.Gray), - - // BaseUnit -> AbsorbedDoseOfIonizingRadiationUnit - (AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Centigray) => new AbsorbedDoseOfIonizingRadiation((_value) / 1e-2d, AbsorbedDoseOfIonizingRadiationUnit.Centigray), - (AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Decigray) => new AbsorbedDoseOfIonizingRadiation((_value) / 1e-1d, AbsorbedDoseOfIonizingRadiationUnit.Decigray), - (AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Femtogray) => new AbsorbedDoseOfIonizingRadiation((_value) / 1e-15d, AbsorbedDoseOfIonizingRadiationUnit.Femtogray), - (AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Gigagray) => new AbsorbedDoseOfIonizingRadiation((_value) / 1e9d, AbsorbedDoseOfIonizingRadiationUnit.Gigagray), - (AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Kilogray) => new AbsorbedDoseOfIonizingRadiation((_value) / 1e3d, AbsorbedDoseOfIonizingRadiationUnit.Kilogray), - (AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Kilorad) => new AbsorbedDoseOfIonizingRadiation((_value * 100) / 1e3d, AbsorbedDoseOfIonizingRadiationUnit.Kilorad), - (AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Megagray) => new AbsorbedDoseOfIonizingRadiation((_value) / 1e6d, AbsorbedDoseOfIonizingRadiationUnit.Megagray), - (AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Megarad) => new AbsorbedDoseOfIonizingRadiation((_value * 100) / 1e6d, AbsorbedDoseOfIonizingRadiationUnit.Megarad), - (AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Microgray) => new AbsorbedDoseOfIonizingRadiation((_value) / 1e-6d, AbsorbedDoseOfIonizingRadiationUnit.Microgray), - (AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Milligray) => new AbsorbedDoseOfIonizingRadiation((_value) / 1e-3d, AbsorbedDoseOfIonizingRadiationUnit.Milligray), - (AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Millirad) => new AbsorbedDoseOfIonizingRadiation((_value * 100) / 1e-3d, AbsorbedDoseOfIonizingRadiationUnit.Millirad), - (AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Nanogray) => new AbsorbedDoseOfIonizingRadiation((_value) / 1e-9d, AbsorbedDoseOfIonizingRadiationUnit.Nanogray), - (AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Petagray) => new AbsorbedDoseOfIonizingRadiation((_value) / 1e15d, AbsorbedDoseOfIonizingRadiationUnit.Petagray), - (AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Picogray) => new AbsorbedDoseOfIonizingRadiation((_value) / 1e-12d, AbsorbedDoseOfIonizingRadiationUnit.Picogray), - (AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Rad) => new AbsorbedDoseOfIonizingRadiation(_value * 100, AbsorbedDoseOfIonizingRadiationUnit.Rad), - (AbsorbedDoseOfIonizingRadiationUnit.Gray, AbsorbedDoseOfIonizingRadiationUnit.Teragray) => new AbsorbedDoseOfIonizingRadiation((_value) / 1e12d, AbsorbedDoseOfIonizingRadiationUnit.Teragray), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public AbsorbedDoseOfIonizingRadiation ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not AbsorbedDoseOfIonizingRadiationUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AbsorbedDoseOfIonizingRadiationUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is AbsorbedDoseOfIonizingRadiationUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AbsorbedDoseOfIonizingRadiationUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(AbsorbedDoseOfIonizingRadiationUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1038,7 +844,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs b/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs index f6a9d49a5c..419330665a 100644 --- a/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Acceleration.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Acceleration : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -57,13 +56,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly AccelerationUnit? _unit; /// @@ -108,7 +107,7 @@ public static AccelerationInfo CreateDefault(Func - /// The for is [T^-2][L]. + /// The for is T^-2L. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 0, -2, 0, 0, 0, 0); @@ -123,28 +122,52 @@ public static AccelerationInfo CreateDefault(FuncAn of representing the default unit mappings for Acceleration. public static IEnumerable> GetDefaultMappings() { - yield return new (AccelerationUnit.CentimeterPerSecondSquared, "CentimeterPerSecondSquared", "CentimetersPerSecondSquared", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Second)); - yield return new (AccelerationUnit.DecimeterPerSecondSquared, "DecimeterPerSecondSquared", "DecimetersPerSecondSquared", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Second)); - yield return new (AccelerationUnit.FootPerSecondSquared, "FootPerSecondSquared", "FeetPerSecondSquared", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second)); - yield return new (AccelerationUnit.InchPerSecondSquared, "InchPerSecondSquared", "InchesPerSecondSquared", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Second)); - yield return new (AccelerationUnit.KilometerPerSecondSquared, "KilometerPerSecondSquared", "KilometersPerSecondSquared", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second)); - yield return new (AccelerationUnit.KnotPerHour, "KnotPerHour", "KnotsPerHour", new BaseUnits(length: LengthUnit.NauticalMile, time: DurationUnit.Hour)); - yield return new (AccelerationUnit.KnotPerMinute, "KnotPerMinute", "KnotsPerMinute", new BaseUnits(length: LengthUnit.NauticalMile, time: DurationUnit.Minute)); - yield return new (AccelerationUnit.KnotPerSecond, "KnotPerSecond", "KnotsPerSecond", new BaseUnits(length: LengthUnit.NauticalMile, time: DurationUnit.Second)); + yield return new (AccelerationUnit.CentimeterPerSecondSquared, "CentimeterPerSecondSquared", "CentimetersPerSecondSquared", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Second), + 100 + ); + yield return new (AccelerationUnit.DecimeterPerSecondSquared, "DecimeterPerSecondSquared", "DecimetersPerSecondSquared", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Second), + 10 + ); + yield return new (AccelerationUnit.FootPerSecondSquared, "FootPerSecondSquared", "FeetPerSecondSquared", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second), + new QuantityValue(1250, 381) + ); + yield return new (AccelerationUnit.InchPerSecondSquared, "InchPerSecondSquared", "InchesPerSecondSquared", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Second), + new QuantityValue(5000, 127) + ); + yield return new (AccelerationUnit.KilometerPerSecondSquared, "KilometerPerSecondSquared", "KilometersPerSecondSquared", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second), + new QuantityValue(1, 1000) + ); + yield return new (AccelerationUnit.KnotPerHour, "KnotPerHour", "KnotsPerHour", new BaseUnits(length: LengthUnit.NauticalMile, time: DurationUnit.Hour), + new QuantityValue(3240000, 463) + ); + yield return new (AccelerationUnit.KnotPerMinute, "KnotPerMinute", "KnotsPerMinute", new BaseUnits(length: LengthUnit.NauticalMile, time: DurationUnit.Minute), + new QuantityValue(54000, 463) + ); + yield return new (AccelerationUnit.KnotPerSecond, "KnotPerSecond", "KnotsPerSecond", new BaseUnits(length: LengthUnit.NauticalMile, time: DurationUnit.Second), + new QuantityValue(900, 463) + ); yield return new (AccelerationUnit.MeterPerSecondSquared, "MeterPerSecondSquared", "MetersPerSecondSquared", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)); - yield return new (AccelerationUnit.MicrometerPerSecondSquared, "MicrometerPerSecondSquared", "MicrometersPerSecondSquared", new BaseUnits(length: LengthUnit.Micrometer, time: DurationUnit.Second)); - yield return new (AccelerationUnit.MillimeterPerSecondSquared, "MillimeterPerSecondSquared", "MillimetersPerSecondSquared", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second)); - yield return new (AccelerationUnit.MillistandardGravity, "MillistandardGravity", "MillistandardGravity", BaseUnits.Undefined); - yield return new (AccelerationUnit.NanometerPerSecondSquared, "NanometerPerSecondSquared", "NanometersPerSecondSquared", new BaseUnits(length: LengthUnit.Nanometer, time: DurationUnit.Second)); - yield return new (AccelerationUnit.StandardGravity, "StandardGravity", "StandardGravity", BaseUnits.Undefined); + yield return new (AccelerationUnit.MicrometerPerSecondSquared, "MicrometerPerSecondSquared", "MicrometersPerSecondSquared", new BaseUnits(length: LengthUnit.Micrometer, time: DurationUnit.Second), + 1000000 + ); + yield return new (AccelerationUnit.MillimeterPerSecondSquared, "MillimeterPerSecondSquared", "MillimetersPerSecondSquared", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second), + 1000 + ); + yield return new (AccelerationUnit.MillistandardGravity, "MillistandardGravity", "MillistandardGravity", BaseUnits.Undefined, + new QuantityValue(20000000, 196133) + ); + yield return new (AccelerationUnit.NanometerPerSecondSquared, "NanometerPerSecondSquared", "NanometersPerSecondSquared", new BaseUnits(length: LengthUnit.Nanometer, time: DurationUnit.Second), + 1000000000 + ); + yield return new (AccelerationUnit.StandardGravity, "StandardGravity", "StandardGravity", BaseUnits.Undefined, + new QuantityValue(20000, 196133) + ); } } static Acceleration() { - Info = AccelerationInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(AccelerationInfo.CreateDefault); } /// @@ -152,7 +175,7 @@ static Acceleration() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Acceleration(double value, AccelerationUnit unit) + public Acceleration(QuantityValue value, AccelerationUnit unit) { _value = value; _unit = unit; @@ -166,7 +189,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -177,7 +200,8 @@ public Acceleration(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -206,10 +230,8 @@ public Acceleration(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public AccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -248,119 +270,79 @@ public Acceleration(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentimetersPerSecondSquared => As(AccelerationUnit.CentimeterPerSecondSquared); + public QuantityValue CentimetersPerSecondSquared => this.As(AccelerationUnit.CentimeterPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecimetersPerSecondSquared => As(AccelerationUnit.DecimeterPerSecondSquared); + public QuantityValue DecimetersPerSecondSquared => this.As(AccelerationUnit.DecimeterPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double FeetPerSecondSquared => As(AccelerationUnit.FootPerSecondSquared); + public QuantityValue FeetPerSecondSquared => this.As(AccelerationUnit.FootPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InchesPerSecondSquared => As(AccelerationUnit.InchPerSecondSquared); + public QuantityValue InchesPerSecondSquared => this.As(AccelerationUnit.InchPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilometersPerSecondSquared => As(AccelerationUnit.KilometerPerSecondSquared); + public QuantityValue KilometersPerSecondSquared => this.As(AccelerationUnit.KilometerPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KnotsPerHour => As(AccelerationUnit.KnotPerHour); + public QuantityValue KnotsPerHour => this.As(AccelerationUnit.KnotPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KnotsPerMinute => As(AccelerationUnit.KnotPerMinute); + public QuantityValue KnotsPerMinute => this.As(AccelerationUnit.KnotPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KnotsPerSecond => As(AccelerationUnit.KnotPerSecond); + public QuantityValue KnotsPerSecond => this.As(AccelerationUnit.KnotPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MetersPerSecondSquared => As(AccelerationUnit.MeterPerSecondSquared); + public QuantityValue MetersPerSecondSquared => this.As(AccelerationUnit.MeterPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrometersPerSecondSquared => As(AccelerationUnit.MicrometerPerSecondSquared); + public QuantityValue MicrometersPerSecondSquared => this.As(AccelerationUnit.MicrometerPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimetersPerSecondSquared => As(AccelerationUnit.MillimeterPerSecondSquared); + public QuantityValue MillimetersPerSecondSquared => this.As(AccelerationUnit.MillimeterPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillistandardGravity => As(AccelerationUnit.MillistandardGravity); + public QuantityValue MillistandardGravity => this.As(AccelerationUnit.MillistandardGravity); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanometersPerSecondSquared => As(AccelerationUnit.NanometerPerSecondSquared); + public QuantityValue NanometersPerSecondSquared => this.As(AccelerationUnit.NanometerPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double StandardGravity => As(AccelerationUnit.StandardGravity); + public QuantityValue StandardGravity => this.As(AccelerationUnit.StandardGravity); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: AccelerationUnit -> BaseUnit - unitConverter.SetConversionFunction(AccelerationUnit.CentimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.DecimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.FootPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.InchPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.KilometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.KnotPerHour, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.KnotPerMinute, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.KnotPerSecond, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MicrometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MillimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MillistandardGravity, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.NanometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.StandardGravity, AccelerationUnit.MeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MeterPerSecondSquared)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared, quantity => quantity); - - // Register in unit converter: BaseUnit -> AccelerationUnit - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.CentimeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.CentimeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.DecimeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.DecimeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.FootPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.FootPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.InchPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.InchPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KilometerPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.KilometerPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerHour, quantity => quantity.ToUnit(AccelerationUnit.KnotPerHour)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerMinute, quantity => quantity.ToUnit(AccelerationUnit.KnotPerMinute)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerSecond, quantity => quantity.ToUnit(AccelerationUnit.KnotPerSecond)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MicrometerPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MicrometerPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MillimeterPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.MillimeterPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MillistandardGravity, quantity => quantity.ToUnit(AccelerationUnit.MillistandardGravity)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.NanometerPerSecondSquared, quantity => quantity.ToUnit(AccelerationUnit.NanometerPerSecondSquared)); - unitConverter.SetConversionFunction(AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.StandardGravity, quantity => quantity.ToUnit(AccelerationUnit.StandardGravity)); - } - /// /// Get unit abbreviation string. /// @@ -389,7 +371,7 @@ public static string GetAbbreviation(AccelerationUnit unit, IFormatProvider? pro /// /// Creates a from . /// - public static Acceleration FromCentimetersPerSecondSquared(double value) + public static Acceleration FromCentimetersPerSecondSquared(QuantityValue value) { return new Acceleration(value, AccelerationUnit.CentimeterPerSecondSquared); } @@ -397,7 +379,7 @@ public static Acceleration FromCentimetersPerSecondSquared(double value) /// /// Creates a from . /// - public static Acceleration FromDecimetersPerSecondSquared(double value) + public static Acceleration FromDecimetersPerSecondSquared(QuantityValue value) { return new Acceleration(value, AccelerationUnit.DecimeterPerSecondSquared); } @@ -405,7 +387,7 @@ public static Acceleration FromDecimetersPerSecondSquared(double value) /// /// Creates a from . /// - public static Acceleration FromFeetPerSecondSquared(double value) + public static Acceleration FromFeetPerSecondSquared(QuantityValue value) { return new Acceleration(value, AccelerationUnit.FootPerSecondSquared); } @@ -413,7 +395,7 @@ public static Acceleration FromFeetPerSecondSquared(double value) /// /// Creates a from . /// - public static Acceleration FromInchesPerSecondSquared(double value) + public static Acceleration FromInchesPerSecondSquared(QuantityValue value) { return new Acceleration(value, AccelerationUnit.InchPerSecondSquared); } @@ -421,7 +403,7 @@ public static Acceleration FromInchesPerSecondSquared(double value) /// /// Creates a from . /// - public static Acceleration FromKilometersPerSecondSquared(double value) + public static Acceleration FromKilometersPerSecondSquared(QuantityValue value) { return new Acceleration(value, AccelerationUnit.KilometerPerSecondSquared); } @@ -429,7 +411,7 @@ public static Acceleration FromKilometersPerSecondSquared(double value) /// /// Creates a from . /// - public static Acceleration FromKnotsPerHour(double value) + public static Acceleration FromKnotsPerHour(QuantityValue value) { return new Acceleration(value, AccelerationUnit.KnotPerHour); } @@ -437,7 +419,7 @@ public static Acceleration FromKnotsPerHour(double value) /// /// Creates a from . /// - public static Acceleration FromKnotsPerMinute(double value) + public static Acceleration FromKnotsPerMinute(QuantityValue value) { return new Acceleration(value, AccelerationUnit.KnotPerMinute); } @@ -445,7 +427,7 @@ public static Acceleration FromKnotsPerMinute(double value) /// /// Creates a from . /// - public static Acceleration FromKnotsPerSecond(double value) + public static Acceleration FromKnotsPerSecond(QuantityValue value) { return new Acceleration(value, AccelerationUnit.KnotPerSecond); } @@ -453,7 +435,7 @@ public static Acceleration FromKnotsPerSecond(double value) /// /// Creates a from . /// - public static Acceleration FromMetersPerSecondSquared(double value) + public static Acceleration FromMetersPerSecondSquared(QuantityValue value) { return new Acceleration(value, AccelerationUnit.MeterPerSecondSquared); } @@ -461,7 +443,7 @@ public static Acceleration FromMetersPerSecondSquared(double value) /// /// Creates a from . /// - public static Acceleration FromMicrometersPerSecondSquared(double value) + public static Acceleration FromMicrometersPerSecondSquared(QuantityValue value) { return new Acceleration(value, AccelerationUnit.MicrometerPerSecondSquared); } @@ -469,7 +451,7 @@ public static Acceleration FromMicrometersPerSecondSquared(double value) /// /// Creates a from . /// - public static Acceleration FromMillimetersPerSecondSquared(double value) + public static Acceleration FromMillimetersPerSecondSquared(QuantityValue value) { return new Acceleration(value, AccelerationUnit.MillimeterPerSecondSquared); } @@ -477,7 +459,7 @@ public static Acceleration FromMillimetersPerSecondSquared(double value) /// /// Creates a from . /// - public static Acceleration FromMillistandardGravity(double value) + public static Acceleration FromMillistandardGravity(QuantityValue value) { return new Acceleration(value, AccelerationUnit.MillistandardGravity); } @@ -485,7 +467,7 @@ public static Acceleration FromMillistandardGravity(double value) /// /// Creates a from . /// - public static Acceleration FromNanometersPerSecondSquared(double value) + public static Acceleration FromNanometersPerSecondSquared(QuantityValue value) { return new Acceleration(value, AccelerationUnit.NanometerPerSecondSquared); } @@ -493,7 +475,7 @@ public static Acceleration FromNanometersPerSecondSquared(double value) /// /// Creates a from . /// - public static Acceleration FromStandardGravity(double value) + public static Acceleration FromStandardGravity(QuantityValue value) { return new Acceleration(value, AccelerationUnit.StandardGravity); } @@ -504,7 +486,7 @@ public static Acceleration FromStandardGravity(double value) /// Value to convert from. /// Unit to convert from. /// Acceleration unit value. - public static Acceleration From(double value, AccelerationUnit fromUnit) + public static Acceleration From(QuantityValue value, AccelerationUnit fromUnit) { return new Acceleration(value, fromUnit); } @@ -565,10 +547,7 @@ public static Acceleration Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Acceleration Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -596,11 +575,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Acceleration res /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Acceleration result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -621,7 +596,7 @@ public static AccelerationUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -632,7 +607,7 @@ public static AccelerationUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out AccelerationUnit unit) { return TryParseUnit(str, null, out unit); @@ -647,7 +622,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out Acceleration /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out AccelerationUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -666,35 +641,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Acceleration operator +(Acceleration left, Acceleration right) { - return new Acceleration(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Acceleration(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Acceleration operator -(Acceleration left, Acceleration right) { - return new Acceleration(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Acceleration(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -740,97 +715,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Acceleration left, Acceleration right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Acceleration left, Acceleration right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Acceleration left, Acceleration right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Acceleration left, Acceleration right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Acceleration other, Acceleration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Acceleration left, Acceleration right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Acceleration other, Acceleration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Acceleration left, Acceleration right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Acceleration other, Acceleration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Acceleration otherQuantity)) + if (obj is not Acceleration otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Acceleration other, Acceleration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Acceleration other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Acceleration. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Acceleration), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Acceleration otherQuantity)) throw new ArgumentException("Expected type Acceleration.", nameof(obj)); + if (obj is not Acceleration otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -842,172 +802,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Acceleration other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AccelerationUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this Acceleration to another Acceleration with the unit representation . - /// - /// The unit to convert to. - /// A Acceleration with the specified unit. - public Acceleration ToUnit(AccelerationUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Acceleration with the specified unit. - public Acceleration ToUnit(AccelerationUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Acceleration), Unit, typeof(Acceleration), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Acceleration)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(AccelerationUnit unit, [NotNullWhen(true)] out Acceleration? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Acceleration? convertedOrNull = (Unit, unit) switch - { - // AccelerationUnit -> BaseUnit - (AccelerationUnit.CentimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared) => new Acceleration((_value) * 1e-2d, AccelerationUnit.MeterPerSecondSquared), - (AccelerationUnit.DecimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared) => new Acceleration((_value) * 1e-1d, AccelerationUnit.MeterPerSecondSquared), - (AccelerationUnit.FootPerSecondSquared, AccelerationUnit.MeterPerSecondSquared) => new Acceleration(_value * 0.304800, AccelerationUnit.MeterPerSecondSquared), - (AccelerationUnit.InchPerSecondSquared, AccelerationUnit.MeterPerSecondSquared) => new Acceleration(_value * 0.0254, AccelerationUnit.MeterPerSecondSquared), - (AccelerationUnit.KilometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared) => new Acceleration((_value) * 1e3d, AccelerationUnit.MeterPerSecondSquared), - (AccelerationUnit.KnotPerHour, AccelerationUnit.MeterPerSecondSquared) => new Acceleration(_value * (1852.0 / 3600.0) / 3600, AccelerationUnit.MeterPerSecondSquared), - (AccelerationUnit.KnotPerMinute, AccelerationUnit.MeterPerSecondSquared) => new Acceleration(_value * (1852.0 / 3600.0) / 60, AccelerationUnit.MeterPerSecondSquared), - (AccelerationUnit.KnotPerSecond, AccelerationUnit.MeterPerSecondSquared) => new Acceleration(_value * (1852.0 / 3600.0), AccelerationUnit.MeterPerSecondSquared), - (AccelerationUnit.MicrometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared) => new Acceleration((_value) * 1e-6d, AccelerationUnit.MeterPerSecondSquared), - (AccelerationUnit.MillimeterPerSecondSquared, AccelerationUnit.MeterPerSecondSquared) => new Acceleration((_value) * 1e-3d, AccelerationUnit.MeterPerSecondSquared), - (AccelerationUnit.MillistandardGravity, AccelerationUnit.MeterPerSecondSquared) => new Acceleration((_value * 9.80665) * 1e-3d, AccelerationUnit.MeterPerSecondSquared), - (AccelerationUnit.NanometerPerSecondSquared, AccelerationUnit.MeterPerSecondSquared) => new Acceleration((_value) * 1e-9d, AccelerationUnit.MeterPerSecondSquared), - (AccelerationUnit.StandardGravity, AccelerationUnit.MeterPerSecondSquared) => new Acceleration(_value * 9.80665, AccelerationUnit.MeterPerSecondSquared), - - // BaseUnit -> AccelerationUnit - (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.CentimeterPerSecondSquared) => new Acceleration((_value) / 1e-2d, AccelerationUnit.CentimeterPerSecondSquared), - (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.DecimeterPerSecondSquared) => new Acceleration((_value) / 1e-1d, AccelerationUnit.DecimeterPerSecondSquared), - (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.FootPerSecondSquared) => new Acceleration(_value / 0.304800, AccelerationUnit.FootPerSecondSquared), - (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.InchPerSecondSquared) => new Acceleration(_value / 0.0254, AccelerationUnit.InchPerSecondSquared), - (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KilometerPerSecondSquared) => new Acceleration((_value) / 1e3d, AccelerationUnit.KilometerPerSecondSquared), - (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerHour) => new Acceleration(_value * 3600 / (1852.0 / 3600.0), AccelerationUnit.KnotPerHour), - (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerMinute) => new Acceleration(_value * 60 / (1852.0 / 3600.0), AccelerationUnit.KnotPerMinute), - (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.KnotPerSecond) => new Acceleration(_value / (1852.0 / 3600.0), AccelerationUnit.KnotPerSecond), - (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MicrometerPerSecondSquared) => new Acceleration((_value) / 1e-6d, AccelerationUnit.MicrometerPerSecondSquared), - (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MillimeterPerSecondSquared) => new Acceleration((_value) / 1e-3d, AccelerationUnit.MillimeterPerSecondSquared), - (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.MillistandardGravity) => new Acceleration((_value / 9.80665) / 1e-3d, AccelerationUnit.MillistandardGravity), - (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.NanometerPerSecondSquared) => new Acceleration((_value) / 1e-9d, AccelerationUnit.NanometerPerSecondSquared), - (AccelerationUnit.MeterPerSecondSquared, AccelerationUnit.StandardGravity) => new Acceleration(_value / 9.80665, AccelerationUnit.StandardGravity), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Acceleration ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not AccelerationUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AccelerationUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(AccelerationUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(AccelerationUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1022,7 +834,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs index 5fa15becd6..bb09ee9756 100644 --- a/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AmountOfSubstance.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct AmountOfSubstance : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -58,13 +57,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly AmountOfSubstanceUnit? _unit; /// @@ -109,7 +108,7 @@ public static AmountOfSubstanceInfo CreateDefault(Func - /// The for is [N]. + /// The for is N. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 0, 0, 0, 1, 0); @@ -124,31 +123,61 @@ public static AmountOfSubstanceInfo CreateDefault(FuncAn of representing the default unit mappings for AmountOfSubstance. public static IEnumerable> GetDefaultMappings() { - yield return new (AmountOfSubstanceUnit.Centimole, "Centimole", "Centimoles", new BaseUnits(amount: AmountOfSubstanceUnit.Centimole)); - yield return new (AmountOfSubstanceUnit.CentipoundMole, "CentipoundMole", "CentipoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.CentipoundMole)); - yield return new (AmountOfSubstanceUnit.Decimole, "Decimole", "Decimoles", new BaseUnits(amount: AmountOfSubstanceUnit.Decimole)); - yield return new (AmountOfSubstanceUnit.DecipoundMole, "DecipoundMole", "DecipoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.DecipoundMole)); - yield return new (AmountOfSubstanceUnit.Femtomole, "Femtomole", "Femtomoles", new BaseUnits(amount: AmountOfSubstanceUnit.Femtomole)); - yield return new (AmountOfSubstanceUnit.Kilomole, "Kilomole", "Kilomoles", new BaseUnits(amount: AmountOfSubstanceUnit.Kilomole)); - yield return new (AmountOfSubstanceUnit.KilopoundMole, "KilopoundMole", "KilopoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.KilopoundMole)); - yield return new (AmountOfSubstanceUnit.Megamole, "Megamole", "Megamoles", new BaseUnits(amount: AmountOfSubstanceUnit.Megamole)); - yield return new (AmountOfSubstanceUnit.Micromole, "Micromole", "Micromoles", new BaseUnits(amount: AmountOfSubstanceUnit.Micromole)); - yield return new (AmountOfSubstanceUnit.MicropoundMole, "MicropoundMole", "MicropoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.MicropoundMole)); - yield return new (AmountOfSubstanceUnit.Millimole, "Millimole", "Millimoles", new BaseUnits(amount: AmountOfSubstanceUnit.Millimole)); - yield return new (AmountOfSubstanceUnit.MillipoundMole, "MillipoundMole", "MillipoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.MillipoundMole)); + yield return new (AmountOfSubstanceUnit.Centimole, "Centimole", "Centimoles", new BaseUnits(amount: AmountOfSubstanceUnit.Centimole), + 100 + ); + yield return new (AmountOfSubstanceUnit.CentipoundMole, "CentipoundMole", "CentipoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.CentipoundMole), + new QuantityValue(10000000, 45359237) + ); + yield return new (AmountOfSubstanceUnit.Decimole, "Decimole", "Decimoles", new BaseUnits(amount: AmountOfSubstanceUnit.Decimole), + 10 + ); + yield return new (AmountOfSubstanceUnit.DecipoundMole, "DecipoundMole", "DecipoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.DecipoundMole), + new QuantityValue(1000000, 45359237) + ); + yield return new (AmountOfSubstanceUnit.Femtomole, "Femtomole", "Femtomoles", new BaseUnits(amount: AmountOfSubstanceUnit.Femtomole), + 1000000000000000 + ); + yield return new (AmountOfSubstanceUnit.Kilomole, "Kilomole", "Kilomoles", new BaseUnits(amount: AmountOfSubstanceUnit.Kilomole), + new QuantityValue(1, 1000) + ); + yield return new (AmountOfSubstanceUnit.KilopoundMole, "KilopoundMole", "KilopoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.KilopoundMole), + new QuantityValue(100, 45359237) + ); + yield return new (AmountOfSubstanceUnit.Megamole, "Megamole", "Megamoles", new BaseUnits(amount: AmountOfSubstanceUnit.Megamole), + new QuantityValue(1, 1000000) + ); + yield return new (AmountOfSubstanceUnit.Micromole, "Micromole", "Micromoles", new BaseUnits(amount: AmountOfSubstanceUnit.Micromole), + 1000000 + ); + yield return new (AmountOfSubstanceUnit.MicropoundMole, "MicropoundMole", "MicropoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.MicropoundMole), + new QuantityValue(100000000000, 45359237) + ); + yield return new (AmountOfSubstanceUnit.Millimole, "Millimole", "Millimoles", new BaseUnits(amount: AmountOfSubstanceUnit.Millimole), + 1000 + ); + yield return new (AmountOfSubstanceUnit.MillipoundMole, "MillipoundMole", "MillipoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.MillipoundMole), + new QuantityValue(100000000, 45359237) + ); yield return new (AmountOfSubstanceUnit.Mole, "Mole", "Moles", new BaseUnits(amount: AmountOfSubstanceUnit.Mole)); - yield return new (AmountOfSubstanceUnit.Nanomole, "Nanomole", "Nanomoles", new BaseUnits(amount: AmountOfSubstanceUnit.Nanomole)); - yield return new (AmountOfSubstanceUnit.NanopoundMole, "NanopoundMole", "NanopoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.NanopoundMole)); - yield return new (AmountOfSubstanceUnit.Picomole, "Picomole", "Picomoles", new BaseUnits(amount: AmountOfSubstanceUnit.Picomole)); - yield return new (AmountOfSubstanceUnit.PoundMole, "PoundMole", "PoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.PoundMole)); + yield return new (AmountOfSubstanceUnit.Nanomole, "Nanomole", "Nanomoles", new BaseUnits(amount: AmountOfSubstanceUnit.Nanomole), + 1000000000 + ); + yield return new (AmountOfSubstanceUnit.NanopoundMole, "NanopoundMole", "NanopoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.NanopoundMole), + new QuantityValue(100000000000000, 45359237) + ); + yield return new (AmountOfSubstanceUnit.Picomole, "Picomole", "Picomoles", new BaseUnits(amount: AmountOfSubstanceUnit.Picomole), + 1000000000000 + ); + yield return new (AmountOfSubstanceUnit.PoundMole, "PoundMole", "PoundMoles", new BaseUnits(amount: AmountOfSubstanceUnit.PoundMole), + new QuantityValue(100000, 45359237) + ); } } static AmountOfSubstance() { - Info = AmountOfSubstanceInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(AmountOfSubstanceInfo.CreateDefault); } /// @@ -156,7 +185,7 @@ static AmountOfSubstance() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public AmountOfSubstance(double value, AmountOfSubstanceUnit unit) + public AmountOfSubstance(QuantityValue value, AmountOfSubstanceUnit unit) { _value = value; _unit = unit; @@ -170,7 +199,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -181,7 +210,8 @@ public AmountOfSubstance(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -210,10 +240,8 @@ public AmountOfSubstance(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public AmountOfSubstanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -252,140 +280,94 @@ public AmountOfSubstance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Centimoles => As(AmountOfSubstanceUnit.Centimole); + public QuantityValue Centimoles => this.As(AmountOfSubstanceUnit.Centimole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentipoundMoles => As(AmountOfSubstanceUnit.CentipoundMole); + public QuantityValue CentipoundMoles => this.As(AmountOfSubstanceUnit.CentipoundMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Decimoles => As(AmountOfSubstanceUnit.Decimole); + public QuantityValue Decimoles => this.As(AmountOfSubstanceUnit.Decimole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecipoundMoles => As(AmountOfSubstanceUnit.DecipoundMole); + public QuantityValue DecipoundMoles => this.As(AmountOfSubstanceUnit.DecipoundMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Femtomoles => As(AmountOfSubstanceUnit.Femtomole); + public QuantityValue Femtomoles => this.As(AmountOfSubstanceUnit.Femtomole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilomoles => As(AmountOfSubstanceUnit.Kilomole); + public QuantityValue Kilomoles => this.As(AmountOfSubstanceUnit.Kilomole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundMoles => As(AmountOfSubstanceUnit.KilopoundMole); + public QuantityValue KilopoundMoles => this.As(AmountOfSubstanceUnit.KilopoundMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megamoles => As(AmountOfSubstanceUnit.Megamole); + public QuantityValue Megamoles => this.As(AmountOfSubstanceUnit.Megamole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Micromoles => As(AmountOfSubstanceUnit.Micromole); + public QuantityValue Micromoles => this.As(AmountOfSubstanceUnit.Micromole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicropoundMoles => As(AmountOfSubstanceUnit.MicropoundMole); + public QuantityValue MicropoundMoles => this.As(AmountOfSubstanceUnit.MicropoundMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millimoles => As(AmountOfSubstanceUnit.Millimole); + public QuantityValue Millimoles => this.As(AmountOfSubstanceUnit.Millimole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillipoundMoles => As(AmountOfSubstanceUnit.MillipoundMole); + public QuantityValue MillipoundMoles => this.As(AmountOfSubstanceUnit.MillipoundMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Moles => As(AmountOfSubstanceUnit.Mole); + public QuantityValue Moles => this.As(AmountOfSubstanceUnit.Mole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanomoles => As(AmountOfSubstanceUnit.Nanomole); + public QuantityValue Nanomoles => this.As(AmountOfSubstanceUnit.Nanomole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanopoundMoles => As(AmountOfSubstanceUnit.NanopoundMole); + public QuantityValue NanopoundMoles => this.As(AmountOfSubstanceUnit.NanopoundMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Picomoles => As(AmountOfSubstanceUnit.Picomole); + public QuantityValue Picomoles => this.As(AmountOfSubstanceUnit.Picomole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundMoles => As(AmountOfSubstanceUnit.PoundMole); + public QuantityValue PoundMoles => this.As(AmountOfSubstanceUnit.PoundMole); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: AmountOfSubstanceUnit -> BaseUnit - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Centimole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.CentipoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Decimole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.DecipoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Femtomole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Kilomole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.KilopoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Megamole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Micromole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.MicropoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Millimole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.MillipoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Nanomole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.NanopoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Picomole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.PoundMole, AmountOfSubstanceUnit.Mole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Mole)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Mole, quantity => quantity); - - // Register in unit converter: BaseUnit -> AmountOfSubstanceUnit - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Centimole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Centimole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.CentipoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.CentipoundMole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Decimole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Decimole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.DecipoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.DecipoundMole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Femtomole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Femtomole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Kilomole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Kilomole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.KilopoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.KilopoundMole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Megamole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Megamole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Micromole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Micromole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.MicropoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.MicropoundMole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Millimole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Millimole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.MillipoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.MillipoundMole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Nanomole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Nanomole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.NanopoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.NanopoundMole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Picomole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.Picomole)); - unitConverter.SetConversionFunction(AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.PoundMole, quantity => quantity.ToUnit(AmountOfSubstanceUnit.PoundMole)); - } - /// /// Get unit abbreviation string. /// @@ -414,7 +396,7 @@ public static string GetAbbreviation(AmountOfSubstanceUnit unit, IFormatProvider /// /// Creates a from . /// - public static AmountOfSubstance FromCentimoles(double value) + public static AmountOfSubstance FromCentimoles(QuantityValue value) { return new AmountOfSubstance(value, AmountOfSubstanceUnit.Centimole); } @@ -422,7 +404,7 @@ public static AmountOfSubstance FromCentimoles(double value) /// /// Creates a from . /// - public static AmountOfSubstance FromCentipoundMoles(double value) + public static AmountOfSubstance FromCentipoundMoles(QuantityValue value) { return new AmountOfSubstance(value, AmountOfSubstanceUnit.CentipoundMole); } @@ -430,7 +412,7 @@ public static AmountOfSubstance FromCentipoundMoles(double value) /// /// Creates a from . /// - public static AmountOfSubstance FromDecimoles(double value) + public static AmountOfSubstance FromDecimoles(QuantityValue value) { return new AmountOfSubstance(value, AmountOfSubstanceUnit.Decimole); } @@ -438,7 +420,7 @@ public static AmountOfSubstance FromDecimoles(double value) /// /// Creates a from . /// - public static AmountOfSubstance FromDecipoundMoles(double value) + public static AmountOfSubstance FromDecipoundMoles(QuantityValue value) { return new AmountOfSubstance(value, AmountOfSubstanceUnit.DecipoundMole); } @@ -446,7 +428,7 @@ public static AmountOfSubstance FromDecipoundMoles(double value) /// /// Creates a from . /// - public static AmountOfSubstance FromFemtomoles(double value) + public static AmountOfSubstance FromFemtomoles(QuantityValue value) { return new AmountOfSubstance(value, AmountOfSubstanceUnit.Femtomole); } @@ -454,7 +436,7 @@ public static AmountOfSubstance FromFemtomoles(double value) /// /// Creates a from . /// - public static AmountOfSubstance FromKilomoles(double value) + public static AmountOfSubstance FromKilomoles(QuantityValue value) { return new AmountOfSubstance(value, AmountOfSubstanceUnit.Kilomole); } @@ -462,7 +444,7 @@ public static AmountOfSubstance FromKilomoles(double value) /// /// Creates a from . /// - public static AmountOfSubstance FromKilopoundMoles(double value) + public static AmountOfSubstance FromKilopoundMoles(QuantityValue value) { return new AmountOfSubstance(value, AmountOfSubstanceUnit.KilopoundMole); } @@ -470,7 +452,7 @@ public static AmountOfSubstance FromKilopoundMoles(double value) /// /// Creates a from . /// - public static AmountOfSubstance FromMegamoles(double value) + public static AmountOfSubstance FromMegamoles(QuantityValue value) { return new AmountOfSubstance(value, AmountOfSubstanceUnit.Megamole); } @@ -478,7 +460,7 @@ public static AmountOfSubstance FromMegamoles(double value) /// /// Creates a from . /// - public static AmountOfSubstance FromMicromoles(double value) + public static AmountOfSubstance FromMicromoles(QuantityValue value) { return new AmountOfSubstance(value, AmountOfSubstanceUnit.Micromole); } @@ -486,7 +468,7 @@ public static AmountOfSubstance FromMicromoles(double value) /// /// Creates a from . /// - public static AmountOfSubstance FromMicropoundMoles(double value) + public static AmountOfSubstance FromMicropoundMoles(QuantityValue value) { return new AmountOfSubstance(value, AmountOfSubstanceUnit.MicropoundMole); } @@ -494,7 +476,7 @@ public static AmountOfSubstance FromMicropoundMoles(double value) /// /// Creates a from . /// - public static AmountOfSubstance FromMillimoles(double value) + public static AmountOfSubstance FromMillimoles(QuantityValue value) { return new AmountOfSubstance(value, AmountOfSubstanceUnit.Millimole); } @@ -502,7 +484,7 @@ public static AmountOfSubstance FromMillimoles(double value) /// /// Creates a from . /// - public static AmountOfSubstance FromMillipoundMoles(double value) + public static AmountOfSubstance FromMillipoundMoles(QuantityValue value) { return new AmountOfSubstance(value, AmountOfSubstanceUnit.MillipoundMole); } @@ -510,7 +492,7 @@ public static AmountOfSubstance FromMillipoundMoles(double value) /// /// Creates a from . /// - public static AmountOfSubstance FromMoles(double value) + public static AmountOfSubstance FromMoles(QuantityValue value) { return new AmountOfSubstance(value, AmountOfSubstanceUnit.Mole); } @@ -518,7 +500,7 @@ public static AmountOfSubstance FromMoles(double value) /// /// Creates a from . /// - public static AmountOfSubstance FromNanomoles(double value) + public static AmountOfSubstance FromNanomoles(QuantityValue value) { return new AmountOfSubstance(value, AmountOfSubstanceUnit.Nanomole); } @@ -526,7 +508,7 @@ public static AmountOfSubstance FromNanomoles(double value) /// /// Creates a from . /// - public static AmountOfSubstance FromNanopoundMoles(double value) + public static AmountOfSubstance FromNanopoundMoles(QuantityValue value) { return new AmountOfSubstance(value, AmountOfSubstanceUnit.NanopoundMole); } @@ -534,7 +516,7 @@ public static AmountOfSubstance FromNanopoundMoles(double value) /// /// Creates a from . /// - public static AmountOfSubstance FromPicomoles(double value) + public static AmountOfSubstance FromPicomoles(QuantityValue value) { return new AmountOfSubstance(value, AmountOfSubstanceUnit.Picomole); } @@ -542,7 +524,7 @@ public static AmountOfSubstance FromPicomoles(double value) /// /// Creates a from . /// - public static AmountOfSubstance FromPoundMoles(double value) + public static AmountOfSubstance FromPoundMoles(QuantityValue value) { return new AmountOfSubstance(value, AmountOfSubstanceUnit.PoundMole); } @@ -553,7 +535,7 @@ public static AmountOfSubstance FromPoundMoles(double value) /// Value to convert from. /// Unit to convert from. /// AmountOfSubstance unit value. - public static AmountOfSubstance From(double value, AmountOfSubstanceUnit fromUnit) + public static AmountOfSubstance From(QuantityValue value, AmountOfSubstanceUnit fromUnit) { return new AmountOfSubstance(value, fromUnit); } @@ -614,10 +596,7 @@ public static AmountOfSubstance Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static AmountOfSubstance Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -645,11 +624,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out AmountOfSubstanc /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out AmountOfSubstance result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -670,7 +645,7 @@ public static AmountOfSubstanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -681,7 +656,7 @@ public static AmountOfSubstanceUnit ParseUnit(string str, IFormatProvider? provi return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out AmountOfSubstanceUnit unit) { return TryParseUnit(str, null, out unit); @@ -696,7 +671,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out AmountOfSubs /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out AmountOfSubstanceUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -715,35 +690,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static AmountOfSubstance operator +(AmountOfSubstance left, AmountOfSubstance right) { - return new AmountOfSubstance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new AmountOfSubstance(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static AmountOfSubstance operator -(AmountOfSubstance left, AmountOfSubstance right) { - return new AmountOfSubstance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new AmountOfSubstance(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -795,97 +770,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(AmountOfSubstance left, AmountOfSubstance right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(AmountOfSubstance left, AmountOfSubstance right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(AmountOfSubstance left, AmountOfSubstance right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(AmountOfSubstance left, AmountOfSubstance right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(AmountOfSubstance other, AmountOfSubstance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(AmountOfSubstance left, AmountOfSubstance right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(AmountOfSubstance other, AmountOfSubstance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(AmountOfSubstance left, AmountOfSubstance right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(AmountOfSubstance other, AmountOfSubstance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is AmountOfSubstance otherQuantity)) + if (obj is not AmountOfSubstance otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(AmountOfSubstance other, AmountOfSubstance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(AmountOfSubstance other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current AmountOfSubstance. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(AmountOfSubstance), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is AmountOfSubstance otherQuantity)) throw new ArgumentException("Expected type AmountOfSubstance.", nameof(obj)); + if (obj is not AmountOfSubstance otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -897,178 +857,24 @@ public int CompareTo(object? obj) /// public int CompareTo(AmountOfSubstance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AmountOfSubstanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this AmountOfSubstance to another AmountOfSubstance with the unit representation . - /// - /// The unit to convert to. - /// A AmountOfSubstance with the specified unit. - public AmountOfSubstance ToUnit(AmountOfSubstanceUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A AmountOfSubstance with the specified unit. - public AmountOfSubstance ToUnit(AmountOfSubstanceUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(AmountOfSubstance), Unit, typeof(AmountOfSubstance), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (AmountOfSubstance)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(AmountOfSubstanceUnit unit, [NotNullWhen(true)] out AmountOfSubstance? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - AmountOfSubstance? convertedOrNull = (Unit, unit) switch - { - // AmountOfSubstanceUnit -> BaseUnit - (AmountOfSubstanceUnit.Centimole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value) * 1e-2d, AmountOfSubstanceUnit.Mole), - (AmountOfSubstanceUnit.CentipoundMole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value * 453.59237) * 1e-2d, AmountOfSubstanceUnit.Mole), - (AmountOfSubstanceUnit.Decimole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value) * 1e-1d, AmountOfSubstanceUnit.Mole), - (AmountOfSubstanceUnit.DecipoundMole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value * 453.59237) * 1e-1d, AmountOfSubstanceUnit.Mole), - (AmountOfSubstanceUnit.Femtomole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value) * 1e-15d, AmountOfSubstanceUnit.Mole), - (AmountOfSubstanceUnit.Kilomole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value) * 1e3d, AmountOfSubstanceUnit.Mole), - (AmountOfSubstanceUnit.KilopoundMole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value * 453.59237) * 1e3d, AmountOfSubstanceUnit.Mole), - (AmountOfSubstanceUnit.Megamole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value) * 1e6d, AmountOfSubstanceUnit.Mole), - (AmountOfSubstanceUnit.Micromole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value) * 1e-6d, AmountOfSubstanceUnit.Mole), - (AmountOfSubstanceUnit.MicropoundMole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value * 453.59237) * 1e-6d, AmountOfSubstanceUnit.Mole), - (AmountOfSubstanceUnit.Millimole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value) * 1e-3d, AmountOfSubstanceUnit.Mole), - (AmountOfSubstanceUnit.MillipoundMole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value * 453.59237) * 1e-3d, AmountOfSubstanceUnit.Mole), - (AmountOfSubstanceUnit.Nanomole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value) * 1e-9d, AmountOfSubstanceUnit.Mole), - (AmountOfSubstanceUnit.NanopoundMole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value * 453.59237) * 1e-9d, AmountOfSubstanceUnit.Mole), - (AmountOfSubstanceUnit.Picomole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance((_value) * 1e-12d, AmountOfSubstanceUnit.Mole), - (AmountOfSubstanceUnit.PoundMole, AmountOfSubstanceUnit.Mole) => new AmountOfSubstance(_value * 453.59237, AmountOfSubstanceUnit.Mole), - - // BaseUnit -> AmountOfSubstanceUnit - (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Centimole) => new AmountOfSubstance((_value) / 1e-2d, AmountOfSubstanceUnit.Centimole), - (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.CentipoundMole) => new AmountOfSubstance((_value / 453.59237) / 1e-2d, AmountOfSubstanceUnit.CentipoundMole), - (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Decimole) => new AmountOfSubstance((_value) / 1e-1d, AmountOfSubstanceUnit.Decimole), - (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.DecipoundMole) => new AmountOfSubstance((_value / 453.59237) / 1e-1d, AmountOfSubstanceUnit.DecipoundMole), - (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Femtomole) => new AmountOfSubstance((_value) / 1e-15d, AmountOfSubstanceUnit.Femtomole), - (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Kilomole) => new AmountOfSubstance((_value) / 1e3d, AmountOfSubstanceUnit.Kilomole), - (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.KilopoundMole) => new AmountOfSubstance((_value / 453.59237) / 1e3d, AmountOfSubstanceUnit.KilopoundMole), - (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Megamole) => new AmountOfSubstance((_value) / 1e6d, AmountOfSubstanceUnit.Megamole), - (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Micromole) => new AmountOfSubstance((_value) / 1e-6d, AmountOfSubstanceUnit.Micromole), - (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.MicropoundMole) => new AmountOfSubstance((_value / 453.59237) / 1e-6d, AmountOfSubstanceUnit.MicropoundMole), - (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Millimole) => new AmountOfSubstance((_value) / 1e-3d, AmountOfSubstanceUnit.Millimole), - (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.MillipoundMole) => new AmountOfSubstance((_value / 453.59237) / 1e-3d, AmountOfSubstanceUnit.MillipoundMole), - (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Nanomole) => new AmountOfSubstance((_value) / 1e-9d, AmountOfSubstanceUnit.Nanomole), - (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.NanopoundMole) => new AmountOfSubstance((_value / 453.59237) / 1e-9d, AmountOfSubstanceUnit.NanopoundMole), - (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.Picomole) => new AmountOfSubstance((_value) / 1e-12d, AmountOfSubstanceUnit.Picomole), - (AmountOfSubstanceUnit.Mole, AmountOfSubstanceUnit.PoundMole) => new AmountOfSubstance(_value / 453.59237, AmountOfSubstanceUnit.PoundMole), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public AmountOfSubstance ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not AmountOfSubstanceUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AmountOfSubstanceUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(AmountOfSubstanceUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(AmountOfSubstanceUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1083,7 +889,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs index 41bf9b836d..30331f49c9 100644 --- a/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AmplitudeRatio.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// The strength of a signal expressed in decibels (dB) relative to one volt RMS. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct AmplitudeRatio : ILogarithmicQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly AmplitudeRatioUnit? _unit; /// @@ -116,18 +115,25 @@ public static AmplitudeRatioInfo CreateDefault(FuncAn of representing the default unit mappings for AmplitudeRatio. public static IEnumerable> GetDefaultMappings() { - yield return new (AmplitudeRatioUnit.DecibelMicrovolt, "DecibelMicrovolt", "DecibelMicrovolts", BaseUnits.Undefined); - yield return new (AmplitudeRatioUnit.DecibelMillivolt, "DecibelMillivolt", "DecibelMillivolts", BaseUnits.Undefined); - yield return new (AmplitudeRatioUnit.DecibelUnloaded, "DecibelUnloaded", "DecibelsUnloaded", BaseUnits.Undefined); + yield return new (AmplitudeRatioUnit.DecibelMicrovolt, "DecibelMicrovolt", "DecibelMicrovolts", BaseUnits.Undefined, + new ConversionExpression(1, 120), + new ConversionExpression(1, -120) + ); + yield return new (AmplitudeRatioUnit.DecibelMillivolt, "DecibelMillivolt", "DecibelMillivolts", BaseUnits.Undefined, + new ConversionExpression(1, 60), + new ConversionExpression(1, -60) + ); + yield return new (AmplitudeRatioUnit.DecibelUnloaded, "DecibelUnloaded", "DecibelsUnloaded", BaseUnits.Undefined, + new ConversionExpression(1, new QuantityValue(2218487499, 1000000000)), + new ConversionExpression(1, new QuantityValue(-2218487499, 1000000000)) + ); yield return new (AmplitudeRatioUnit.DecibelVolt, "DecibelVolt", "DecibelVolts", BaseUnits.Undefined); } } static AmplitudeRatio() { - Info = AmplitudeRatioInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(AmplitudeRatioInfo.CreateDefault); } /// @@ -135,7 +141,7 @@ static AmplitudeRatio() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public AmplitudeRatio(double value, AmplitudeRatioUnit unit) + public AmplitudeRatio(QuantityValue value, AmplitudeRatioUnit unit) { _value = value; _unit = unit; @@ -146,7 +152,8 @@ public AmplitudeRatio(double value, AmplitudeRatioUnit unit) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -172,16 +179,14 @@ public AmplitudeRatio(double value, AmplitudeRatioUnit unit) public static AmplitudeRatio Zero => Info.Zero; /// - public static double LogarithmicScalingFactor {get;} = 20; + public static QuantityValue LogarithmicScalingFactor {get;} = 20; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public AmplitudeRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -214,7 +219,7 @@ public AmplitudeRatio(double value, AmplitudeRatioUnit unit) #endif #if NETSTANDARD2_0 - double ILogarithmicQuantity.LogarithmicScalingFactor => LogarithmicScalingFactor; + QuantityValue ILogarithmicQuantity.LogarithmicScalingFactor => LogarithmicScalingFactor; #endif #endregion @@ -224,49 +229,29 @@ public AmplitudeRatio(double value, AmplitudeRatioUnit unit) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecibelMicrovolts => As(AmplitudeRatioUnit.DecibelMicrovolt); + public QuantityValue DecibelMicrovolts => this.As(AmplitudeRatioUnit.DecibelMicrovolt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecibelMillivolts => As(AmplitudeRatioUnit.DecibelMillivolt); + public QuantityValue DecibelMillivolts => this.As(AmplitudeRatioUnit.DecibelMillivolt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecibelsUnloaded => As(AmplitudeRatioUnit.DecibelUnloaded); + public QuantityValue DecibelsUnloaded => this.As(AmplitudeRatioUnit.DecibelUnloaded); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecibelVolts => As(AmplitudeRatioUnit.DecibelVolt); + public QuantityValue DecibelVolts => this.As(AmplitudeRatioUnit.DecibelVolt); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: AmplitudeRatioUnit -> BaseUnit - unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelMicrovolt, AmplitudeRatioUnit.DecibelVolt, quantity => quantity.ToUnit(AmplitudeRatioUnit.DecibelVolt)); - unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelMillivolt, AmplitudeRatioUnit.DecibelVolt, quantity => quantity.ToUnit(AmplitudeRatioUnit.DecibelVolt)); - unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelUnloaded, AmplitudeRatioUnit.DecibelVolt, quantity => quantity.ToUnit(AmplitudeRatioUnit.DecibelVolt)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelVolt, quantity => quantity); - - // Register in unit converter: BaseUnit -> AmplitudeRatioUnit - unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelMicrovolt, quantity => quantity.ToUnit(AmplitudeRatioUnit.DecibelMicrovolt)); - unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelMillivolt, quantity => quantity.ToUnit(AmplitudeRatioUnit.DecibelMillivolt)); - unitConverter.SetConversionFunction(AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelUnloaded, quantity => quantity.ToUnit(AmplitudeRatioUnit.DecibelUnloaded)); - } - /// /// Get unit abbreviation string. /// @@ -295,7 +280,7 @@ public static string GetAbbreviation(AmplitudeRatioUnit unit, IFormatProvider? p /// /// Creates a from . /// - public static AmplitudeRatio FromDecibelMicrovolts(double value) + public static AmplitudeRatio FromDecibelMicrovolts(QuantityValue value) { return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMicrovolt); } @@ -303,7 +288,7 @@ public static AmplitudeRatio FromDecibelMicrovolts(double value) /// /// Creates a from . /// - public static AmplitudeRatio FromDecibelMillivolts(double value) + public static AmplitudeRatio FromDecibelMillivolts(QuantityValue value) { return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelMillivolt); } @@ -311,7 +296,7 @@ public static AmplitudeRatio FromDecibelMillivolts(double value) /// /// Creates a from . /// - public static AmplitudeRatio FromDecibelsUnloaded(double value) + public static AmplitudeRatio FromDecibelsUnloaded(QuantityValue value) { return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelUnloaded); } @@ -319,7 +304,7 @@ public static AmplitudeRatio FromDecibelsUnloaded(double value) /// /// Creates a from . /// - public static AmplitudeRatio FromDecibelVolts(double value) + public static AmplitudeRatio FromDecibelVolts(QuantityValue value) { return new AmplitudeRatio(value, AmplitudeRatioUnit.DecibelVolt); } @@ -330,7 +315,7 @@ public static AmplitudeRatio FromDecibelVolts(double value) /// Value to convert from. /// Unit to convert from. /// AmplitudeRatio unit value. - public static AmplitudeRatio From(double value, AmplitudeRatioUnit fromUnit) + public static AmplitudeRatio From(QuantityValue value, AmplitudeRatioUnit fromUnit) { return new AmplitudeRatio(value, fromUnit); } @@ -391,10 +376,7 @@ public static AmplitudeRatio Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static AmplitudeRatio Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -422,11 +404,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out AmplitudeRatio r /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out AmplitudeRatio result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -447,7 +425,7 @@ public static AmplitudeRatioUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -458,7 +436,7 @@ public static AmplitudeRatioUnit ParseUnit(string str, IFormatProvider? provider return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out AmplitudeRatioUnit unit) { return TryParseUnit(str, null, out unit); @@ -473,7 +451,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out AmplitudeRat /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out AmplitudeRatioUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -484,53 +462,61 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? #region Logarithmic Arithmetic Operators /// Negate the value. - public static AmplitudeRatio operator -(AmplitudeRatio right) + public static AmplitudeRatio operator -(AmplitudeRatio quantity) { - return new AmplitudeRatio(-right.Value, right.Unit); + return new AmplitudeRatio(-quantity.Value, quantity.Unit); } /// Get from logarithmic addition of two . + /// This operation involves a conversion of the values to linear space, which is not guaranteed to produce an exact value. + /// The final result is rounded to 15 significant digits. + /// public static AmplitudeRatio operator +(AmplitudeRatio left, AmplitudeRatio right) { // 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.ToUnit(left.Unit).Value / 20)), left.Unit); + var leftUnit = left.Unit; + return new AmplitudeRatio(QuantityValueExtensions.AddWithLogScaling(left.Value, right.As(leftUnit), LogarithmicScalingFactor), leftUnit); } /// Get from logarithmic subtraction of two . + /// This operation involves a conversion of the values to linear space, which is not guaranteed to produce an exact value. + /// The final result is rounded to 15 significant digits. + /// public static AmplitudeRatio operator -(AmplitudeRatio left, AmplitudeRatio right) { // 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.ToUnit(left.Unit).Value / 20)), left.Unit); + var leftUnit = left.Unit; + return new AmplitudeRatio(QuantityValueExtensions.SubtractWithLogScaling(left.Value, right.As(leftUnit), LogarithmicScalingFactor), leftUnit); } /// 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); } /// Get from logarithmic multiplication of value and . - public static AmplitudeRatio operator *(AmplitudeRatio left, double right) + public static AmplitudeRatio operator *(AmplitudeRatio left, QuantityValue right) { // Logarithmic multiplication = addition return new AmplitudeRatio(left.Value + right, left.Unit); } /// Get from logarithmic division of by value. - public static AmplitudeRatio operator /(AmplitudeRatio left, double right) + public static AmplitudeRatio operator /(AmplitudeRatio left, QuantityValue right) { // Logarithmic division = subtraction return new AmplitudeRatio(left.Value - right, left.Unit); } /// Get ratio value from logarithmic division of by . - public static double operator /(AmplitudeRatio left, AmplitudeRatio right) + public static QuantityValue operator /(AmplitudeRatio left, AmplitudeRatio right) { // Logarithmic division = subtraction - return Convert.ToDouble(left.Value - right.ToUnit(left.Unit).Value); + return left.Value - right.As(left.Unit); } #endregion @@ -540,97 +526,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(AmplitudeRatio left, AmplitudeRatio right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(AmplitudeRatio left, AmplitudeRatio right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(AmplitudeRatio left, AmplitudeRatio right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(AmplitudeRatio left, AmplitudeRatio right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(AmplitudeRatio other, AmplitudeRatio tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(AmplitudeRatio left, AmplitudeRatio right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(AmplitudeRatio other, AmplitudeRatio tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(AmplitudeRatio left, AmplitudeRatio right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(AmplitudeRatio other, AmplitudeRatio tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is AmplitudeRatio otherQuantity)) + if (obj is not AmplitudeRatio otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(AmplitudeRatio other, AmplitudeRatio tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(AmplitudeRatio other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current AmplitudeRatio. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(AmplitudeRatio), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is AmplitudeRatio otherQuantity)) throw new ArgumentException("Expected type AmplitudeRatio.", nameof(obj)); + if (obj is not AmplitudeRatio otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -642,152 +613,24 @@ public int CompareTo(object? obj) /// public int CompareTo(AmplitudeRatio other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AmplitudeRatioUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this AmplitudeRatio to another AmplitudeRatio with the unit representation . - /// - /// The unit to convert to. - /// A AmplitudeRatio with the specified unit. - public AmplitudeRatio ToUnit(AmplitudeRatioUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A AmplitudeRatio with the specified unit. - public AmplitudeRatio ToUnit(AmplitudeRatioUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(AmplitudeRatio), Unit, typeof(AmplitudeRatio), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (AmplitudeRatio)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(AmplitudeRatioUnit unit, [NotNullWhen(true)] out AmplitudeRatio? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - AmplitudeRatio? convertedOrNull = (Unit, unit) switch - { - // AmplitudeRatioUnit -> BaseUnit - (AmplitudeRatioUnit.DecibelMicrovolt, AmplitudeRatioUnit.DecibelVolt) => new AmplitudeRatio(_value - 120, AmplitudeRatioUnit.DecibelVolt), - (AmplitudeRatioUnit.DecibelMillivolt, AmplitudeRatioUnit.DecibelVolt) => new AmplitudeRatio(_value - 60, AmplitudeRatioUnit.DecibelVolt), - (AmplitudeRatioUnit.DecibelUnloaded, AmplitudeRatioUnit.DecibelVolt) => new AmplitudeRatio(_value - 2.218487499, AmplitudeRatioUnit.DecibelVolt), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> AmplitudeRatioUnit - (AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelMicrovolt) => new AmplitudeRatio(_value + 120, AmplitudeRatioUnit.DecibelMicrovolt), - (AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelMillivolt) => new AmplitudeRatio(_value + 60, AmplitudeRatioUnit.DecibelMillivolt), - (AmplitudeRatioUnit.DecibelVolt, AmplitudeRatioUnit.DecibelUnloaded) => new AmplitudeRatio(_value + 2.218487499, AmplitudeRatioUnit.DecibelUnloaded), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public AmplitudeRatio ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not AmplitudeRatioUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AmplitudeRatioUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is AmplitudeRatioUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AmplitudeRatioUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(AmplitudeRatioUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(AmplitudeRatioUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -802,7 +645,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Angle.g.cs b/UnitsNet/GeneratedCode/Quantities/Angle.g.cs index 846af3096f..8b4c00bc90 100644 --- a/UnitsNet/GeneratedCode/Quantities/Angle.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Angle.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Angle : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -55,13 +54,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly AngleUnit? _unit; /// @@ -121,29 +120,55 @@ public static AngleInfo CreateDefault(Func /// An of representing the default unit mappings for Angle. public static IEnumerable> GetDefaultMappings() { - yield return new (AngleUnit.Arcminute, "Arcminute", "Arcminutes", BaseUnits.Undefined); - yield return new (AngleUnit.Arcsecond, "Arcsecond", "Arcseconds", BaseUnits.Undefined); - yield return new (AngleUnit.Centiradian, "Centiradian", "Centiradians", BaseUnits.Undefined); - yield return new (AngleUnit.Deciradian, "Deciradian", "Deciradians", BaseUnits.Undefined); - yield return new (AngleUnit.Degree, "Degree", "Degrees", BaseUnits.Undefined); - yield return new (AngleUnit.Gradian, "Gradian", "Gradians", BaseUnits.Undefined); - yield return new (AngleUnit.Microdegree, "Microdegree", "Microdegrees", BaseUnits.Undefined); - yield return new (AngleUnit.Microradian, "Microradian", "Microradians", BaseUnits.Undefined); - yield return new (AngleUnit.Millidegree, "Millidegree", "Millidegrees", BaseUnits.Undefined); - yield return new (AngleUnit.Milliradian, "Milliradian", "Milliradians", BaseUnits.Undefined); - yield return new (AngleUnit.Nanodegree, "Nanodegree", "Nanodegrees", BaseUnits.Undefined); - yield return new (AngleUnit.Nanoradian, "Nanoradian", "Nanoradians", BaseUnits.Undefined); - yield return new (AngleUnit.NatoMil, "NatoMil", "NatoMils", BaseUnits.Undefined); + yield return new (AngleUnit.Arcminute, "Arcminute", "Arcminutes", BaseUnits.Undefined, + new QuantityValue(new BigInteger(108) * QuantityValue.PowerOfTen(17), 3141592653589793) + ); + yield return new (AngleUnit.Arcsecond, "Arcsecond", "Arcseconds", BaseUnits.Undefined, + new QuantityValue(new BigInteger(648) * QuantityValue.PowerOfTen(18), 3141592653589793) + ); + yield return new (AngleUnit.Centiradian, "Centiradian", "Centiradians", BaseUnits.Undefined, + 100 + ); + yield return new (AngleUnit.Deciradian, "Deciradian", "Deciradians", BaseUnits.Undefined, + 10 + ); + yield return new (AngleUnit.Degree, "Degree", "Degrees", BaseUnits.Undefined, + new QuantityValue(180000000000000000, 3141592653589793) + ); + yield return new (AngleUnit.Gradian, "Gradian", "Gradians", BaseUnits.Undefined, + new QuantityValue(200000000000000000, 3141592653589793) + ); + yield return new (AngleUnit.Microdegree, "Microdegree", "Microdegrees", BaseUnits.Undefined, + new QuantityValue(new BigInteger(18) * QuantityValue.PowerOfTen(22), 3141592653589793) + ); + yield return new (AngleUnit.Microradian, "Microradian", "Microradians", BaseUnits.Undefined, + 1000000 + ); + yield return new (AngleUnit.Millidegree, "Millidegree", "Millidegrees", BaseUnits.Undefined, + new QuantityValue(new BigInteger(18) * QuantityValue.PowerOfTen(19), 3141592653589793) + ); + yield return new (AngleUnit.Milliradian, "Milliradian", "Milliradians", BaseUnits.Undefined, + 1000 + ); + yield return new (AngleUnit.Nanodegree, "Nanodegree", "Nanodegrees", BaseUnits.Undefined, + new QuantityValue(new BigInteger(18) * QuantityValue.PowerOfTen(25), 3141592653589793) + ); + yield return new (AngleUnit.Nanoradian, "Nanoradian", "Nanoradians", BaseUnits.Undefined, + 1000000000 + ); + yield return new (AngleUnit.NatoMil, "NatoMil", "NatoMils", BaseUnits.Undefined, + new QuantityValue(3200000000000000000, 3141592653589793) + ); yield return new (AngleUnit.Radian, "Radian", "Radians", BaseUnits.Undefined); - yield return new (AngleUnit.Revolution, "Revolution", "Revolutions", BaseUnits.Undefined); + yield return new (AngleUnit.Revolution, "Revolution", "Revolutions", BaseUnits.Undefined, + new QuantityValue(500000000000000, 3141592653589793) + ); } } static Angle() { - Info = AngleInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(AngleInfo.CreateDefault); } /// @@ -151,7 +176,7 @@ static Angle() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Angle(double value, AngleUnit unit) + public Angle(QuantityValue value, AngleUnit unit) { _value = value; _unit = unit; @@ -162,7 +187,8 @@ public Angle(double value, AngleUnit unit) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -191,10 +217,8 @@ public Angle(double value, AngleUnit unit) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public AngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -233,126 +257,84 @@ public Angle(double value, AngleUnit unit) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Arcminutes => As(AngleUnit.Arcminute); + public QuantityValue Arcminutes => this.As(AngleUnit.Arcminute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Arcseconds => As(AngleUnit.Arcsecond); + public QuantityValue Arcseconds => this.As(AngleUnit.Arcsecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Centiradians => As(AngleUnit.Centiradian); + public QuantityValue Centiradians => this.As(AngleUnit.Centiradian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Deciradians => As(AngleUnit.Deciradian); + public QuantityValue Deciradians => this.As(AngleUnit.Deciradian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Degrees => As(AngleUnit.Degree); + public QuantityValue Degrees => this.As(AngleUnit.Degree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gradians => As(AngleUnit.Gradian); + public QuantityValue Gradians => this.As(AngleUnit.Gradian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microdegrees => As(AngleUnit.Microdegree); + public QuantityValue Microdegrees => this.As(AngleUnit.Microdegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microradians => As(AngleUnit.Microradian); + public QuantityValue Microradians => this.As(AngleUnit.Microradian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millidegrees => As(AngleUnit.Millidegree); + public QuantityValue Millidegrees => this.As(AngleUnit.Millidegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Milliradians => As(AngleUnit.Milliradian); + public QuantityValue Milliradians => this.As(AngleUnit.Milliradian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanodegrees => As(AngleUnit.Nanodegree); + public QuantityValue Nanodegrees => this.As(AngleUnit.Nanodegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanoradians => As(AngleUnit.Nanoradian); + public QuantityValue Nanoradians => this.As(AngleUnit.Nanoradian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NatoMils => As(AngleUnit.NatoMil); + public QuantityValue NatoMils => this.As(AngleUnit.NatoMil); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Radians => As(AngleUnit.Radian); + public QuantityValue Radians => this.As(AngleUnit.Radian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Revolutions => As(AngleUnit.Revolution); + public QuantityValue Revolutions => this.As(AngleUnit.Revolution); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: AngleUnit -> BaseUnit - unitConverter.SetConversionFunction(AngleUnit.Arcminute, AngleUnit.Radian, quantity => quantity.ToUnit(AngleUnit.Radian)); - unitConverter.SetConversionFunction(AngleUnit.Arcsecond, AngleUnit.Radian, quantity => quantity.ToUnit(AngleUnit.Radian)); - unitConverter.SetConversionFunction(AngleUnit.Centiradian, AngleUnit.Radian, quantity => quantity.ToUnit(AngleUnit.Radian)); - unitConverter.SetConversionFunction(AngleUnit.Deciradian, AngleUnit.Radian, quantity => quantity.ToUnit(AngleUnit.Radian)); - unitConverter.SetConversionFunction(AngleUnit.Degree, AngleUnit.Radian, quantity => quantity.ToUnit(AngleUnit.Radian)); - unitConverter.SetConversionFunction(AngleUnit.Gradian, AngleUnit.Radian, quantity => quantity.ToUnit(AngleUnit.Radian)); - unitConverter.SetConversionFunction(AngleUnit.Microdegree, AngleUnit.Radian, quantity => quantity.ToUnit(AngleUnit.Radian)); - unitConverter.SetConversionFunction(AngleUnit.Microradian, AngleUnit.Radian, quantity => quantity.ToUnit(AngleUnit.Radian)); - unitConverter.SetConversionFunction(AngleUnit.Millidegree, AngleUnit.Radian, quantity => quantity.ToUnit(AngleUnit.Radian)); - unitConverter.SetConversionFunction(AngleUnit.Milliradian, AngleUnit.Radian, quantity => quantity.ToUnit(AngleUnit.Radian)); - unitConverter.SetConversionFunction(AngleUnit.Nanodegree, AngleUnit.Radian, quantity => quantity.ToUnit(AngleUnit.Radian)); - unitConverter.SetConversionFunction(AngleUnit.Nanoradian, AngleUnit.Radian, quantity => quantity.ToUnit(AngleUnit.Radian)); - unitConverter.SetConversionFunction(AngleUnit.NatoMil, AngleUnit.Radian, quantity => quantity.ToUnit(AngleUnit.Radian)); - unitConverter.SetConversionFunction(AngleUnit.Revolution, AngleUnit.Radian, quantity => quantity.ToUnit(AngleUnit.Radian)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(AngleUnit.Radian, AngleUnit.Radian, quantity => quantity); - - // Register in unit converter: BaseUnit -> AngleUnit - unitConverter.SetConversionFunction(AngleUnit.Radian, AngleUnit.Arcminute, quantity => quantity.ToUnit(AngleUnit.Arcminute)); - unitConverter.SetConversionFunction(AngleUnit.Radian, AngleUnit.Arcsecond, quantity => quantity.ToUnit(AngleUnit.Arcsecond)); - unitConverter.SetConversionFunction(AngleUnit.Radian, AngleUnit.Centiradian, quantity => quantity.ToUnit(AngleUnit.Centiradian)); - unitConverter.SetConversionFunction(AngleUnit.Radian, AngleUnit.Deciradian, quantity => quantity.ToUnit(AngleUnit.Deciradian)); - unitConverter.SetConversionFunction(AngleUnit.Radian, AngleUnit.Degree, quantity => quantity.ToUnit(AngleUnit.Degree)); - unitConverter.SetConversionFunction(AngleUnit.Radian, AngleUnit.Gradian, quantity => quantity.ToUnit(AngleUnit.Gradian)); - unitConverter.SetConversionFunction(AngleUnit.Radian, AngleUnit.Microdegree, quantity => quantity.ToUnit(AngleUnit.Microdegree)); - unitConverter.SetConversionFunction(AngleUnit.Radian, AngleUnit.Microradian, quantity => quantity.ToUnit(AngleUnit.Microradian)); - unitConverter.SetConversionFunction(AngleUnit.Radian, AngleUnit.Millidegree, quantity => quantity.ToUnit(AngleUnit.Millidegree)); - unitConverter.SetConversionFunction(AngleUnit.Radian, AngleUnit.Milliradian, quantity => quantity.ToUnit(AngleUnit.Milliradian)); - unitConverter.SetConversionFunction(AngleUnit.Radian, AngleUnit.Nanodegree, quantity => quantity.ToUnit(AngleUnit.Nanodegree)); - unitConverter.SetConversionFunction(AngleUnit.Radian, AngleUnit.Nanoradian, quantity => quantity.ToUnit(AngleUnit.Nanoradian)); - unitConverter.SetConversionFunction(AngleUnit.Radian, AngleUnit.NatoMil, quantity => quantity.ToUnit(AngleUnit.NatoMil)); - unitConverter.SetConversionFunction(AngleUnit.Radian, AngleUnit.Revolution, quantity => quantity.ToUnit(AngleUnit.Revolution)); - } - /// /// Get unit abbreviation string. /// @@ -381,7 +363,7 @@ public static string GetAbbreviation(AngleUnit unit, IFormatProvider? provider) /// /// Creates a from . /// - public static Angle FromArcminutes(double value) + public static Angle FromArcminutes(QuantityValue value) { return new Angle(value, AngleUnit.Arcminute); } @@ -389,7 +371,7 @@ public static Angle FromArcminutes(double value) /// /// Creates a from . /// - public static Angle FromArcseconds(double value) + public static Angle FromArcseconds(QuantityValue value) { return new Angle(value, AngleUnit.Arcsecond); } @@ -397,7 +379,7 @@ public static Angle FromArcseconds(double value) /// /// Creates a from . /// - public static Angle FromCentiradians(double value) + public static Angle FromCentiradians(QuantityValue value) { return new Angle(value, AngleUnit.Centiradian); } @@ -405,7 +387,7 @@ public static Angle FromCentiradians(double value) /// /// Creates a from . /// - public static Angle FromDeciradians(double value) + public static Angle FromDeciradians(QuantityValue value) { return new Angle(value, AngleUnit.Deciradian); } @@ -413,7 +395,7 @@ public static Angle FromDeciradians(double value) /// /// Creates a from . /// - public static Angle FromDegrees(double value) + public static Angle FromDegrees(QuantityValue value) { return new Angle(value, AngleUnit.Degree); } @@ -421,7 +403,7 @@ public static Angle FromDegrees(double value) /// /// Creates a from . /// - public static Angle FromGradians(double value) + public static Angle FromGradians(QuantityValue value) { return new Angle(value, AngleUnit.Gradian); } @@ -429,7 +411,7 @@ public static Angle FromGradians(double value) /// /// Creates a from . /// - public static Angle FromMicrodegrees(double value) + public static Angle FromMicrodegrees(QuantityValue value) { return new Angle(value, AngleUnit.Microdegree); } @@ -437,7 +419,7 @@ public static Angle FromMicrodegrees(double value) /// /// Creates a from . /// - public static Angle FromMicroradians(double value) + public static Angle FromMicroradians(QuantityValue value) { return new Angle(value, AngleUnit.Microradian); } @@ -445,7 +427,7 @@ public static Angle FromMicroradians(double value) /// /// Creates a from . /// - public static Angle FromMillidegrees(double value) + public static Angle FromMillidegrees(QuantityValue value) { return new Angle(value, AngleUnit.Millidegree); } @@ -453,7 +435,7 @@ public static Angle FromMillidegrees(double value) /// /// Creates a from . /// - public static Angle FromMilliradians(double value) + public static Angle FromMilliradians(QuantityValue value) { return new Angle(value, AngleUnit.Milliradian); } @@ -461,7 +443,7 @@ public static Angle FromMilliradians(double value) /// /// Creates a from . /// - public static Angle FromNanodegrees(double value) + public static Angle FromNanodegrees(QuantityValue value) { return new Angle(value, AngleUnit.Nanodegree); } @@ -469,7 +451,7 @@ public static Angle FromNanodegrees(double value) /// /// Creates a from . /// - public static Angle FromNanoradians(double value) + public static Angle FromNanoradians(QuantityValue value) { return new Angle(value, AngleUnit.Nanoradian); } @@ -477,7 +459,7 @@ public static Angle FromNanoradians(double value) /// /// Creates a from . /// - public static Angle FromNatoMils(double value) + public static Angle FromNatoMils(QuantityValue value) { return new Angle(value, AngleUnit.NatoMil); } @@ -485,7 +467,7 @@ public static Angle FromNatoMils(double value) /// /// Creates a from . /// - public static Angle FromRadians(double value) + public static Angle FromRadians(QuantityValue value) { return new Angle(value, AngleUnit.Radian); } @@ -493,7 +475,7 @@ public static Angle FromRadians(double value) /// /// Creates a from . /// - public static Angle FromRevolutions(double value) + public static Angle FromRevolutions(QuantityValue value) { return new Angle(value, AngleUnit.Revolution); } @@ -504,7 +486,7 @@ public static Angle FromRevolutions(double value) /// Value to convert from. /// Unit to convert from. /// Angle unit value. - public static Angle From(double value, AngleUnit fromUnit) + public static Angle From(QuantityValue value, AngleUnit fromUnit) { return new Angle(value, fromUnit); } @@ -565,10 +547,7 @@ public static Angle Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Angle Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -596,11 +575,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Angle result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Angle result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -621,7 +596,7 @@ public static AngleUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -632,7 +607,7 @@ public static AngleUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out AngleUnit unit) { return TryParseUnit(str, null, out unit); @@ -647,7 +622,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out AngleUnit un /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out AngleUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -666,35 +641,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Angle operator +(Angle left, Angle right) { - return new Angle(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Angle(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Angle operator -(Angle left, Angle right) { - return new Angle(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Angle(left.Value - right.As(left.Unit), left.Unit); } /// 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.Radians / right.Radians; } @@ -728,97 +703,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Angle left, Angle right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Angle left, Angle right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Angle left, Angle right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Angle left, Angle right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Angle other, Angle tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Angle left, Angle right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Angle other, Angle tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Angle left, Angle right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Angle other, Angle tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Angle otherQuantity)) + if (obj is not Angle otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Angle other, Angle tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Angle other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Angle. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Angle), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Angle otherQuantity)) throw new ArgumentException("Expected type Angle.", nameof(obj)); + if (obj is not Angle otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -830,174 +790,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Angle other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AngleUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this Angle to another Angle with the unit representation . - /// - /// The unit to convert to. - /// A Angle with the specified unit. - public Angle ToUnit(AngleUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Angle with the specified unit. - public Angle ToUnit(AngleUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Angle), Unit, typeof(Angle), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Angle)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(AngleUnit unit, [NotNullWhen(true)] out Angle? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Angle? convertedOrNull = (Unit, unit) switch - { - // AngleUnit -> BaseUnit - (AngleUnit.Arcminute, AngleUnit.Radian) => new Angle(_value * Math.PI / (60 * 180), AngleUnit.Radian), - (AngleUnit.Arcsecond, AngleUnit.Radian) => new Angle(_value * Math.PI / (3600 * 180), AngleUnit.Radian), - (AngleUnit.Centiradian, AngleUnit.Radian) => new Angle((_value) * 1e-2d, AngleUnit.Radian), - (AngleUnit.Deciradian, AngleUnit.Radian) => new Angle((_value) * 1e-1d, AngleUnit.Radian), - (AngleUnit.Degree, AngleUnit.Radian) => new Angle(_value * Math.PI / 180, AngleUnit.Radian), - (AngleUnit.Gradian, AngleUnit.Radian) => new Angle(_value * Math.PI / 200, AngleUnit.Radian), - (AngleUnit.Microdegree, AngleUnit.Radian) => new Angle((_value * Math.PI / 180) * 1e-6d, AngleUnit.Radian), - (AngleUnit.Microradian, AngleUnit.Radian) => new Angle((_value) * 1e-6d, AngleUnit.Radian), - (AngleUnit.Millidegree, AngleUnit.Radian) => new Angle((_value * Math.PI / 180) * 1e-3d, AngleUnit.Radian), - (AngleUnit.Milliradian, AngleUnit.Radian) => new Angle((_value) * 1e-3d, AngleUnit.Radian), - (AngleUnit.Nanodegree, AngleUnit.Radian) => new Angle((_value * Math.PI / 180) * 1e-9d, AngleUnit.Radian), - (AngleUnit.Nanoradian, AngleUnit.Radian) => new Angle((_value) * 1e-9d, AngleUnit.Radian), - (AngleUnit.NatoMil, AngleUnit.Radian) => new Angle(_value * Math.PI / 3200, AngleUnit.Radian), - (AngleUnit.Revolution, AngleUnit.Radian) => new Angle(_value * 2 * Math.PI, AngleUnit.Radian), - - // BaseUnit -> AngleUnit - (AngleUnit.Radian, AngleUnit.Arcminute) => new Angle(_value * 60 * 180 / Math.PI, AngleUnit.Arcminute), - (AngleUnit.Radian, AngleUnit.Arcsecond) => new Angle(_value * 3600 * 180 / Math.PI, AngleUnit.Arcsecond), - (AngleUnit.Radian, AngleUnit.Centiradian) => new Angle((_value) / 1e-2d, AngleUnit.Centiradian), - (AngleUnit.Radian, AngleUnit.Deciradian) => new Angle((_value) / 1e-1d, AngleUnit.Deciradian), - (AngleUnit.Radian, AngleUnit.Degree) => new Angle(_value * 180 / Math.PI, AngleUnit.Degree), - (AngleUnit.Radian, AngleUnit.Gradian) => new Angle(_value * 200 / Math.PI, AngleUnit.Gradian), - (AngleUnit.Radian, AngleUnit.Microdegree) => new Angle((_value * 180 / Math.PI) / 1e-6d, AngleUnit.Microdegree), - (AngleUnit.Radian, AngleUnit.Microradian) => new Angle((_value) / 1e-6d, AngleUnit.Microradian), - (AngleUnit.Radian, AngleUnit.Millidegree) => new Angle((_value * 180 / Math.PI) / 1e-3d, AngleUnit.Millidegree), - (AngleUnit.Radian, AngleUnit.Milliradian) => new Angle((_value) / 1e-3d, AngleUnit.Milliradian), - (AngleUnit.Radian, AngleUnit.Nanodegree) => new Angle((_value * 180 / Math.PI) / 1e-9d, AngleUnit.Nanodegree), - (AngleUnit.Radian, AngleUnit.Nanoradian) => new Angle((_value) / 1e-9d, AngleUnit.Nanoradian), - (AngleUnit.Radian, AngleUnit.NatoMil) => new Angle(_value * 3200 / Math.PI, AngleUnit.NatoMil), - (AngleUnit.Radian, AngleUnit.Revolution) => new Angle(_value / (2 * Math.PI), AngleUnit.Revolution), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Angle ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not AngleUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AngleUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(AngleUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(AngleUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1012,7 +822,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Area.g.cs b/UnitsNet/GeneratedCode/Quantities/Area.g.cs index c9bbcf6329..82863b6d6c 100644 --- a/UnitsNet/GeneratedCode/Quantities/Area.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Area.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Area : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -68,13 +67,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly AreaUnit? _unit; /// @@ -119,7 +118,7 @@ public static AreaInfo CreateDefault(Func>, } /// - /// The for is [L^2]. + /// The for is L^2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); @@ -134,28 +133,52 @@ public static AreaInfo CreateDefault(Func>, /// An of representing the default unit mappings for Area. public static IEnumerable> GetDefaultMappings() { - yield return new (AreaUnit.Acre, "Acre", "Acres", BaseUnits.Undefined); - yield return new (AreaUnit.Hectare, "Hectare", "Hectares", BaseUnits.Undefined); - yield return new (AreaUnit.SquareCentimeter, "SquareCentimeter", "SquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter)); - yield return new (AreaUnit.SquareDecimeter, "SquareDecimeter", "SquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter)); - yield return new (AreaUnit.SquareFoot, "SquareFoot", "SquareFeet", new BaseUnits(length: LengthUnit.Foot)); - yield return new (AreaUnit.SquareInch, "SquareInch", "SquareInches", new BaseUnits(length: LengthUnit.Inch)); - yield return new (AreaUnit.SquareKilometer, "SquareKilometer", "SquareKilometers", new BaseUnits(length: LengthUnit.Kilometer)); + yield return new (AreaUnit.Acre, "Acre", "Acres", BaseUnits.Undefined, + new QuantityValue(78125, 316160658) + ); + yield return new (AreaUnit.Hectare, "Hectare", "Hectares", BaseUnits.Undefined, + new QuantityValue(1, 10000) + ); + yield return new (AreaUnit.SquareCentimeter, "SquareCentimeter", "SquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter), + 10000 + ); + yield return new (AreaUnit.SquareDecimeter, "SquareDecimeter", "SquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter), + 100 + ); + yield return new (AreaUnit.SquareFoot, "SquareFoot", "SquareFeet", new BaseUnits(length: LengthUnit.Foot), + new QuantityValue(1562500, 145161) + ); + yield return new (AreaUnit.SquareInch, "SquareInch", "SquareInches", new BaseUnits(length: LengthUnit.Inch), + new QuantityValue(25000000, 16129) + ); + yield return new (AreaUnit.SquareKilometer, "SquareKilometer", "SquareKilometers", new BaseUnits(length: LengthUnit.Kilometer), + new QuantityValue(1, 1000000) + ); yield return new (AreaUnit.SquareMeter, "SquareMeter", "SquareMeters", new BaseUnits(length: LengthUnit.Meter)); - yield return new (AreaUnit.SquareMicrometer, "SquareMicrometer", "SquareMicrometers", new BaseUnits(length: LengthUnit.Micrometer)); - yield return new (AreaUnit.SquareMile, "SquareMile", "SquareMiles", new BaseUnits(length: LengthUnit.Mile)); - yield return new (AreaUnit.SquareMillimeter, "SquareMillimeter", "SquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter)); - yield return new (AreaUnit.SquareNauticalMile, "SquareNauticalMile", "SquareNauticalMiles", BaseUnits.Undefined); - yield return new (AreaUnit.SquareYard, "SquareYard", "SquareYards", new BaseUnits(length: LengthUnit.Yard)); - yield return new (AreaUnit.UsSurveySquareFoot, "UsSurveySquareFoot", "UsSurveySquareFeet", new BaseUnits(length: LengthUnit.UsSurveyFoot)); + yield return new (AreaUnit.SquareMicrometer, "SquareMicrometer", "SquareMicrometers", new BaseUnits(length: LengthUnit.Micrometer), + 1000000000000 + ); + yield return new (AreaUnit.SquareMile, "SquareMile", "SquareMiles", new BaseUnits(length: LengthUnit.Mile), + new QuantityValue(15625, 40468564224) + ); + yield return new (AreaUnit.SquareMillimeter, "SquareMillimeter", "SquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter), + 1000000 + ); + yield return new (AreaUnit.SquareNauticalMile, "SquareNauticalMile", "SquareNauticalMiles", BaseUnits.Undefined, + new QuantityValue(1, 3429904) + ); + yield return new (AreaUnit.SquareYard, "SquareYard", "SquareYards", new BaseUnits(length: LengthUnit.Yard), + new QuantityValue(1562500, 1306449) + ); + yield return new (AreaUnit.UsSurveySquareFoot, "UsSurveySquareFoot", "UsSurveySquareFeet", new BaseUnits(length: LengthUnit.UsSurveyFoot), + new QuantityValue(15499969, 1440000) + ); } } static Area() { - Info = AreaInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(AreaInfo.CreateDefault); } /// @@ -163,7 +186,7 @@ static Area() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Area(double value, AreaUnit unit) + public Area(QuantityValue value, AreaUnit unit) { _value = value; _unit = unit; @@ -177,7 +200,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -188,7 +211,8 @@ public Area(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -217,10 +241,8 @@ public Area(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public AreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -259,119 +281,79 @@ public Area(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Acres => As(AreaUnit.Acre); + public QuantityValue Acres => this.As(AreaUnit.Acre); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Hectares => As(AreaUnit.Hectare); + public QuantityValue Hectares => this.As(AreaUnit.Hectare); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareCentimeters => As(AreaUnit.SquareCentimeter); + public QuantityValue SquareCentimeters => this.As(AreaUnit.SquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareDecimeters => As(AreaUnit.SquareDecimeter); + public QuantityValue SquareDecimeters => this.As(AreaUnit.SquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareFeet => As(AreaUnit.SquareFoot); + public QuantityValue SquareFeet => this.As(AreaUnit.SquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareInches => As(AreaUnit.SquareInch); + public QuantityValue SquareInches => this.As(AreaUnit.SquareInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareKilometers => As(AreaUnit.SquareKilometer); + public QuantityValue SquareKilometers => this.As(AreaUnit.SquareKilometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareMeters => As(AreaUnit.SquareMeter); + public QuantityValue SquareMeters => this.As(AreaUnit.SquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareMicrometers => As(AreaUnit.SquareMicrometer); + public QuantityValue SquareMicrometers => this.As(AreaUnit.SquareMicrometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareMiles => As(AreaUnit.SquareMile); + public QuantityValue SquareMiles => this.As(AreaUnit.SquareMile); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareMillimeters => As(AreaUnit.SquareMillimeter); + public QuantityValue SquareMillimeters => this.As(AreaUnit.SquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareNauticalMiles => As(AreaUnit.SquareNauticalMile); + public QuantityValue SquareNauticalMiles => this.As(AreaUnit.SquareNauticalMile); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareYards => As(AreaUnit.SquareYard); + public QuantityValue SquareYards => this.As(AreaUnit.SquareYard); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsSurveySquareFeet => As(AreaUnit.UsSurveySquareFoot); + public QuantityValue UsSurveySquareFeet => this.As(AreaUnit.UsSurveySquareFoot); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: AreaUnit -> BaseUnit - unitConverter.SetConversionFunction(AreaUnit.Acre, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); - unitConverter.SetConversionFunction(AreaUnit.Hectare, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); - unitConverter.SetConversionFunction(AreaUnit.SquareCentimeter, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); - unitConverter.SetConversionFunction(AreaUnit.SquareDecimeter, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); - unitConverter.SetConversionFunction(AreaUnit.SquareFoot, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); - unitConverter.SetConversionFunction(AreaUnit.SquareInch, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); - unitConverter.SetConversionFunction(AreaUnit.SquareKilometer, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); - unitConverter.SetConversionFunction(AreaUnit.SquareMicrometer, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); - unitConverter.SetConversionFunction(AreaUnit.SquareMile, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); - unitConverter.SetConversionFunction(AreaUnit.SquareMillimeter, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); - unitConverter.SetConversionFunction(AreaUnit.SquareNauticalMile, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); - unitConverter.SetConversionFunction(AreaUnit.SquareYard, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); - unitConverter.SetConversionFunction(AreaUnit.UsSurveySquareFoot, AreaUnit.SquareMeter, quantity => quantity.ToUnit(AreaUnit.SquareMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> AreaUnit - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.Acre, quantity => quantity.ToUnit(AreaUnit.Acre)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.Hectare, quantity => quantity.ToUnit(AreaUnit.Hectare)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareCentimeter, quantity => quantity.ToUnit(AreaUnit.SquareCentimeter)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareDecimeter, quantity => quantity.ToUnit(AreaUnit.SquareDecimeter)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareFoot, quantity => quantity.ToUnit(AreaUnit.SquareFoot)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareInch, quantity => quantity.ToUnit(AreaUnit.SquareInch)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareKilometer, quantity => quantity.ToUnit(AreaUnit.SquareKilometer)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareMicrometer, quantity => quantity.ToUnit(AreaUnit.SquareMicrometer)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareMile, quantity => quantity.ToUnit(AreaUnit.SquareMile)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareMillimeter, quantity => quantity.ToUnit(AreaUnit.SquareMillimeter)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareNauticalMile, quantity => quantity.ToUnit(AreaUnit.SquareNauticalMile)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.SquareYard, quantity => quantity.ToUnit(AreaUnit.SquareYard)); - unitConverter.SetConversionFunction(AreaUnit.SquareMeter, AreaUnit.UsSurveySquareFoot, quantity => quantity.ToUnit(AreaUnit.UsSurveySquareFoot)); - } - /// /// Get unit abbreviation string. /// @@ -400,7 +382,7 @@ public static string GetAbbreviation(AreaUnit unit, IFormatProvider? provider) /// /// Creates a from . /// - public static Area FromAcres(double value) + public static Area FromAcres(QuantityValue value) { return new Area(value, AreaUnit.Acre); } @@ -408,7 +390,7 @@ public static Area FromAcres(double value) /// /// Creates a from . /// - public static Area FromHectares(double value) + public static Area FromHectares(QuantityValue value) { return new Area(value, AreaUnit.Hectare); } @@ -416,7 +398,7 @@ public static Area FromHectares(double value) /// /// Creates a from . /// - public static Area FromSquareCentimeters(double value) + public static Area FromSquareCentimeters(QuantityValue value) { return new Area(value, AreaUnit.SquareCentimeter); } @@ -424,7 +406,7 @@ public static Area FromSquareCentimeters(double value) /// /// Creates a from . /// - public static Area FromSquareDecimeters(double value) + public static Area FromSquareDecimeters(QuantityValue value) { return new Area(value, AreaUnit.SquareDecimeter); } @@ -432,7 +414,7 @@ public static Area FromSquareDecimeters(double value) /// /// Creates a from . /// - public static Area FromSquareFeet(double value) + public static Area FromSquareFeet(QuantityValue value) { return new Area(value, AreaUnit.SquareFoot); } @@ -440,7 +422,7 @@ public static Area FromSquareFeet(double value) /// /// Creates a from . /// - public static Area FromSquareInches(double value) + public static Area FromSquareInches(QuantityValue value) { return new Area(value, AreaUnit.SquareInch); } @@ -448,7 +430,7 @@ public static Area FromSquareInches(double value) /// /// Creates a from . /// - public static Area FromSquareKilometers(double value) + public static Area FromSquareKilometers(QuantityValue value) { return new Area(value, AreaUnit.SquareKilometer); } @@ -456,7 +438,7 @@ public static Area FromSquareKilometers(double value) /// /// Creates a from . /// - public static Area FromSquareMeters(double value) + public static Area FromSquareMeters(QuantityValue value) { return new Area(value, AreaUnit.SquareMeter); } @@ -464,7 +446,7 @@ public static Area FromSquareMeters(double value) /// /// Creates a from . /// - public static Area FromSquareMicrometers(double value) + public static Area FromSquareMicrometers(QuantityValue value) { return new Area(value, AreaUnit.SquareMicrometer); } @@ -472,7 +454,7 @@ public static Area FromSquareMicrometers(double value) /// /// Creates a from . /// - public static Area FromSquareMiles(double value) + public static Area FromSquareMiles(QuantityValue value) { return new Area(value, AreaUnit.SquareMile); } @@ -480,7 +462,7 @@ public static Area FromSquareMiles(double value) /// /// Creates a from . /// - public static Area FromSquareMillimeters(double value) + public static Area FromSquareMillimeters(QuantityValue value) { return new Area(value, AreaUnit.SquareMillimeter); } @@ -488,7 +470,7 @@ public static Area FromSquareMillimeters(double value) /// /// Creates a from . /// - public static Area FromSquareNauticalMiles(double value) + public static Area FromSquareNauticalMiles(QuantityValue value) { return new Area(value, AreaUnit.SquareNauticalMile); } @@ -496,7 +478,7 @@ public static Area FromSquareNauticalMiles(double value) /// /// Creates a from . /// - public static Area FromSquareYards(double value) + public static Area FromSquareYards(QuantityValue value) { return new Area(value, AreaUnit.SquareYard); } @@ -504,7 +486,7 @@ public static Area FromSquareYards(double value) /// /// Creates a from . /// - public static Area FromUsSurveySquareFeet(double value) + public static Area FromUsSurveySquareFeet(QuantityValue value) { return new Area(value, AreaUnit.UsSurveySquareFoot); } @@ -515,7 +497,7 @@ public static Area FromUsSurveySquareFeet(double value) /// Value to convert from. /// Unit to convert from. /// Area unit value. - public static Area From(double value, AreaUnit fromUnit) + public static Area From(QuantityValue value, AreaUnit fromUnit) { return new Area(value, fromUnit); } @@ -576,10 +558,7 @@ public static Area Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Area Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -607,11 +586,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Area result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Area result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -632,7 +607,7 @@ public static AreaUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -643,7 +618,7 @@ public static AreaUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out AreaUnit unit) { return TryParseUnit(str, null, out unit); @@ -658,7 +633,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out AreaUnit uni /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out AreaUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -677,35 +652,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Area operator +(Area left, Area right) { - return new Area(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Area(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Area operator -(Area left, Area right) { - return new Area(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Area(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -718,7 +693,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// The corresponding inverse quantity, . public ReciprocalArea Inverse() { - return ReciprocalArea.FromInverseSquareMeters(1 / SquareMeters); + return UnitConverter.Default.ConvertTo(Value, Unit, ReciprocalArea.Info); } /// Get from * . @@ -824,97 +799,82 @@ public ReciprocalArea Inverse() /// Returns true if less or equal to. public static bool operator <=(Area left, Area right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Area left, Area right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Area left, Area right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Area left, Area right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Area other, Area tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Area left, Area right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Area other, Area tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Area left, Area right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Area other, Area tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Area otherQuantity)) + if (obj is not Area otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Area other, Area tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Area other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Area. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Area), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Area otherQuantity)) throw new ArgumentException("Expected type Area.", nameof(obj)); + if (obj is not Area otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -926,172 +886,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Area other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AreaUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this Area to another Area with the unit representation . - /// - /// The unit to convert to. - /// A Area with the specified unit. - public Area ToUnit(AreaUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Area with the specified unit. - public Area ToUnit(AreaUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Area), Unit, typeof(Area), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Area)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(AreaUnit unit, [NotNullWhen(true)] out Area? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Area? convertedOrNull = (Unit, unit) switch - { - // AreaUnit -> BaseUnit - (AreaUnit.Acre, AreaUnit.SquareMeter) => new Area(_value * 4046.8564224, AreaUnit.SquareMeter), - (AreaUnit.Hectare, AreaUnit.SquareMeter) => new Area(_value * 1e4, AreaUnit.SquareMeter), - (AreaUnit.SquareCentimeter, AreaUnit.SquareMeter) => new Area(_value * 1e-4, AreaUnit.SquareMeter), - (AreaUnit.SquareDecimeter, AreaUnit.SquareMeter) => new Area(_value * 1e-2, AreaUnit.SquareMeter), - (AreaUnit.SquareFoot, AreaUnit.SquareMeter) => new Area(_value * 9.290304e-2, AreaUnit.SquareMeter), - (AreaUnit.SquareInch, AreaUnit.SquareMeter) => new Area(_value * 0.00064516, AreaUnit.SquareMeter), - (AreaUnit.SquareKilometer, AreaUnit.SquareMeter) => new Area(_value * 1e6, AreaUnit.SquareMeter), - (AreaUnit.SquareMicrometer, AreaUnit.SquareMeter) => new Area(_value * 1e-12, AreaUnit.SquareMeter), - (AreaUnit.SquareMile, AreaUnit.SquareMeter) => new Area(_value * 1609.344 * 1609.344, AreaUnit.SquareMeter), - (AreaUnit.SquareMillimeter, AreaUnit.SquareMeter) => new Area(_value * 1e-6, AreaUnit.SquareMeter), - (AreaUnit.SquareNauticalMile, AreaUnit.SquareMeter) => new Area(_value * 3429904, AreaUnit.SquareMeter), - (AreaUnit.SquareYard, AreaUnit.SquareMeter) => new Area(_value * 0.9144 * 0.9144, AreaUnit.SquareMeter), - (AreaUnit.UsSurveySquareFoot, AreaUnit.SquareMeter) => new Area(_value * (1200.0 / 3937.0) * (1200.0 / 3937.0), AreaUnit.SquareMeter), - - // BaseUnit -> AreaUnit - (AreaUnit.SquareMeter, AreaUnit.Acre) => new Area(_value / 4046.8564224, AreaUnit.Acre), - (AreaUnit.SquareMeter, AreaUnit.Hectare) => new Area(_value / 1e4, AreaUnit.Hectare), - (AreaUnit.SquareMeter, AreaUnit.SquareCentimeter) => new Area(_value / 1e-4, AreaUnit.SquareCentimeter), - (AreaUnit.SquareMeter, AreaUnit.SquareDecimeter) => new Area(_value / 1e-2, AreaUnit.SquareDecimeter), - (AreaUnit.SquareMeter, AreaUnit.SquareFoot) => new Area(_value / 9.290304e-2, AreaUnit.SquareFoot), - (AreaUnit.SquareMeter, AreaUnit.SquareInch) => new Area(_value / 0.00064516, AreaUnit.SquareInch), - (AreaUnit.SquareMeter, AreaUnit.SquareKilometer) => new Area(_value / 1e6, AreaUnit.SquareKilometer), - (AreaUnit.SquareMeter, AreaUnit.SquareMicrometer) => new Area(_value / 1e-12, AreaUnit.SquareMicrometer), - (AreaUnit.SquareMeter, AreaUnit.SquareMile) => new Area(_value / 1609.344 / 1609.344, AreaUnit.SquareMile), - (AreaUnit.SquareMeter, AreaUnit.SquareMillimeter) => new Area(_value / 1e-6, AreaUnit.SquareMillimeter), - (AreaUnit.SquareMeter, AreaUnit.SquareNauticalMile) => new Area(_value / 3429904, AreaUnit.SquareNauticalMile), - (AreaUnit.SquareMeter, AreaUnit.SquareYard) => new Area(_value / 0.9144 / 0.9144, AreaUnit.SquareYard), - (AreaUnit.SquareMeter, AreaUnit.UsSurveySquareFoot) => new Area(_value / (1200.0 / 3937.0) / (1200.0 / 3937.0), AreaUnit.UsSurveySquareFoot), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Area ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not AreaUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(AreaUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(AreaUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1106,7 +918,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs index b0e4e1bbf9..ff5d026723 100644 --- a/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AreaDensity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// The area density of a two-dimensional object is calculated as the mass per unit area. For paper this is also called grammage. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct AreaDensity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly AreaDensityUnit? _unit; /// @@ -104,7 +103,7 @@ public static AreaDensityInfo CreateDefault(Func - /// The for is [L^-2][M]. + /// The for is L^-2M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 1, 0, 0, 0, 0, 0); @@ -119,17 +118,19 @@ public static AreaDensityInfo CreateDefault(FuncAn of representing the default unit mappings for AreaDensity. public static IEnumerable> GetDefaultMappings() { - yield return new (AreaDensityUnit.GramPerSquareMeter, "GramPerSquareMeter", "GramsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram)); + yield return new (AreaDensityUnit.GramPerSquareMeter, "GramPerSquareMeter", "GramsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram), + 1000 + ); yield return new (AreaDensityUnit.KilogramPerSquareMeter, "KilogramPerSquareMeter", "KilogramsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram)); - yield return new (AreaDensityUnit.MilligramPerSquareMeter, "MilligramPerSquareMeter", "MilligramsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram)); + yield return new (AreaDensityUnit.MilligramPerSquareMeter, "MilligramPerSquareMeter", "MilligramsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram), + 1000000 + ); } } static AreaDensity() { - Info = AreaDensityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(AreaDensityInfo.CreateDefault); } /// @@ -137,7 +138,7 @@ static AreaDensity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public AreaDensity(double value, AreaDensityUnit unit) + public AreaDensity(QuantityValue value, AreaDensityUnit unit) { _value = value; _unit = unit; @@ -151,7 +152,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -162,7 +163,8 @@ public AreaDensity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -191,10 +193,8 @@ public AreaDensity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public AreaDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -233,42 +233,24 @@ public AreaDensity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerSquareMeter => As(AreaDensityUnit.GramPerSquareMeter); + public QuantityValue GramsPerSquareMeter => this.As(AreaDensityUnit.GramPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerSquareMeter => As(AreaDensityUnit.KilogramPerSquareMeter); + public QuantityValue KilogramsPerSquareMeter => this.As(AreaDensityUnit.KilogramPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerSquareMeter => As(AreaDensityUnit.MilligramPerSquareMeter); + public QuantityValue MilligramsPerSquareMeter => this.As(AreaDensityUnit.MilligramPerSquareMeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: AreaDensityUnit -> BaseUnit - unitConverter.SetConversionFunction(AreaDensityUnit.GramPerSquareMeter, AreaDensityUnit.KilogramPerSquareMeter, quantity => quantity.ToUnit(AreaDensityUnit.KilogramPerSquareMeter)); - unitConverter.SetConversionFunction(AreaDensityUnit.MilligramPerSquareMeter, AreaDensityUnit.KilogramPerSquareMeter, quantity => quantity.ToUnit(AreaDensityUnit.KilogramPerSquareMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(AreaDensityUnit.KilogramPerSquareMeter, AreaDensityUnit.KilogramPerSquareMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> AreaDensityUnit - unitConverter.SetConversionFunction(AreaDensityUnit.KilogramPerSquareMeter, AreaDensityUnit.GramPerSquareMeter, quantity => quantity.ToUnit(AreaDensityUnit.GramPerSquareMeter)); - unitConverter.SetConversionFunction(AreaDensityUnit.KilogramPerSquareMeter, AreaDensityUnit.MilligramPerSquareMeter, quantity => quantity.ToUnit(AreaDensityUnit.MilligramPerSquareMeter)); - } - /// /// Get unit abbreviation string. /// @@ -297,7 +279,7 @@ public static string GetAbbreviation(AreaDensityUnit unit, IFormatProvider? prov /// /// Creates a from . /// - public static AreaDensity FromGramsPerSquareMeter(double value) + public static AreaDensity FromGramsPerSquareMeter(QuantityValue value) { return new AreaDensity(value, AreaDensityUnit.GramPerSquareMeter); } @@ -305,7 +287,7 @@ public static AreaDensity FromGramsPerSquareMeter(double value) /// /// Creates a from . /// - public static AreaDensity FromKilogramsPerSquareMeter(double value) + public static AreaDensity FromKilogramsPerSquareMeter(QuantityValue value) { return new AreaDensity(value, AreaDensityUnit.KilogramPerSquareMeter); } @@ -313,7 +295,7 @@ public static AreaDensity FromKilogramsPerSquareMeter(double value) /// /// Creates a from . /// - public static AreaDensity FromMilligramsPerSquareMeter(double value) + public static AreaDensity FromMilligramsPerSquareMeter(QuantityValue value) { return new AreaDensity(value, AreaDensityUnit.MilligramPerSquareMeter); } @@ -324,7 +306,7 @@ public static AreaDensity FromMilligramsPerSquareMeter(double value) /// Value to convert from. /// Unit to convert from. /// AreaDensity unit value. - public static AreaDensity From(double value, AreaDensityUnit fromUnit) + public static AreaDensity From(QuantityValue value, AreaDensityUnit fromUnit) { return new AreaDensity(value, fromUnit); } @@ -385,10 +367,7 @@ public static AreaDensity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static AreaDensity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -416,11 +395,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out AreaDensity resu /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out AreaDensity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -441,7 +416,7 @@ public static AreaDensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -452,7 +427,7 @@ public static AreaDensityUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out AreaDensityUnit unit) { return TryParseUnit(str, null, out unit); @@ -467,7 +442,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out AreaDensityU /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out AreaDensityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -486,35 +461,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static AreaDensity operator +(AreaDensity left, AreaDensity right) { - return new AreaDensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new AreaDensity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static AreaDensity operator -(AreaDensity left, AreaDensity right) { - return new AreaDensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new AreaDensity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -536,97 +511,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(AreaDensity left, AreaDensity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(AreaDensity left, AreaDensity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(AreaDensity left, AreaDensity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(AreaDensity left, AreaDensity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(AreaDensity other, AreaDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(AreaDensity left, AreaDensity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(AreaDensity other, AreaDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(AreaDensity left, AreaDensity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(AreaDensity other, AreaDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is AreaDensity otherQuantity)) + if (obj is not AreaDensity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(AreaDensity other, AreaDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(AreaDensity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current AreaDensity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(AreaDensity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is AreaDensity otherQuantity)) throw new ArgumentException("Expected type AreaDensity.", nameof(obj)); + if (obj is not AreaDensity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -638,150 +598,24 @@ public int CompareTo(object? obj) /// public int CompareTo(AreaDensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AreaDensityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this AreaDensity to another AreaDensity with the unit representation . - /// - /// The unit to convert to. - /// A AreaDensity with the specified unit. - public AreaDensity ToUnit(AreaDensityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A AreaDensity with the specified unit. - public AreaDensity ToUnit(AreaDensityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(AreaDensity), Unit, typeof(AreaDensity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (AreaDensity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(AreaDensityUnit unit, [NotNullWhen(true)] out AreaDensity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - AreaDensity? convertedOrNull = (Unit, unit) switch - { - // AreaDensityUnit -> BaseUnit - (AreaDensityUnit.GramPerSquareMeter, AreaDensityUnit.KilogramPerSquareMeter) => new AreaDensity(_value / 1000, AreaDensityUnit.KilogramPerSquareMeter), - (AreaDensityUnit.MilligramPerSquareMeter, AreaDensityUnit.KilogramPerSquareMeter) => new AreaDensity(_value / 1000000, AreaDensityUnit.KilogramPerSquareMeter), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> AreaDensityUnit - (AreaDensityUnit.KilogramPerSquareMeter, AreaDensityUnit.GramPerSquareMeter) => new AreaDensity(_value * 1000, AreaDensityUnit.GramPerSquareMeter), - (AreaDensityUnit.KilogramPerSquareMeter, AreaDensityUnit.MilligramPerSquareMeter) => new AreaDensity(_value * 1000000, AreaDensityUnit.MilligramPerSquareMeter), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public AreaDensity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not AreaDensityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaDensityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is AreaDensityUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaDensityUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(AreaDensityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(AreaDensityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -796,7 +630,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs index 9d9f232be4..641d032dc4 100644 --- a/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/AreaMomentOfInertia.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// A geometric property of an area that reflects how its points are distributed with regard to an axis. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct AreaMomentOfInertia : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -54,13 +53,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly AreaMomentOfInertiaUnit? _unit; /// @@ -105,7 +104,7 @@ public static AreaMomentOfInertiaInfo CreateDefault(Func - /// The for is [L^4]. + /// The for is L^4. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(4, 0, 0, 0, 0, 0, 0); @@ -120,20 +119,28 @@ public static AreaMomentOfInertiaInfo CreateDefault(FuncAn of representing the default unit mappings for AreaMomentOfInertia. public static IEnumerable> GetDefaultMappings() { - yield return new (AreaMomentOfInertiaUnit.CentimeterToTheFourth, "CentimeterToTheFourth", "CentimetersToTheFourth", new BaseUnits(length: LengthUnit.Centimeter)); - yield return new (AreaMomentOfInertiaUnit.DecimeterToTheFourth, "DecimeterToTheFourth", "DecimetersToTheFourth", new BaseUnits(length: LengthUnit.Decimeter)); - yield return new (AreaMomentOfInertiaUnit.FootToTheFourth, "FootToTheFourth", "FeetToTheFourth", new BaseUnits(length: LengthUnit.Foot)); - yield return new (AreaMomentOfInertiaUnit.InchToTheFourth, "InchToTheFourth", "InchesToTheFourth", new BaseUnits(length: LengthUnit.Inch)); + yield return new (AreaMomentOfInertiaUnit.CentimeterToTheFourth, "CentimeterToTheFourth", "CentimetersToTheFourth", new BaseUnits(length: LengthUnit.Centimeter), + 100000000 + ); + yield return new (AreaMomentOfInertiaUnit.DecimeterToTheFourth, "DecimeterToTheFourth", "DecimetersToTheFourth", new BaseUnits(length: LengthUnit.Decimeter), + 10000 + ); + yield return new (AreaMomentOfInertiaUnit.FootToTheFourth, "FootToTheFourth", "FeetToTheFourth", new BaseUnits(length: LengthUnit.Foot), + new QuantityValue(2441406250000, 21071715921) + ); + yield return new (AreaMomentOfInertiaUnit.InchToTheFourth, "InchToTheFourth", "InchesToTheFourth", new BaseUnits(length: LengthUnit.Inch), + new QuantityValue(625000000000000, 260144641) + ); yield return new (AreaMomentOfInertiaUnit.MeterToTheFourth, "MeterToTheFourth", "MetersToTheFourth", new BaseUnits(length: LengthUnit.Meter)); - yield return new (AreaMomentOfInertiaUnit.MillimeterToTheFourth, "MillimeterToTheFourth", "MillimetersToTheFourth", new BaseUnits(length: LengthUnit.Millimeter)); + yield return new (AreaMomentOfInertiaUnit.MillimeterToTheFourth, "MillimeterToTheFourth", "MillimetersToTheFourth", new BaseUnits(length: LengthUnit.Millimeter), + 1000000000000 + ); } } static AreaMomentOfInertia() { - Info = AreaMomentOfInertiaInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(AreaMomentOfInertiaInfo.CreateDefault); } /// @@ -141,7 +148,7 @@ static AreaMomentOfInertia() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public AreaMomentOfInertia(double value, AreaMomentOfInertiaUnit unit) + public AreaMomentOfInertia(QuantityValue value, AreaMomentOfInertiaUnit unit) { _value = value; _unit = unit; @@ -155,7 +162,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -166,7 +173,8 @@ public AreaMomentOfInertia(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -195,10 +203,8 @@ public AreaMomentOfInertia(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public AreaMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -237,63 +243,39 @@ public AreaMomentOfInertia(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentimetersToTheFourth => As(AreaMomentOfInertiaUnit.CentimeterToTheFourth); + public QuantityValue CentimetersToTheFourth => this.As(AreaMomentOfInertiaUnit.CentimeterToTheFourth); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecimetersToTheFourth => As(AreaMomentOfInertiaUnit.DecimeterToTheFourth); + public QuantityValue DecimetersToTheFourth => this.As(AreaMomentOfInertiaUnit.DecimeterToTheFourth); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double FeetToTheFourth => As(AreaMomentOfInertiaUnit.FootToTheFourth); + public QuantityValue FeetToTheFourth => this.As(AreaMomentOfInertiaUnit.FootToTheFourth); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InchesToTheFourth => As(AreaMomentOfInertiaUnit.InchToTheFourth); + public QuantityValue InchesToTheFourth => this.As(AreaMomentOfInertiaUnit.InchToTheFourth); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MetersToTheFourth => As(AreaMomentOfInertiaUnit.MeterToTheFourth); + public QuantityValue MetersToTheFourth => this.As(AreaMomentOfInertiaUnit.MeterToTheFourth); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimetersToTheFourth => As(AreaMomentOfInertiaUnit.MillimeterToTheFourth); + public QuantityValue MillimetersToTheFourth => this.As(AreaMomentOfInertiaUnit.MillimeterToTheFourth); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: AreaMomentOfInertiaUnit -> BaseUnit - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.CentimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.MeterToTheFourth)); - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.DecimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.MeterToTheFourth)); - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.FootToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.MeterToTheFourth)); - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.InchToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.MeterToTheFourth)); - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MillimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.MeterToTheFourth)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth, quantity => quantity); - - // Register in unit converter: BaseUnit -> AreaMomentOfInertiaUnit - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.CentimeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.CentimeterToTheFourth)); - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.DecimeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.DecimeterToTheFourth)); - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.FootToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.FootToTheFourth)); - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.InchToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.InchToTheFourth)); - unitConverter.SetConversionFunction(AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.MillimeterToTheFourth, quantity => quantity.ToUnit(AreaMomentOfInertiaUnit.MillimeterToTheFourth)); - } - /// /// Get unit abbreviation string. /// @@ -322,7 +304,7 @@ public static string GetAbbreviation(AreaMomentOfInertiaUnit unit, IFormatProvid /// /// Creates a from . /// - public static AreaMomentOfInertia FromCentimetersToTheFourth(double value) + public static AreaMomentOfInertia FromCentimetersToTheFourth(QuantityValue value) { return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.CentimeterToTheFourth); } @@ -330,7 +312,7 @@ public static AreaMomentOfInertia FromCentimetersToTheFourth(double value) /// /// Creates a from . /// - public static AreaMomentOfInertia FromDecimetersToTheFourth(double value) + public static AreaMomentOfInertia FromDecimetersToTheFourth(QuantityValue value) { return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.DecimeterToTheFourth); } @@ -338,7 +320,7 @@ public static AreaMomentOfInertia FromDecimetersToTheFourth(double value) /// /// Creates a from . /// - public static AreaMomentOfInertia FromFeetToTheFourth(double value) + public static AreaMomentOfInertia FromFeetToTheFourth(QuantityValue value) { return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.FootToTheFourth); } @@ -346,7 +328,7 @@ public static AreaMomentOfInertia FromFeetToTheFourth(double value) /// /// Creates a from . /// - public static AreaMomentOfInertia FromInchesToTheFourth(double value) + public static AreaMomentOfInertia FromInchesToTheFourth(QuantityValue value) { return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.InchToTheFourth); } @@ -354,7 +336,7 @@ public static AreaMomentOfInertia FromInchesToTheFourth(double value) /// /// Creates a from . /// - public static AreaMomentOfInertia FromMetersToTheFourth(double value) + public static AreaMomentOfInertia FromMetersToTheFourth(QuantityValue value) { return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MeterToTheFourth); } @@ -362,7 +344,7 @@ public static AreaMomentOfInertia FromMetersToTheFourth(double value) /// /// Creates a from . /// - public static AreaMomentOfInertia FromMillimetersToTheFourth(double value) + public static AreaMomentOfInertia FromMillimetersToTheFourth(QuantityValue value) { return new AreaMomentOfInertia(value, AreaMomentOfInertiaUnit.MillimeterToTheFourth); } @@ -373,7 +355,7 @@ public static AreaMomentOfInertia FromMillimetersToTheFourth(double value) /// Value to convert from. /// Unit to convert from. /// AreaMomentOfInertia unit value. - public static AreaMomentOfInertia From(double value, AreaMomentOfInertiaUnit fromUnit) + public static AreaMomentOfInertia From(QuantityValue value, AreaMomentOfInertiaUnit fromUnit) { return new AreaMomentOfInertia(value, fromUnit); } @@ -434,10 +416,7 @@ public static AreaMomentOfInertia Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static AreaMomentOfInertia Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -465,11 +444,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out AreaMomentOfIner /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out AreaMomentOfInertia result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -490,7 +465,7 @@ public static AreaMomentOfInertiaUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -501,7 +476,7 @@ public static AreaMomentOfInertiaUnit ParseUnit(string str, IFormatProvider? pro return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out AreaMomentOfInertiaUnit unit) { return TryParseUnit(str, null, out unit); @@ -516,7 +491,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out AreaMomentOf /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out AreaMomentOfInertiaUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -535,35 +510,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static AreaMomentOfInertia operator +(AreaMomentOfInertia left, AreaMomentOfInertia right) { - return new AreaMomentOfInertia(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new AreaMomentOfInertia(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static AreaMomentOfInertia operator -(AreaMomentOfInertia left, AreaMomentOfInertia right) { - return new AreaMomentOfInertia(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new AreaMomentOfInertia(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -591,97 +566,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(AreaMomentOfInertia left, AreaMomentOfInertia right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(AreaMomentOfInertia left, AreaMomentOfInertia right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(AreaMomentOfInertia left, AreaMomentOfInertia right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(AreaMomentOfInertia left, AreaMomentOfInertia right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(AreaMomentOfInertia other, AreaMomentOfInertia tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(AreaMomentOfInertia left, AreaMomentOfInertia right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(AreaMomentOfInertia other, AreaMomentOfInertia tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(AreaMomentOfInertia left, AreaMomentOfInertia right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(AreaMomentOfInertia other, AreaMomentOfInertia tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is AreaMomentOfInertia otherQuantity)) + if (obj is not AreaMomentOfInertia otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(AreaMomentOfInertia other, AreaMomentOfInertia tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(AreaMomentOfInertia other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current AreaMomentOfInertia. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(AreaMomentOfInertia), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is AreaMomentOfInertia otherQuantity)) throw new ArgumentException("Expected type AreaMomentOfInertia.", nameof(obj)); + if (obj is not AreaMomentOfInertia otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -693,156 +653,24 @@ public int CompareTo(object? obj) /// public int CompareTo(AreaMomentOfInertia other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(AreaMomentOfInertiaUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this AreaMomentOfInertia to another AreaMomentOfInertia with the unit representation . - /// - /// The unit to convert to. - /// A AreaMomentOfInertia with the specified unit. - public AreaMomentOfInertia ToUnit(AreaMomentOfInertiaUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A AreaMomentOfInertia with the specified unit. - public AreaMomentOfInertia ToUnit(AreaMomentOfInertiaUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(AreaMomentOfInertia), Unit, typeof(AreaMomentOfInertia), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (AreaMomentOfInertia)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(AreaMomentOfInertiaUnit unit, [NotNullWhen(true)] out AreaMomentOfInertia? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - AreaMomentOfInertia? convertedOrNull = (Unit, unit) switch - { - // AreaMomentOfInertiaUnit -> BaseUnit - (AreaMomentOfInertiaUnit.CentimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth) => new AreaMomentOfInertia(_value / 1e8, AreaMomentOfInertiaUnit.MeterToTheFourth), - (AreaMomentOfInertiaUnit.DecimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth) => new AreaMomentOfInertia(_value / 1e4, AreaMomentOfInertiaUnit.MeterToTheFourth), - (AreaMomentOfInertiaUnit.FootToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth) => new AreaMomentOfInertia(_value * 0.0086309748412416, AreaMomentOfInertiaUnit.MeterToTheFourth), - (AreaMomentOfInertiaUnit.InchToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth) => new AreaMomentOfInertia(_value * 0.0000004162314256, AreaMomentOfInertiaUnit.MeterToTheFourth), - (AreaMomentOfInertiaUnit.MillimeterToTheFourth, AreaMomentOfInertiaUnit.MeterToTheFourth) => new AreaMomentOfInertia(_value / 1e12, AreaMomentOfInertiaUnit.MeterToTheFourth), - - // BaseUnit -> AreaMomentOfInertiaUnit - (AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.CentimeterToTheFourth) => new AreaMomentOfInertia(_value * 1e8, AreaMomentOfInertiaUnit.CentimeterToTheFourth), - (AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.DecimeterToTheFourth) => new AreaMomentOfInertia(_value * 1e4, AreaMomentOfInertiaUnit.DecimeterToTheFourth), - (AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.FootToTheFourth) => new AreaMomentOfInertia(_value / 0.0086309748412416, AreaMomentOfInertiaUnit.FootToTheFourth), - (AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.InchToTheFourth) => new AreaMomentOfInertia(_value / 0.0000004162314256, AreaMomentOfInertiaUnit.InchToTheFourth), - (AreaMomentOfInertiaUnit.MeterToTheFourth, AreaMomentOfInertiaUnit.MillimeterToTheFourth) => new AreaMomentOfInertia(_value * 1e12, AreaMomentOfInertiaUnit.MillimeterToTheFourth), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public AreaMomentOfInertia ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not AreaMomentOfInertiaUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(AreaMomentOfInertiaUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(AreaMomentOfInertiaUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(AreaMomentOfInertiaUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -857,7 +685,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs b/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs index fc62a899a3..e990628052 100644 --- a/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/BitRate.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Bit_rate /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct BitRate : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly BitRateUnit? _unit; /// @@ -104,7 +103,7 @@ public static BitRateInfo CreateDefault(Func - /// The for is [T^-1]. + /// The for is T^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); @@ -120,52 +119,126 @@ public static BitRateInfo CreateDefault(Func> GetDefaultMappings() { yield return new (BitRateUnit.BitPerSecond, "BitPerSecond", "BitsPerSecond", new BaseUnits(time: DurationUnit.Second)); - yield return new (BitRateUnit.BytePerSecond, "BytePerSecond", "BytesPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.ExabitPerSecond, "ExabitPerSecond", "ExabitsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.ExabytePerSecond, "ExabytePerSecond", "ExabytesPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.ExaoctetPerSecond, "ExaoctetPerSecond", "ExaoctetsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.ExbibitPerSecond, "ExbibitPerSecond", "ExbibitsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.ExbibytePerSecond, "ExbibytePerSecond", "ExbibytesPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.ExbioctetPerSecond, "ExbioctetPerSecond", "ExbioctetsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.GibibitPerSecond, "GibibitPerSecond", "GibibitsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.GibibytePerSecond, "GibibytePerSecond", "GibibytesPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.GibioctetPerSecond, "GibioctetPerSecond", "GibioctetsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.GigabitPerSecond, "GigabitPerSecond", "GigabitsPerSecond", new BaseUnits(time: DurationUnit.Nanosecond)); - yield return new (BitRateUnit.GigabytePerSecond, "GigabytePerSecond", "GigabytesPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.GigaoctetPerSecond, "GigaoctetPerSecond", "GigaoctetsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.KibibitPerSecond, "KibibitPerSecond", "KibibitsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.KibibytePerSecond, "KibibytePerSecond", "KibibytesPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.KibioctetPerSecond, "KibioctetPerSecond", "KibioctetsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.KilobitPerSecond, "KilobitPerSecond", "KilobitsPerSecond", new BaseUnits(time: DurationUnit.Millisecond)); - yield return new (BitRateUnit.KilobytePerSecond, "KilobytePerSecond", "KilobytesPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.KilooctetPerSecond, "KilooctetPerSecond", "KilooctetsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.MebibitPerSecond, "MebibitPerSecond", "MebibitsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.MebibytePerSecond, "MebibytePerSecond", "MebibytesPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.MebioctetPerSecond, "MebioctetPerSecond", "MebioctetsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.MegabitPerSecond, "MegabitPerSecond", "MegabitsPerSecond", new BaseUnits(time: DurationUnit.Microsecond)); - yield return new (BitRateUnit.MegabytePerSecond, "MegabytePerSecond", "MegabytesPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.MegaoctetPerSecond, "MegaoctetPerSecond", "MegaoctetsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.OctetPerSecond, "OctetPerSecond", "OctetsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.PebibitPerSecond, "PebibitPerSecond", "PebibitsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.PebibytePerSecond, "PebibytePerSecond", "PebibytesPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.PebioctetPerSecond, "PebioctetPerSecond", "PebioctetsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.PetabitPerSecond, "PetabitPerSecond", "PetabitsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.PetabytePerSecond, "PetabytePerSecond", "PetabytesPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.PetaoctetPerSecond, "PetaoctetPerSecond", "PetaoctetsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.TebibitPerSecond, "TebibitPerSecond", "TebibitsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.TebibytePerSecond, "TebibytePerSecond", "TebibytesPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.TebioctetPerSecond, "TebioctetPerSecond", "TebioctetsPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.TerabitPerSecond, "TerabitPerSecond", "TerabitsPerSecond", new BaseUnits(time: DurationUnit.Picosecond)); - yield return new (BitRateUnit.TerabytePerSecond, "TerabytePerSecond", "TerabytesPerSecond", BaseUnits.Undefined); - yield return new (BitRateUnit.TeraoctetPerSecond, "TeraoctetPerSecond", "TeraoctetsPerSecond", BaseUnits.Undefined); + yield return new (BitRateUnit.BytePerSecond, "BytePerSecond", "BytesPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8) + ); + yield return new (BitRateUnit.ExabitPerSecond, "ExabitPerSecond", "ExabitsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000000000) + ); + yield return new (BitRateUnit.ExabytePerSecond, "ExabytePerSecond", "ExabytesPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8000000000000000000) + ); + yield return new (BitRateUnit.ExaoctetPerSecond, "ExaoctetPerSecond", "ExaoctetsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8000000000000000000) + ); + yield return new (BitRateUnit.ExbibitPerSecond, "ExbibitPerSecond", "ExbibitsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 1152921504606846976) + ); + yield return new (BitRateUnit.ExbibytePerSecond, "ExbibytePerSecond", "ExbibytesPerSecond", BaseUnits.Undefined, + new QuantityValue(1, BigInteger.Pow(2, 63)) + ); + yield return new (BitRateUnit.ExbioctetPerSecond, "ExbioctetPerSecond", "ExbioctetsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, BigInteger.Pow(2, 63)) + ); + yield return new (BitRateUnit.GibibitPerSecond, "GibibitPerSecond", "GibibitsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 1073741824) + ); + yield return new (BitRateUnit.GibibytePerSecond, "GibibytePerSecond", "GibibytesPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8589934592) + ); + yield return new (BitRateUnit.GibioctetPerSecond, "GibioctetPerSecond", "GibioctetsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8589934592) + ); + yield return new (BitRateUnit.GigabitPerSecond, "GigabitPerSecond", "GigabitsPerSecond", new BaseUnits(time: DurationUnit.Nanosecond), + new QuantityValue(1, 1000000000) + ); + yield return new (BitRateUnit.GigabytePerSecond, "GigabytePerSecond", "GigabytesPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8000000000) + ); + yield return new (BitRateUnit.GigaoctetPerSecond, "GigaoctetPerSecond", "GigaoctetsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8000000000) + ); + yield return new (BitRateUnit.KibibitPerSecond, "KibibitPerSecond", "KibibitsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 1024) + ); + yield return new (BitRateUnit.KibibytePerSecond, "KibibytePerSecond", "KibibytesPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8192) + ); + yield return new (BitRateUnit.KibioctetPerSecond, "KibioctetPerSecond", "KibioctetsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8192) + ); + yield return new (BitRateUnit.KilobitPerSecond, "KilobitPerSecond", "KilobitsPerSecond", new BaseUnits(time: DurationUnit.Millisecond), + new QuantityValue(1, 1000) + ); + yield return new (BitRateUnit.KilobytePerSecond, "KilobytePerSecond", "KilobytesPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8000) + ); + yield return new (BitRateUnit.KilooctetPerSecond, "KilooctetPerSecond", "KilooctetsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8000) + ); + yield return new (BitRateUnit.MebibitPerSecond, "MebibitPerSecond", "MebibitsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 1048576) + ); + yield return new (BitRateUnit.MebibytePerSecond, "MebibytePerSecond", "MebibytesPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8388608) + ); + yield return new (BitRateUnit.MebioctetPerSecond, "MebioctetPerSecond", "MebioctetsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8388608) + ); + yield return new (BitRateUnit.MegabitPerSecond, "MegabitPerSecond", "MegabitsPerSecond", new BaseUnits(time: DurationUnit.Microsecond), + new QuantityValue(1, 1000000) + ); + yield return new (BitRateUnit.MegabytePerSecond, "MegabytePerSecond", "MegabytesPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8000000) + ); + yield return new (BitRateUnit.MegaoctetPerSecond, "MegaoctetPerSecond", "MegaoctetsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8000000) + ); + yield return new (BitRateUnit.OctetPerSecond, "OctetPerSecond", "OctetsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8) + ); + yield return new (BitRateUnit.PebibitPerSecond, "PebibitPerSecond", "PebibitsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 1125899906842624) + ); + yield return new (BitRateUnit.PebibytePerSecond, "PebibytePerSecond", "PebibytesPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 9007199254740992) + ); + yield return new (BitRateUnit.PebioctetPerSecond, "PebioctetPerSecond", "PebioctetsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 9007199254740992) + ); + yield return new (BitRateUnit.PetabitPerSecond, "PetabitPerSecond", "PetabitsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000000) + ); + yield return new (BitRateUnit.PetabytePerSecond, "PetabytePerSecond", "PetabytesPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8000000000000000) + ); + yield return new (BitRateUnit.PetaoctetPerSecond, "PetaoctetPerSecond", "PetaoctetsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8000000000000000) + ); + yield return new (BitRateUnit.TebibitPerSecond, "TebibitPerSecond", "TebibitsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 1099511627776) + ); + yield return new (BitRateUnit.TebibytePerSecond, "TebibytePerSecond", "TebibytesPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8796093022208) + ); + yield return new (BitRateUnit.TebioctetPerSecond, "TebioctetPerSecond", "TebioctetsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8796093022208) + ); + yield return new (BitRateUnit.TerabitPerSecond, "TerabitPerSecond", "TerabitsPerSecond", new BaseUnits(time: DurationUnit.Picosecond), + new QuantityValue(1, 1000000000000) + ); + yield return new (BitRateUnit.TerabytePerSecond, "TerabytePerSecond", "TerabytesPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8000000000000) + ); + yield return new (BitRateUnit.TeraoctetPerSecond, "TeraoctetPerSecond", "TeraoctetsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 8000000000000) + ); } } static BitRate() { - Info = BitRateInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(BitRateInfo.CreateDefault); } /// @@ -173,7 +246,7 @@ static BitRate() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public BitRate(double value, BitRateUnit unit) + public BitRate(QuantityValue value, BitRateUnit unit) { _value = value; _unit = unit; @@ -187,7 +260,7 @@ public BitRate(double value, BitRateUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public BitRate(double value, UnitSystem unitSystem) + public BitRate(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -198,7 +271,8 @@ public BitRate(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -227,10 +301,8 @@ public BitRate(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public BitRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -269,294 +341,204 @@ public BitRate(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BitsPerSecond => As(BitRateUnit.BitPerSecond); + public QuantityValue BitsPerSecond => this.As(BitRateUnit.BitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BytesPerSecond => As(BitRateUnit.BytePerSecond); + public QuantityValue BytesPerSecond => this.As(BitRateUnit.BytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ExabitsPerSecond => As(BitRateUnit.ExabitPerSecond); + public QuantityValue ExabitsPerSecond => this.As(BitRateUnit.ExabitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ExabytesPerSecond => As(BitRateUnit.ExabytePerSecond); + public QuantityValue ExabytesPerSecond => this.As(BitRateUnit.ExabytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ExaoctetsPerSecond => As(BitRateUnit.ExaoctetPerSecond); + public QuantityValue ExaoctetsPerSecond => this.As(BitRateUnit.ExaoctetPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ExbibitsPerSecond => As(BitRateUnit.ExbibitPerSecond); + public QuantityValue ExbibitsPerSecond => this.As(BitRateUnit.ExbibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ExbibytesPerSecond => As(BitRateUnit.ExbibytePerSecond); + public QuantityValue ExbibytesPerSecond => this.As(BitRateUnit.ExbibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ExbioctetsPerSecond => As(BitRateUnit.ExbioctetPerSecond); + public QuantityValue ExbioctetsPerSecond => this.As(BitRateUnit.ExbioctetPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GibibitsPerSecond => As(BitRateUnit.GibibitPerSecond); + public QuantityValue GibibitsPerSecond => this.As(BitRateUnit.GibibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GibibytesPerSecond => As(BitRateUnit.GibibytePerSecond); + public QuantityValue GibibytesPerSecond => this.As(BitRateUnit.GibibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GibioctetsPerSecond => As(BitRateUnit.GibioctetPerSecond); + public QuantityValue GibioctetsPerSecond => this.As(BitRateUnit.GibioctetPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigabitsPerSecond => As(BitRateUnit.GigabitPerSecond); + public QuantityValue GigabitsPerSecond => this.As(BitRateUnit.GigabitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigabytesPerSecond => As(BitRateUnit.GigabytePerSecond); + public QuantityValue GigabytesPerSecond => this.As(BitRateUnit.GigabytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigaoctetsPerSecond => As(BitRateUnit.GigaoctetPerSecond); + public QuantityValue GigaoctetsPerSecond => this.As(BitRateUnit.GigaoctetPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KibibitsPerSecond => As(BitRateUnit.KibibitPerSecond); + public QuantityValue KibibitsPerSecond => this.As(BitRateUnit.KibibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KibibytesPerSecond => As(BitRateUnit.KibibytePerSecond); + public QuantityValue KibibytesPerSecond => this.As(BitRateUnit.KibibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KibioctetsPerSecond => As(BitRateUnit.KibioctetPerSecond); + public QuantityValue KibioctetsPerSecond => this.As(BitRateUnit.KibioctetPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilobitsPerSecond => As(BitRateUnit.KilobitPerSecond); + public QuantityValue KilobitsPerSecond => this.As(BitRateUnit.KilobitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilobytesPerSecond => As(BitRateUnit.KilobytePerSecond); + public QuantityValue KilobytesPerSecond => this.As(BitRateUnit.KilobytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilooctetsPerSecond => As(BitRateUnit.KilooctetPerSecond); + public QuantityValue KilooctetsPerSecond => this.As(BitRateUnit.KilooctetPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MebibitsPerSecond => As(BitRateUnit.MebibitPerSecond); + public QuantityValue MebibitsPerSecond => this.As(BitRateUnit.MebibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MebibytesPerSecond => As(BitRateUnit.MebibytePerSecond); + public QuantityValue MebibytesPerSecond => this.As(BitRateUnit.MebibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MebioctetsPerSecond => As(BitRateUnit.MebioctetPerSecond); + public QuantityValue MebioctetsPerSecond => this.As(BitRateUnit.MebioctetPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegabitsPerSecond => As(BitRateUnit.MegabitPerSecond); + public QuantityValue MegabitsPerSecond => this.As(BitRateUnit.MegabitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegabytesPerSecond => As(BitRateUnit.MegabytePerSecond); + public QuantityValue MegabytesPerSecond => this.As(BitRateUnit.MegabytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegaoctetsPerSecond => As(BitRateUnit.MegaoctetPerSecond); + public QuantityValue MegaoctetsPerSecond => this.As(BitRateUnit.MegaoctetPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double OctetsPerSecond => As(BitRateUnit.OctetPerSecond); + public QuantityValue OctetsPerSecond => this.As(BitRateUnit.OctetPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PebibitsPerSecond => As(BitRateUnit.PebibitPerSecond); + public QuantityValue PebibitsPerSecond => this.As(BitRateUnit.PebibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PebibytesPerSecond => As(BitRateUnit.PebibytePerSecond); + public QuantityValue PebibytesPerSecond => this.As(BitRateUnit.PebibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PebioctetsPerSecond => As(BitRateUnit.PebioctetPerSecond); + public QuantityValue PebioctetsPerSecond => this.As(BitRateUnit.PebioctetPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PetabitsPerSecond => As(BitRateUnit.PetabitPerSecond); + public QuantityValue PetabitsPerSecond => this.As(BitRateUnit.PetabitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PetabytesPerSecond => As(BitRateUnit.PetabytePerSecond); + public QuantityValue PetabytesPerSecond => this.As(BitRateUnit.PetabytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PetaoctetsPerSecond => As(BitRateUnit.PetaoctetPerSecond); + public QuantityValue PetaoctetsPerSecond => this.As(BitRateUnit.PetaoctetPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TebibitsPerSecond => As(BitRateUnit.TebibitPerSecond); + public QuantityValue TebibitsPerSecond => this.As(BitRateUnit.TebibitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TebibytesPerSecond => As(BitRateUnit.TebibytePerSecond); + public QuantityValue TebibytesPerSecond => this.As(BitRateUnit.TebibytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TebioctetsPerSecond => As(BitRateUnit.TebioctetPerSecond); + public QuantityValue TebioctetsPerSecond => this.As(BitRateUnit.TebioctetPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TerabitsPerSecond => As(BitRateUnit.TerabitPerSecond); + public QuantityValue TerabitsPerSecond => this.As(BitRateUnit.TerabitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TerabytesPerSecond => As(BitRateUnit.TerabytePerSecond); + public QuantityValue TerabytesPerSecond => this.As(BitRateUnit.TerabytePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TeraoctetsPerSecond => As(BitRateUnit.TeraoctetPerSecond); + public QuantityValue TeraoctetsPerSecond => this.As(BitRateUnit.TeraoctetPerSecond); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: BitRateUnit -> BaseUnit - unitConverter.SetConversionFunction(BitRateUnit.BytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.ExabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.ExabytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.ExaoctetPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.ExbibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.ExbibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.ExbioctetPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.GibibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.GibibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.GibioctetPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.GigabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.GigabytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.GigaoctetPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.KibibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.KibibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.KibioctetPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.KilobitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.KilobytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.KilooctetPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.MebibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.MebibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.MebioctetPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.MegabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.MegabytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.MegaoctetPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.OctetPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.PebibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.PebibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.PebioctetPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.PetabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.PetabytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.PetaoctetPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.TebibitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.TebibytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.TebioctetPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.TerabitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.TerabytePerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.TeraoctetPerSecond, BitRateUnit.BitPerSecond, quantity => quantity.ToUnit(BitRateUnit.BitPerSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.BitPerSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> BitRateUnit - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.BytePerSecond, quantity => quantity.ToUnit(BitRateUnit.BytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.ExabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.ExabitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.ExabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.ExabytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.ExaoctetPerSecond, quantity => quantity.ToUnit(BitRateUnit.ExaoctetPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.ExbibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.ExbibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.ExbibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.ExbibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.ExbioctetPerSecond, quantity => quantity.ToUnit(BitRateUnit.ExbioctetPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GibibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.GibibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GibibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.GibibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GibioctetPerSecond, quantity => quantity.ToUnit(BitRateUnit.GibioctetPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GigabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.GigabitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GigabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.GigabytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.GigaoctetPerSecond, quantity => quantity.ToUnit(BitRateUnit.GigaoctetPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KibibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.KibibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KibibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.KibibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KibioctetPerSecond, quantity => quantity.ToUnit(BitRateUnit.KibioctetPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KilobitPerSecond, quantity => quantity.ToUnit(BitRateUnit.KilobitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KilobytePerSecond, quantity => quantity.ToUnit(BitRateUnit.KilobytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.KilooctetPerSecond, quantity => quantity.ToUnit(BitRateUnit.KilooctetPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MebibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.MebibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MebibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.MebibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MebioctetPerSecond, quantity => quantity.ToUnit(BitRateUnit.MebioctetPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MegabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.MegabitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MegabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.MegabytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.MegaoctetPerSecond, quantity => quantity.ToUnit(BitRateUnit.MegaoctetPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.OctetPerSecond, quantity => quantity.ToUnit(BitRateUnit.OctetPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PebibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.PebibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PebibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.PebibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PebioctetPerSecond, quantity => quantity.ToUnit(BitRateUnit.PebioctetPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PetabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.PetabitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PetabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.PetabytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.PetaoctetPerSecond, quantity => quantity.ToUnit(BitRateUnit.PetaoctetPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TebibitPerSecond, quantity => quantity.ToUnit(BitRateUnit.TebibitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TebibytePerSecond, quantity => quantity.ToUnit(BitRateUnit.TebibytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TebioctetPerSecond, quantity => quantity.ToUnit(BitRateUnit.TebioctetPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TerabitPerSecond, quantity => quantity.ToUnit(BitRateUnit.TerabitPerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TerabytePerSecond, quantity => quantity.ToUnit(BitRateUnit.TerabytePerSecond)); - unitConverter.SetConversionFunction(BitRateUnit.BitPerSecond, BitRateUnit.TeraoctetPerSecond, quantity => quantity.ToUnit(BitRateUnit.TeraoctetPerSecond)); - } - /// /// Get unit abbreviation string. /// @@ -585,7 +567,7 @@ public static string GetAbbreviation(BitRateUnit unit, IFormatProvider? provider /// /// Creates a from . /// - public static BitRate FromBitsPerSecond(double value) + public static BitRate FromBitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.BitPerSecond); } @@ -593,7 +575,7 @@ public static BitRate FromBitsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromBytesPerSecond(double value) + public static BitRate FromBytesPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.BytePerSecond); } @@ -601,7 +583,7 @@ public static BitRate FromBytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromExabitsPerSecond(double value) + public static BitRate FromExabitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.ExabitPerSecond); } @@ -609,7 +591,7 @@ public static BitRate FromExabitsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromExabytesPerSecond(double value) + public static BitRate FromExabytesPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.ExabytePerSecond); } @@ -617,7 +599,7 @@ public static BitRate FromExabytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromExaoctetsPerSecond(double value) + public static BitRate FromExaoctetsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.ExaoctetPerSecond); } @@ -625,7 +607,7 @@ public static BitRate FromExaoctetsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromExbibitsPerSecond(double value) + public static BitRate FromExbibitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.ExbibitPerSecond); } @@ -633,7 +615,7 @@ public static BitRate FromExbibitsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromExbibytesPerSecond(double value) + public static BitRate FromExbibytesPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.ExbibytePerSecond); } @@ -641,7 +623,7 @@ public static BitRate FromExbibytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromExbioctetsPerSecond(double value) + public static BitRate FromExbioctetsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.ExbioctetPerSecond); } @@ -649,7 +631,7 @@ public static BitRate FromExbioctetsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromGibibitsPerSecond(double value) + public static BitRate FromGibibitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.GibibitPerSecond); } @@ -657,7 +639,7 @@ public static BitRate FromGibibitsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromGibibytesPerSecond(double value) + public static BitRate FromGibibytesPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.GibibytePerSecond); } @@ -665,7 +647,7 @@ public static BitRate FromGibibytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromGibioctetsPerSecond(double value) + public static BitRate FromGibioctetsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.GibioctetPerSecond); } @@ -673,7 +655,7 @@ public static BitRate FromGibioctetsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromGigabitsPerSecond(double value) + public static BitRate FromGigabitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.GigabitPerSecond); } @@ -681,7 +663,7 @@ public static BitRate FromGigabitsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromGigabytesPerSecond(double value) + public static BitRate FromGigabytesPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.GigabytePerSecond); } @@ -689,7 +671,7 @@ public static BitRate FromGigabytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromGigaoctetsPerSecond(double value) + public static BitRate FromGigaoctetsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.GigaoctetPerSecond); } @@ -697,7 +679,7 @@ public static BitRate FromGigaoctetsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromKibibitsPerSecond(double value) + public static BitRate FromKibibitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.KibibitPerSecond); } @@ -705,7 +687,7 @@ public static BitRate FromKibibitsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromKibibytesPerSecond(double value) + public static BitRate FromKibibytesPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.KibibytePerSecond); } @@ -713,7 +695,7 @@ public static BitRate FromKibibytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromKibioctetsPerSecond(double value) + public static BitRate FromKibioctetsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.KibioctetPerSecond); } @@ -721,7 +703,7 @@ public static BitRate FromKibioctetsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromKilobitsPerSecond(double value) + public static BitRate FromKilobitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.KilobitPerSecond); } @@ -729,7 +711,7 @@ public static BitRate FromKilobitsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromKilobytesPerSecond(double value) + public static BitRate FromKilobytesPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.KilobytePerSecond); } @@ -737,7 +719,7 @@ public static BitRate FromKilobytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromKilooctetsPerSecond(double value) + public static BitRate FromKilooctetsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.KilooctetPerSecond); } @@ -745,7 +727,7 @@ public static BitRate FromKilooctetsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromMebibitsPerSecond(double value) + public static BitRate FromMebibitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.MebibitPerSecond); } @@ -753,7 +735,7 @@ public static BitRate FromMebibitsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromMebibytesPerSecond(double value) + public static BitRate FromMebibytesPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.MebibytePerSecond); } @@ -761,7 +743,7 @@ public static BitRate FromMebibytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromMebioctetsPerSecond(double value) + public static BitRate FromMebioctetsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.MebioctetPerSecond); } @@ -769,7 +751,7 @@ public static BitRate FromMebioctetsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromMegabitsPerSecond(double value) + public static BitRate FromMegabitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.MegabitPerSecond); } @@ -777,7 +759,7 @@ public static BitRate FromMegabitsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromMegabytesPerSecond(double value) + public static BitRate FromMegabytesPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.MegabytePerSecond); } @@ -785,7 +767,7 @@ public static BitRate FromMegabytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromMegaoctetsPerSecond(double value) + public static BitRate FromMegaoctetsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.MegaoctetPerSecond); } @@ -793,7 +775,7 @@ public static BitRate FromMegaoctetsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromOctetsPerSecond(double value) + public static BitRate FromOctetsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.OctetPerSecond); } @@ -801,7 +783,7 @@ public static BitRate FromOctetsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromPebibitsPerSecond(double value) + public static BitRate FromPebibitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.PebibitPerSecond); } @@ -809,7 +791,7 @@ public static BitRate FromPebibitsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromPebibytesPerSecond(double value) + public static BitRate FromPebibytesPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.PebibytePerSecond); } @@ -817,7 +799,7 @@ public static BitRate FromPebibytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromPebioctetsPerSecond(double value) + public static BitRate FromPebioctetsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.PebioctetPerSecond); } @@ -825,7 +807,7 @@ public static BitRate FromPebioctetsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromPetabitsPerSecond(double value) + public static BitRate FromPetabitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.PetabitPerSecond); } @@ -833,7 +815,7 @@ public static BitRate FromPetabitsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromPetabytesPerSecond(double value) + public static BitRate FromPetabytesPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.PetabytePerSecond); } @@ -841,7 +823,7 @@ public static BitRate FromPetabytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromPetaoctetsPerSecond(double value) + public static BitRate FromPetaoctetsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.PetaoctetPerSecond); } @@ -849,7 +831,7 @@ public static BitRate FromPetaoctetsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromTebibitsPerSecond(double value) + public static BitRate FromTebibitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.TebibitPerSecond); } @@ -857,7 +839,7 @@ public static BitRate FromTebibitsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromTebibytesPerSecond(double value) + public static BitRate FromTebibytesPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.TebibytePerSecond); } @@ -865,7 +847,7 @@ public static BitRate FromTebibytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromTebioctetsPerSecond(double value) + public static BitRate FromTebioctetsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.TebioctetPerSecond); } @@ -873,7 +855,7 @@ public static BitRate FromTebioctetsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromTerabitsPerSecond(double value) + public static BitRate FromTerabitsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.TerabitPerSecond); } @@ -881,7 +863,7 @@ public static BitRate FromTerabitsPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromTerabytesPerSecond(double value) + public static BitRate FromTerabytesPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.TerabytePerSecond); } @@ -889,7 +871,7 @@ public static BitRate FromTerabytesPerSecond(double value) /// /// Creates a from . /// - public static BitRate FromTeraoctetsPerSecond(double value) + public static BitRate FromTeraoctetsPerSecond(QuantityValue value) { return new BitRate(value, BitRateUnit.TeraoctetPerSecond); } @@ -900,7 +882,7 @@ public static BitRate FromTeraoctetsPerSecond(double value) /// Value to convert from. /// Unit to convert from. /// BitRate unit value. - public static BitRate From(double value, BitRateUnit fromUnit) + public static BitRate From(QuantityValue value, BitRateUnit fromUnit) { return new BitRate(value, fromUnit); } @@ -961,10 +943,7 @@ public static BitRate Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static BitRate Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -992,11 +971,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out BitRate result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out BitRate result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -1017,7 +992,7 @@ public static BitRateUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -1028,7 +1003,7 @@ public static BitRateUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out BitRateUnit unit) { return TryParseUnit(str, null, out unit); @@ -1043,7 +1018,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out BitRateUnit /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out BitRateUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -1062,35 +1037,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static BitRate operator +(BitRate left, BitRate right) { - return new BitRate(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new BitRate(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static BitRate operator -(BitRate left, BitRate right) { - return new BitRate(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new BitRate(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static BitRate operator *(double 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, double 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, double 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; } @@ -1102,97 +1077,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(BitRate left, BitRate right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(BitRate left, BitRate right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(BitRate left, BitRate right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(BitRate left, BitRate right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(BitRate other, BitRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(BitRate left, BitRate right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(BitRate other, BitRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(BitRate left, BitRate right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(BitRate other, BitRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is BitRate otherQuantity)) + if (obj is not BitRate otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(BitRate other, BitRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(BitRate other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current BitRate. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(BitRate), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is BitRate otherQuantity)) throw new ArgumentException("Expected type BitRate.", nameof(obj)); + if (obj is not BitRate otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1204,222 +1164,24 @@ public int CompareTo(object? obj) /// public int CompareTo(BitRate other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(BitRateUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this BitRate to another BitRate with the unit representation . - /// - /// The unit to convert to. - /// A BitRate with the specified unit. - public BitRate ToUnit(BitRateUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A BitRate with the specified unit. - public BitRate ToUnit(BitRateUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(BitRate), Unit, typeof(BitRate), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (BitRate)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(BitRateUnit unit, [NotNullWhen(true)] out BitRate? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - BitRate? convertedOrNull = (Unit, unit) switch - { - // BitRateUnit -> BaseUnit - (BitRateUnit.BytePerSecond, BitRateUnit.BitPerSecond) => new BitRate(_value * 8, BitRateUnit.BitPerSecond), - (BitRateUnit.ExabitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1e18d, BitRateUnit.BitPerSecond), - (BitRateUnit.ExabytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * 1e18d, BitRateUnit.BitPerSecond), - (BitRateUnit.ExaoctetPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * 1e18d, BitRateUnit.BitPerSecond), - (BitRateUnit.ExbibitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond), - (BitRateUnit.ExbibytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond), - (BitRateUnit.ExbioctetPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond), - (BitRateUnit.GibibitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * (1024d * 1024 * 1024), BitRateUnit.BitPerSecond), - (BitRateUnit.GibibytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * (1024d * 1024 * 1024), BitRateUnit.BitPerSecond), - (BitRateUnit.GibioctetPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * (1024d * 1024 * 1024), BitRateUnit.BitPerSecond), - (BitRateUnit.GigabitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1e9d, BitRateUnit.BitPerSecond), - (BitRateUnit.GigabytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * 1e9d, BitRateUnit.BitPerSecond), - (BitRateUnit.GigaoctetPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * 1e9d, BitRateUnit.BitPerSecond), - (BitRateUnit.KibibitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1024d, BitRateUnit.BitPerSecond), - (BitRateUnit.KibibytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * 1024d, BitRateUnit.BitPerSecond), - (BitRateUnit.KibioctetPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * 1024d, BitRateUnit.BitPerSecond), - (BitRateUnit.KilobitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1e3d, BitRateUnit.BitPerSecond), - (BitRateUnit.KilobytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * 1e3d, BitRateUnit.BitPerSecond), - (BitRateUnit.KilooctetPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * 1e3d, BitRateUnit.BitPerSecond), - (BitRateUnit.MebibitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * (1024d * 1024), BitRateUnit.BitPerSecond), - (BitRateUnit.MebibytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * (1024d * 1024), BitRateUnit.BitPerSecond), - (BitRateUnit.MebioctetPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * (1024d * 1024), BitRateUnit.BitPerSecond), - (BitRateUnit.MegabitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1e6d, BitRateUnit.BitPerSecond), - (BitRateUnit.MegabytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * 1e6d, BitRateUnit.BitPerSecond), - (BitRateUnit.MegaoctetPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * 1e6d, BitRateUnit.BitPerSecond), - (BitRateUnit.OctetPerSecond, BitRateUnit.BitPerSecond) => new BitRate(_value * 8, BitRateUnit.BitPerSecond), - (BitRateUnit.PebibitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * (1024d * 1024 * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond), - (BitRateUnit.PebibytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * (1024d * 1024 * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond), - (BitRateUnit.PebioctetPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * (1024d * 1024 * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond), - (BitRateUnit.PetabitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1e15d, BitRateUnit.BitPerSecond), - (BitRateUnit.PetabytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * 1e15d, BitRateUnit.BitPerSecond), - (BitRateUnit.PetaoctetPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * 1e15d, BitRateUnit.BitPerSecond), - (BitRateUnit.TebibitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * (1024d * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond), - (BitRateUnit.TebibytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * (1024d * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond), - (BitRateUnit.TebioctetPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * (1024d * 1024 * 1024 * 1024), BitRateUnit.BitPerSecond), - (BitRateUnit.TerabitPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value) * 1e12d, BitRateUnit.BitPerSecond), - (BitRateUnit.TerabytePerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * 1e12d, BitRateUnit.BitPerSecond), - (BitRateUnit.TeraoctetPerSecond, BitRateUnit.BitPerSecond) => new BitRate((_value * 8) * 1e12d, BitRateUnit.BitPerSecond), - - // BaseUnit -> BitRateUnit - (BitRateUnit.BitPerSecond, BitRateUnit.BytePerSecond) => new BitRate(_value / 8, BitRateUnit.BytePerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.ExabitPerSecond) => new BitRate((_value) / 1e18d, BitRateUnit.ExabitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.ExabytePerSecond) => new BitRate((_value / 8) / 1e18d, BitRateUnit.ExabytePerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.ExaoctetPerSecond) => new BitRate((_value / 8) / 1e18d, BitRateUnit.ExaoctetPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.ExbibitPerSecond) => new BitRate((_value) / (1024d * 1024 * 1024 * 1024 * 1024 * 1024), BitRateUnit.ExbibitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.ExbibytePerSecond) => new BitRate((_value / 8) / (1024d * 1024 * 1024 * 1024 * 1024 * 1024), BitRateUnit.ExbibytePerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.ExbioctetPerSecond) => new BitRate((_value / 8) / (1024d * 1024 * 1024 * 1024 * 1024 * 1024), BitRateUnit.ExbioctetPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.GibibitPerSecond) => new BitRate((_value) / (1024d * 1024 * 1024), BitRateUnit.GibibitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.GibibytePerSecond) => new BitRate((_value / 8) / (1024d * 1024 * 1024), BitRateUnit.GibibytePerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.GibioctetPerSecond) => new BitRate((_value / 8) / (1024d * 1024 * 1024), BitRateUnit.GibioctetPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.GigabitPerSecond) => new BitRate((_value) / 1e9d, BitRateUnit.GigabitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.GigabytePerSecond) => new BitRate((_value / 8) / 1e9d, BitRateUnit.GigabytePerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.GigaoctetPerSecond) => new BitRate((_value / 8) / 1e9d, BitRateUnit.GigaoctetPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.KibibitPerSecond) => new BitRate((_value) / 1024d, BitRateUnit.KibibitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.KibibytePerSecond) => new BitRate((_value / 8) / 1024d, BitRateUnit.KibibytePerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.KibioctetPerSecond) => new BitRate((_value / 8) / 1024d, BitRateUnit.KibioctetPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.KilobitPerSecond) => new BitRate((_value) / 1e3d, BitRateUnit.KilobitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.KilobytePerSecond) => new BitRate((_value / 8) / 1e3d, BitRateUnit.KilobytePerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.KilooctetPerSecond) => new BitRate((_value / 8) / 1e3d, BitRateUnit.KilooctetPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.MebibitPerSecond) => new BitRate((_value) / (1024d * 1024), BitRateUnit.MebibitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.MebibytePerSecond) => new BitRate((_value / 8) / (1024d * 1024), BitRateUnit.MebibytePerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.MebioctetPerSecond) => new BitRate((_value / 8) / (1024d * 1024), BitRateUnit.MebioctetPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.MegabitPerSecond) => new BitRate((_value) / 1e6d, BitRateUnit.MegabitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.MegabytePerSecond) => new BitRate((_value / 8) / 1e6d, BitRateUnit.MegabytePerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.MegaoctetPerSecond) => new BitRate((_value / 8) / 1e6d, BitRateUnit.MegaoctetPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.OctetPerSecond) => new BitRate(_value / 8, BitRateUnit.OctetPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.PebibitPerSecond) => new BitRate((_value) / (1024d * 1024 * 1024 * 1024 * 1024), BitRateUnit.PebibitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.PebibytePerSecond) => new BitRate((_value / 8) / (1024d * 1024 * 1024 * 1024 * 1024), BitRateUnit.PebibytePerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.PebioctetPerSecond) => new BitRate((_value / 8) / (1024d * 1024 * 1024 * 1024 * 1024), BitRateUnit.PebioctetPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.PetabitPerSecond) => new BitRate((_value) / 1e15d, BitRateUnit.PetabitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.PetabytePerSecond) => new BitRate((_value / 8) / 1e15d, BitRateUnit.PetabytePerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.PetaoctetPerSecond) => new BitRate((_value / 8) / 1e15d, BitRateUnit.PetaoctetPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.TebibitPerSecond) => new BitRate((_value) / (1024d * 1024 * 1024 * 1024), BitRateUnit.TebibitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.TebibytePerSecond) => new BitRate((_value / 8) / (1024d * 1024 * 1024 * 1024), BitRateUnit.TebibytePerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.TebioctetPerSecond) => new BitRate((_value / 8) / (1024d * 1024 * 1024 * 1024), BitRateUnit.TebioctetPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.TerabitPerSecond) => new BitRate((_value) / 1e12d, BitRateUnit.TerabitPerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.TerabytePerSecond) => new BitRate((_value / 8) / 1e12d, BitRateUnit.TerabytePerSecond), - (BitRateUnit.BitPerSecond, BitRateUnit.TeraoctetPerSecond) => new BitRate((_value / 8) / 1e12d, BitRateUnit.TeraoctetPerSecond), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public BitRate ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not BitRateUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(BitRateUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(BitRateUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(BitRateUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1434,7 +1196,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs index 6a44e29235..ec7aa300a6 100644 --- a/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/BrakeSpecificFuelConsumption.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,12 +33,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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct BrakeSpecificFuelConsumption : IArithmeticQuantity, #if NET7_0_OR_GREATER IMultiplyOperators, - IMultiplyOperators, + IMultiplyOperators, #endif #if NET7_0_OR_GREATER IComparisonOperators, @@ -54,13 +53,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly BrakeSpecificFuelConsumptionUnit? _unit; /// @@ -105,7 +104,7 @@ public static BrakeSpecificFuelConsumptionInfo CreateDefault(Func - /// The for is [T^2][L^-2]. + /// The for is T^2L^-2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 0, 2, 0, 0, 0, 0); @@ -120,17 +119,19 @@ public static BrakeSpecificFuelConsumptionInfo CreateDefault(FuncAn of representing the default unit mappings for BrakeSpecificFuelConsumption. public static IEnumerable> GetDefaultMappings() { - yield return new (BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, "GramPerKiloWattHour", "GramsPerKiloWattHour", BaseUnits.Undefined); + yield return new (BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, "GramPerKiloWattHour", "GramsPerKiloWattHour", BaseUnits.Undefined, + 3600000000 + ); yield return new (BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, "KilogramPerJoule", "KilogramsPerJoule", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)); - yield return new (BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, "PoundPerMechanicalHorsepowerHour", "PoundsPerMechanicalHorsepowerHour", BaseUnits.Undefined); + yield return new (BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, "PoundPerMechanicalHorsepowerHour", "PoundsPerMechanicalHorsepowerHour", BaseUnits.Undefined, + new QuantityValue(191751395532579, 32399455) + ); } } static BrakeSpecificFuelConsumption() { - Info = BrakeSpecificFuelConsumptionInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(BrakeSpecificFuelConsumptionInfo.CreateDefault); } /// @@ -138,7 +139,7 @@ static BrakeSpecificFuelConsumption() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public BrakeSpecificFuelConsumption(double value, BrakeSpecificFuelConsumptionUnit unit) + public BrakeSpecificFuelConsumption(QuantityValue value, BrakeSpecificFuelConsumptionUnit unit) { _value = value; _unit = unit; @@ -152,7 +153,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -163,7 +164,8 @@ public BrakeSpecificFuelConsumption(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -192,10 +194,8 @@ public BrakeSpecificFuelConsumption(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public BrakeSpecificFuelConsumptionUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -234,42 +234,24 @@ public BrakeSpecificFuelConsumption(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerKiloWattHour => As(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); + public QuantityValue GramsPerKiloWattHour => this.As(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerJoule => As(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); + public QuantityValue KilogramsPerJoule => this.As(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerMechanicalHorsepowerHour => As(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); + public QuantityValue PoundsPerMechanicalHorsepowerHour => this.As(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: BrakeSpecificFuelConsumptionUnit -> BaseUnit - unitConverter.SetConversionFunction(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, quantity => quantity.ToUnit(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule)); - unitConverter.SetConversionFunction(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, quantity => quantity.ToUnit(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, quantity => quantity); - - // Register in unit converter: BaseUnit -> BrakeSpecificFuelConsumptionUnit - unitConverter.SetConversionFunction(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, quantity => quantity.ToUnit(BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour)); - unitConverter.SetConversionFunction(BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, quantity => quantity.ToUnit(BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour)); - } - /// /// Get unit abbreviation string. /// @@ -298,7 +280,7 @@ public static string GetAbbreviation(BrakeSpecificFuelConsumptionUnit unit, IFor /// /// Creates a from . /// - public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(double value) + public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(QuantityValue value) { return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour); } @@ -306,7 +288,7 @@ public static BrakeSpecificFuelConsumption FromGramsPerKiloWattHour(double value /// /// Creates a from . /// - public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(double value) + public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(QuantityValue value) { return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule); } @@ -314,7 +296,7 @@ public static BrakeSpecificFuelConsumption FromKilogramsPerJoule(double value) /// /// Creates a from . /// - public static BrakeSpecificFuelConsumption FromPoundsPerMechanicalHorsepowerHour(double value) + public static BrakeSpecificFuelConsumption FromPoundsPerMechanicalHorsepowerHour(QuantityValue value) { return new BrakeSpecificFuelConsumption(value, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour); } @@ -325,7 +307,7 @@ public static BrakeSpecificFuelConsumption FromPoundsPerMechanicalHorsepowerHour /// Value to convert from. /// Unit to convert from. /// BrakeSpecificFuelConsumption unit value. - public static BrakeSpecificFuelConsumption From(double value, BrakeSpecificFuelConsumptionUnit fromUnit) + public static BrakeSpecificFuelConsumption From(QuantityValue value, BrakeSpecificFuelConsumptionUnit fromUnit) { return new BrakeSpecificFuelConsumption(value, fromUnit); } @@ -386,10 +368,7 @@ public static BrakeSpecificFuelConsumption Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static BrakeSpecificFuelConsumption Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -417,11 +396,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out BrakeSpecificFue /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out BrakeSpecificFuelConsumption result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -442,7 +417,7 @@ public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -453,7 +428,7 @@ public static BrakeSpecificFuelConsumptionUnit ParseUnit(string str, IFormatProv return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out BrakeSpecificFuelConsumptionUnit unit) { return TryParseUnit(str, null, out unit); @@ -468,7 +443,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out BrakeSpecifi /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out BrakeSpecificFuelConsumptionUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -487,35 +462,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static BrakeSpecificFuelConsumption operator +(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { - return new BrakeSpecificFuelConsumption(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new BrakeSpecificFuelConsumption(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static BrakeSpecificFuelConsumption operator -(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { - return new BrakeSpecificFuelConsumption(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new BrakeSpecificFuelConsumption(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -530,14 +505,14 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? return MassFlow.FromKilogramsPerSecond(brakeSpecificFuelConsumption.KilogramsPerJoule * power.Watts); } - /// Get from / . - public static SpecificEnergy operator /(double value, BrakeSpecificFuelConsumption brakeSpecificFuelConsumption) + /// Get from / . + public static SpecificEnergy operator /(QuantityValue value, BrakeSpecificFuelConsumption brakeSpecificFuelConsumption) { return SpecificEnergy.FromJoulesPerKilogram(value / brakeSpecificFuelConsumption.KilogramsPerJoule); } - /// Get from * . - public static double operator *(BrakeSpecificFuelConsumption brakeSpecificFuelConsumption, SpecificEnergy specificEnergy) + /// Get from * . + public static QuantityValue operator *(BrakeSpecificFuelConsumption brakeSpecificFuelConsumption, SpecificEnergy specificEnergy) { return brakeSpecificFuelConsumption.KilogramsPerJoule * specificEnergy.JoulesPerKilogram; } @@ -549,97 +524,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(BrakeSpecificFuelConsumption other, BrakeSpecificFuelConsumption tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(BrakeSpecificFuelConsumption other, BrakeSpecificFuelConsumption tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(BrakeSpecificFuelConsumption left, BrakeSpecificFuelConsumption right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(BrakeSpecificFuelConsumption other, BrakeSpecificFuelConsumption tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is BrakeSpecificFuelConsumption otherQuantity)) + if (obj is not BrakeSpecificFuelConsumption otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(BrakeSpecificFuelConsumption other, BrakeSpecificFuelConsumption tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(BrakeSpecificFuelConsumption other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current BrakeSpecificFuelConsumption. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(BrakeSpecificFuelConsumption), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is BrakeSpecificFuelConsumption otherQuantity)) throw new ArgumentException("Expected type BrakeSpecificFuelConsumption.", nameof(obj)); + if (obj is not BrakeSpecificFuelConsumption otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -651,150 +611,24 @@ public int CompareTo(object? obj) /// public int CompareTo(BrakeSpecificFuelConsumption other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(BrakeSpecificFuelConsumptionUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this BrakeSpecificFuelConsumption to another BrakeSpecificFuelConsumption with the unit representation . - /// - /// The unit to convert to. - /// A BrakeSpecificFuelConsumption with the specified unit. - public BrakeSpecificFuelConsumption ToUnit(BrakeSpecificFuelConsumptionUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A BrakeSpecificFuelConsumption with the specified unit. - public BrakeSpecificFuelConsumption ToUnit(BrakeSpecificFuelConsumptionUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(BrakeSpecificFuelConsumption), Unit, typeof(BrakeSpecificFuelConsumption), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (BrakeSpecificFuelConsumption)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(BrakeSpecificFuelConsumptionUnit unit, [NotNullWhen(true)] out BrakeSpecificFuelConsumption? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - BrakeSpecificFuelConsumption? convertedOrNull = (Unit, unit) switch - { - // BrakeSpecificFuelConsumptionUnit -> BaseUnit - (BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule) => new BrakeSpecificFuelConsumption(_value / 3.6e9, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule), - (BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule) => new BrakeSpecificFuelConsumption(_value * (0.45359237 / (76.0402249 * 9.80665))/3600, BrakeSpecificFuelConsumptionUnit.KilogramPerJoule), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> BrakeSpecificFuelConsumptionUnit - (BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour) => new BrakeSpecificFuelConsumption(_value * 3.6e9, BrakeSpecificFuelConsumptionUnit.GramPerKiloWattHour), - (BrakeSpecificFuelConsumptionUnit.KilogramPerJoule, BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour) => new BrakeSpecificFuelConsumption(_value * 3600 / (0.45359237 / (76.0402249 * 9.80665)), BrakeSpecificFuelConsumptionUnit.PoundPerMechanicalHorsepowerHour), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public BrakeSpecificFuelConsumption ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not BrakeSpecificFuelConsumptionUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(BrakeSpecificFuelConsumptionUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is BrakeSpecificFuelConsumptionUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(BrakeSpecificFuelConsumptionUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(BrakeSpecificFuelConsumptionUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(BrakeSpecificFuelConsumptionUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -809,7 +643,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs b/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs index 8f732c9f77..ca79124b2f 100644 --- a/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/CoefficientOfThermalExpansion.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// A unit that represents a fractional change in size in response to a change in temperature. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct CoefficientOfThermalExpansion : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly CoefficientOfThermalExpansionUnit? _unit; /// @@ -104,7 +103,7 @@ public static CoefficientOfThermalExpansionInfo CreateDefault(Func - /// The for is [Θ^-1]. + /// The for is Θ^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 0, 0, -1, 0, 0); @@ -119,20 +118,28 @@ public static CoefficientOfThermalExpansionInfo CreateDefault(FuncAn of representing the default unit mappings for CoefficientOfThermalExpansion. public static IEnumerable> GetDefaultMappings() { - yield return new (CoefficientOfThermalExpansionUnit.PerDegreeCelsius, "PerDegreeCelsius", "PerDegreeCelsius", new BaseUnits(temperature: TemperatureUnit.DegreeCelsius)); - yield return new (CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit, "PerDegreeFahrenheit", "PerDegreeFahrenheit", new BaseUnits(temperature: TemperatureUnit.DegreeFahrenheit)); + yield return new (CoefficientOfThermalExpansionUnit.PerDegreeCelsius, "PerDegreeCelsius", "PerDegreeCelsius", new BaseUnits(temperature: TemperatureUnit.DegreeCelsius), + 1 + ); + yield return new (CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit, "PerDegreeFahrenheit", "PerDegreeFahrenheit", new BaseUnits(temperature: TemperatureUnit.DegreeFahrenheit), + new QuantityValue(5, 9) + ); yield return new (CoefficientOfThermalExpansionUnit.PerKelvin, "PerKelvin", "PerKelvin", new BaseUnits(temperature: TemperatureUnit.Kelvin)); - yield return new (CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius, "PpmPerDegreeCelsius", "PpmPerDegreeCelsius", BaseUnits.Undefined); - yield return new (CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit, "PpmPerDegreeFahrenheit", "PpmPerDegreeFahrenheit", BaseUnits.Undefined); - yield return new (CoefficientOfThermalExpansionUnit.PpmPerKelvin, "PpmPerKelvin", "PpmPerKelvin", BaseUnits.Undefined); + yield return new (CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius, "PpmPerDegreeCelsius", "PpmPerDegreeCelsius", BaseUnits.Undefined, + 1000000 + ); + yield return new (CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit, "PpmPerDegreeFahrenheit", "PpmPerDegreeFahrenheit", BaseUnits.Undefined, + new QuantityValue(5000000, 9) + ); + yield return new (CoefficientOfThermalExpansionUnit.PpmPerKelvin, "PpmPerKelvin", "PpmPerKelvin", BaseUnits.Undefined, + 1000000 + ); } } static CoefficientOfThermalExpansion() { - Info = CoefficientOfThermalExpansionInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(CoefficientOfThermalExpansionInfo.CreateDefault); } /// @@ -140,7 +147,7 @@ static CoefficientOfThermalExpansion() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public CoefficientOfThermalExpansion(double value, CoefficientOfThermalExpansionUnit unit) + public CoefficientOfThermalExpansion(QuantityValue value, CoefficientOfThermalExpansionUnit unit) { _value = value; _unit = unit; @@ -154,7 +161,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -165,7 +172,8 @@ public CoefficientOfThermalExpansion(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -194,10 +202,8 @@ public CoefficientOfThermalExpansion(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public CoefficientOfThermalExpansionUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -236,63 +242,39 @@ public CoefficientOfThermalExpansion(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PerDegreeCelsius => As(CoefficientOfThermalExpansionUnit.PerDegreeCelsius); + public QuantityValue PerDegreeCelsius => this.As(CoefficientOfThermalExpansionUnit.PerDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PerDegreeFahrenheit => As(CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit); + public QuantityValue PerDegreeFahrenheit => this.As(CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PerKelvin => As(CoefficientOfThermalExpansionUnit.PerKelvin); + public QuantityValue PerKelvin => this.As(CoefficientOfThermalExpansionUnit.PerKelvin); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PpmPerDegreeCelsius => As(CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius); + public QuantityValue PpmPerDegreeCelsius => this.As(CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PpmPerDegreeFahrenheit => As(CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit); + public QuantityValue PpmPerDegreeFahrenheit => this.As(CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PpmPerKelvin => As(CoefficientOfThermalExpansionUnit.PpmPerKelvin); + public QuantityValue PpmPerKelvin => this.As(CoefficientOfThermalExpansionUnit.PpmPerKelvin); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: CoefficientOfThermalExpansionUnit -> BaseUnit - unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.PerDegreeCelsius, CoefficientOfThermalExpansionUnit.PerKelvin, quantity => quantity.ToUnit(CoefficientOfThermalExpansionUnit.PerKelvin)); - unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit, CoefficientOfThermalExpansionUnit.PerKelvin, quantity => quantity.ToUnit(CoefficientOfThermalExpansionUnit.PerKelvin)); - unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius, CoefficientOfThermalExpansionUnit.PerKelvin, quantity => quantity.ToUnit(CoefficientOfThermalExpansionUnit.PerKelvin)); - unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit, CoefficientOfThermalExpansionUnit.PerKelvin, quantity => quantity.ToUnit(CoefficientOfThermalExpansionUnit.PerKelvin)); - unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.PpmPerKelvin, CoefficientOfThermalExpansionUnit.PerKelvin, quantity => quantity.ToUnit(CoefficientOfThermalExpansionUnit.PerKelvin)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.PerKelvin, CoefficientOfThermalExpansionUnit.PerKelvin, quantity => quantity); - - // Register in unit converter: BaseUnit -> CoefficientOfThermalExpansionUnit - unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.PerKelvin, CoefficientOfThermalExpansionUnit.PerDegreeCelsius, quantity => quantity.ToUnit(CoefficientOfThermalExpansionUnit.PerDegreeCelsius)); - unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.PerKelvin, CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit, quantity => quantity.ToUnit(CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit)); - unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.PerKelvin, CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius, quantity => quantity.ToUnit(CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius)); - unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.PerKelvin, CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit, quantity => quantity.ToUnit(CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit)); - unitConverter.SetConversionFunction(CoefficientOfThermalExpansionUnit.PerKelvin, CoefficientOfThermalExpansionUnit.PpmPerKelvin, quantity => quantity.ToUnit(CoefficientOfThermalExpansionUnit.PpmPerKelvin)); - } - /// /// Get unit abbreviation string. /// @@ -321,7 +303,7 @@ public static string GetAbbreviation(CoefficientOfThermalExpansionUnit unit, IFo /// /// Creates a from . /// - public static CoefficientOfThermalExpansion FromPerDegreeCelsius(double value) + public static CoefficientOfThermalExpansion FromPerDegreeCelsius(QuantityValue value) { return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.PerDegreeCelsius); } @@ -329,7 +311,7 @@ public static CoefficientOfThermalExpansion FromPerDegreeCelsius(double value) /// /// Creates a from . /// - public static CoefficientOfThermalExpansion FromPerDegreeFahrenheit(double value) + public static CoefficientOfThermalExpansion FromPerDegreeFahrenheit(QuantityValue value) { return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit); } @@ -337,7 +319,7 @@ public static CoefficientOfThermalExpansion FromPerDegreeFahrenheit(double value /// /// Creates a from . /// - public static CoefficientOfThermalExpansion FromPerKelvin(double value) + public static CoefficientOfThermalExpansion FromPerKelvin(QuantityValue value) { return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.PerKelvin); } @@ -345,7 +327,7 @@ public static CoefficientOfThermalExpansion FromPerKelvin(double value) /// /// Creates a from . /// - public static CoefficientOfThermalExpansion FromPpmPerDegreeCelsius(double value) + public static CoefficientOfThermalExpansion FromPpmPerDegreeCelsius(QuantityValue value) { return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius); } @@ -353,7 +335,7 @@ public static CoefficientOfThermalExpansion FromPpmPerDegreeCelsius(double value /// /// Creates a from . /// - public static CoefficientOfThermalExpansion FromPpmPerDegreeFahrenheit(double value) + public static CoefficientOfThermalExpansion FromPpmPerDegreeFahrenheit(QuantityValue value) { return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit); } @@ -361,7 +343,7 @@ public static CoefficientOfThermalExpansion FromPpmPerDegreeFahrenheit(double va /// /// Creates a from . /// - public static CoefficientOfThermalExpansion FromPpmPerKelvin(double value) + public static CoefficientOfThermalExpansion FromPpmPerKelvin(QuantityValue value) { return new CoefficientOfThermalExpansion(value, CoefficientOfThermalExpansionUnit.PpmPerKelvin); } @@ -372,7 +354,7 @@ public static CoefficientOfThermalExpansion FromPpmPerKelvin(double value) /// Value to convert from. /// Unit to convert from. /// CoefficientOfThermalExpansion unit value. - public static CoefficientOfThermalExpansion From(double value, CoefficientOfThermalExpansionUnit fromUnit) + public static CoefficientOfThermalExpansion From(QuantityValue value, CoefficientOfThermalExpansionUnit fromUnit) { return new CoefficientOfThermalExpansion(value, fromUnit); } @@ -433,10 +415,7 @@ public static CoefficientOfThermalExpansion Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static CoefficientOfThermalExpansion Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -464,11 +443,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out CoefficientOfThe /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out CoefficientOfThermalExpansion result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -489,7 +464,7 @@ public static CoefficientOfThermalExpansionUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -500,7 +475,7 @@ public static CoefficientOfThermalExpansionUnit ParseUnit(string str, IFormatPro return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out CoefficientOfThermalExpansionUnit unit) { return TryParseUnit(str, null, out unit); @@ -515,7 +490,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out CoefficientO /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out CoefficientOfThermalExpansionUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -534,35 +509,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static CoefficientOfThermalExpansion operator +(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) { - return new CoefficientOfThermalExpansion(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new CoefficientOfThermalExpansion(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static CoefficientOfThermalExpansion operator -(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) { - return new CoefficientOfThermalExpansion(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new CoefficientOfThermalExpansion(left.Value - right.As(left.Unit), left.Unit); } /// 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.PerKelvin / right.PerKelvin; } @@ -584,97 +559,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(CoefficientOfThermalExpansion other, CoefficientOfThermalExpansion tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(CoefficientOfThermalExpansion other, CoefficientOfThermalExpansion tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(CoefficientOfThermalExpansion left, CoefficientOfThermalExpansion right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(CoefficientOfThermalExpansion other, CoefficientOfThermalExpansion tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is CoefficientOfThermalExpansion otherQuantity)) + if (obj is not CoefficientOfThermalExpansion otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(CoefficientOfThermalExpansion other, CoefficientOfThermalExpansion tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(CoefficientOfThermalExpansion other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current CoefficientOfThermalExpansion. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(CoefficientOfThermalExpansion), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is CoefficientOfThermalExpansion otherQuantity)) throw new ArgumentException("Expected type CoefficientOfThermalExpansion.", nameof(obj)); + if (obj is not CoefficientOfThermalExpansion otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -686,156 +646,24 @@ public int CompareTo(object? obj) /// public int CompareTo(CoefficientOfThermalExpansion other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(CoefficientOfThermalExpansionUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this CoefficientOfThermalExpansion to another CoefficientOfThermalExpansion with the unit representation . - /// - /// The unit to convert to. - /// A CoefficientOfThermalExpansion with the specified unit. - public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A CoefficientOfThermalExpansion with the specified unit. - public CoefficientOfThermalExpansion ToUnit(CoefficientOfThermalExpansionUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(CoefficientOfThermalExpansion), Unit, typeof(CoefficientOfThermalExpansion), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (CoefficientOfThermalExpansion)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(CoefficientOfThermalExpansionUnit unit, [NotNullWhen(true)] out CoefficientOfThermalExpansion? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - CoefficientOfThermalExpansion? convertedOrNull = (Unit, unit) switch - { - // CoefficientOfThermalExpansionUnit -> BaseUnit - (CoefficientOfThermalExpansionUnit.PerDegreeCelsius, CoefficientOfThermalExpansionUnit.PerKelvin) => new CoefficientOfThermalExpansion(_value, CoefficientOfThermalExpansionUnit.PerKelvin), - (CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit, CoefficientOfThermalExpansionUnit.PerKelvin) => new CoefficientOfThermalExpansion(_value * 9 / 5, CoefficientOfThermalExpansionUnit.PerKelvin), - (CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius, CoefficientOfThermalExpansionUnit.PerKelvin) => new CoefficientOfThermalExpansion(_value / 1e6, CoefficientOfThermalExpansionUnit.PerKelvin), - (CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit, CoefficientOfThermalExpansionUnit.PerKelvin) => new CoefficientOfThermalExpansion(_value * 9 / 5e6, CoefficientOfThermalExpansionUnit.PerKelvin), - (CoefficientOfThermalExpansionUnit.PpmPerKelvin, CoefficientOfThermalExpansionUnit.PerKelvin) => new CoefficientOfThermalExpansion(_value / 1e6, CoefficientOfThermalExpansionUnit.PerKelvin), - - // BaseUnit -> CoefficientOfThermalExpansionUnit - (CoefficientOfThermalExpansionUnit.PerKelvin, CoefficientOfThermalExpansionUnit.PerDegreeCelsius) => new CoefficientOfThermalExpansion(_value, CoefficientOfThermalExpansionUnit.PerDegreeCelsius), - (CoefficientOfThermalExpansionUnit.PerKelvin, CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit) => new CoefficientOfThermalExpansion(_value * 5 / 9, CoefficientOfThermalExpansionUnit.PerDegreeFahrenheit), - (CoefficientOfThermalExpansionUnit.PerKelvin, CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius) => new CoefficientOfThermalExpansion(_value * 1e6, CoefficientOfThermalExpansionUnit.PpmPerDegreeCelsius), - (CoefficientOfThermalExpansionUnit.PerKelvin, CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit) => new CoefficientOfThermalExpansion(_value * 5e6 / 9, CoefficientOfThermalExpansionUnit.PpmPerDegreeFahrenheit), - (CoefficientOfThermalExpansionUnit.PerKelvin, CoefficientOfThermalExpansionUnit.PpmPerKelvin) => new CoefficientOfThermalExpansion(_value * 1e6, CoefficientOfThermalExpansionUnit.PpmPerKelvin), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public CoefficientOfThermalExpansion ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not CoefficientOfThermalExpansionUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CoefficientOfThermalExpansionUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(CoefficientOfThermalExpansionUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(CoefficientOfThermalExpansionUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -850,7 +678,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs b/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs index 737627da9a..1e1dde0abb 100644 --- a/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Compressibility.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Compressibility : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly CompressibilityUnit? _unit; /// @@ -101,7 +100,7 @@ public static CompressibilityInfo CreateDefault(Func - /// The for is [T^2][L][M^-1]. + /// The for is T^2LM^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, -1, 2, 0, 0, 0, 0); @@ -116,21 +115,31 @@ public static CompressibilityInfo CreateDefault(FuncAn of representing the default unit mappings for Compressibility. public static IEnumerable> GetDefaultMappings() { - yield return new (CompressibilityUnit.InverseAtmosphere, "InverseAtmosphere", "InverseAtmospheres", BaseUnits.Undefined); - yield return new (CompressibilityUnit.InverseBar, "InverseBar", "InverseBars", BaseUnits.Undefined); - yield return new (CompressibilityUnit.InverseKilopascal, "InverseKilopascal", "InverseKilopascals", BaseUnits.Undefined); - yield return new (CompressibilityUnit.InverseMegapascal, "InverseMegapascal", "InverseMegapascals", BaseUnits.Undefined); - yield return new (CompressibilityUnit.InverseMillibar, "InverseMillibar", "InverseMillibars", BaseUnits.Undefined); + yield return new (CompressibilityUnit.InverseAtmosphere, "InverseAtmosphere", "InverseAtmospheres", BaseUnits.Undefined, + new QuantityValue(1, 101325) + ); + yield return new (CompressibilityUnit.InverseBar, "InverseBar", "InverseBars", BaseUnits.Undefined, + new QuantityValue(1, 100000) + ); + yield return new (CompressibilityUnit.InverseKilopascal, "InverseKilopascal", "InverseKilopascals", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (CompressibilityUnit.InverseMegapascal, "InverseMegapascal", "InverseMegapascals", BaseUnits.Undefined, + new QuantityValue(1, 1000000) + ); + yield return new (CompressibilityUnit.InverseMillibar, "InverseMillibar", "InverseMillibars", BaseUnits.Undefined, + new QuantityValue(1, 100) + ); yield return new (CompressibilityUnit.InversePascal, "InversePascal", "InversePascals", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (CompressibilityUnit.InversePoundForcePerSquareInch, "InversePoundForcePerSquareInch", "InversePoundsForcePerSquareInch", BaseUnits.Undefined); + yield return new (CompressibilityUnit.InversePoundForcePerSquareInch, "InversePoundForcePerSquareInch", "InversePoundsForcePerSquareInch", BaseUnits.Undefined, + new QuantityValue(1000000000000, 6894757293168361) + ); } } static Compressibility() { - Info = CompressibilityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(CompressibilityInfo.CreateDefault); } /// @@ -138,7 +147,7 @@ static Compressibility() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Compressibility(double value, CompressibilityUnit unit) + public Compressibility(QuantityValue value, CompressibilityUnit unit) { _value = value; _unit = unit; @@ -152,7 +161,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -163,7 +172,8 @@ public Compressibility(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -192,10 +202,8 @@ public Compressibility(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public CompressibilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -234,70 +242,44 @@ public Compressibility(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseAtmospheres => As(CompressibilityUnit.InverseAtmosphere); + public QuantityValue InverseAtmospheres => this.As(CompressibilityUnit.InverseAtmosphere); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseBars => As(CompressibilityUnit.InverseBar); + public QuantityValue InverseBars => this.As(CompressibilityUnit.InverseBar); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseKilopascals => As(CompressibilityUnit.InverseKilopascal); + public QuantityValue InverseKilopascals => this.As(CompressibilityUnit.InverseKilopascal); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseMegapascals => As(CompressibilityUnit.InverseMegapascal); + public QuantityValue InverseMegapascals => this.As(CompressibilityUnit.InverseMegapascal); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseMillibars => As(CompressibilityUnit.InverseMillibar); + public QuantityValue InverseMillibars => this.As(CompressibilityUnit.InverseMillibar); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InversePascals => As(CompressibilityUnit.InversePascal); + public QuantityValue InversePascals => this.As(CompressibilityUnit.InversePascal); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InversePoundsForcePerSquareInch => As(CompressibilityUnit.InversePoundForcePerSquareInch); + public QuantityValue InversePoundsForcePerSquareInch => this.As(CompressibilityUnit.InversePoundForcePerSquareInch); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: CompressibilityUnit -> BaseUnit - unitConverter.SetConversionFunction(CompressibilityUnit.InverseAtmosphere, CompressibilityUnit.InversePascal, quantity => quantity.ToUnit(CompressibilityUnit.InversePascal)); - unitConverter.SetConversionFunction(CompressibilityUnit.InverseBar, CompressibilityUnit.InversePascal, quantity => quantity.ToUnit(CompressibilityUnit.InversePascal)); - unitConverter.SetConversionFunction(CompressibilityUnit.InverseKilopascal, CompressibilityUnit.InversePascal, quantity => quantity.ToUnit(CompressibilityUnit.InversePascal)); - unitConverter.SetConversionFunction(CompressibilityUnit.InverseMegapascal, CompressibilityUnit.InversePascal, quantity => quantity.ToUnit(CompressibilityUnit.InversePascal)); - unitConverter.SetConversionFunction(CompressibilityUnit.InverseMillibar, CompressibilityUnit.InversePascal, quantity => quantity.ToUnit(CompressibilityUnit.InversePascal)); - unitConverter.SetConversionFunction(CompressibilityUnit.InversePoundForcePerSquareInch, CompressibilityUnit.InversePascal, quantity => quantity.ToUnit(CompressibilityUnit.InversePascal)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(CompressibilityUnit.InversePascal, CompressibilityUnit.InversePascal, quantity => quantity); - - // Register in unit converter: BaseUnit -> CompressibilityUnit - unitConverter.SetConversionFunction(CompressibilityUnit.InversePascal, CompressibilityUnit.InverseAtmosphere, quantity => quantity.ToUnit(CompressibilityUnit.InverseAtmosphere)); - unitConverter.SetConversionFunction(CompressibilityUnit.InversePascal, CompressibilityUnit.InverseBar, quantity => quantity.ToUnit(CompressibilityUnit.InverseBar)); - unitConverter.SetConversionFunction(CompressibilityUnit.InversePascal, CompressibilityUnit.InverseKilopascal, quantity => quantity.ToUnit(CompressibilityUnit.InverseKilopascal)); - unitConverter.SetConversionFunction(CompressibilityUnit.InversePascal, CompressibilityUnit.InverseMegapascal, quantity => quantity.ToUnit(CompressibilityUnit.InverseMegapascal)); - unitConverter.SetConversionFunction(CompressibilityUnit.InversePascal, CompressibilityUnit.InverseMillibar, quantity => quantity.ToUnit(CompressibilityUnit.InverseMillibar)); - unitConverter.SetConversionFunction(CompressibilityUnit.InversePascal, CompressibilityUnit.InversePoundForcePerSquareInch, quantity => quantity.ToUnit(CompressibilityUnit.InversePoundForcePerSquareInch)); - } - /// /// Get unit abbreviation string. /// @@ -326,7 +308,7 @@ public static string GetAbbreviation(CompressibilityUnit unit, IFormatProvider? /// /// Creates a from . /// - public static Compressibility FromInverseAtmospheres(double value) + public static Compressibility FromInverseAtmospheres(QuantityValue value) { return new Compressibility(value, CompressibilityUnit.InverseAtmosphere); } @@ -334,7 +316,7 @@ public static Compressibility FromInverseAtmospheres(double value) /// /// Creates a from . /// - public static Compressibility FromInverseBars(double value) + public static Compressibility FromInverseBars(QuantityValue value) { return new Compressibility(value, CompressibilityUnit.InverseBar); } @@ -342,7 +324,7 @@ public static Compressibility FromInverseBars(double value) /// /// Creates a from . /// - public static Compressibility FromInverseKilopascals(double value) + public static Compressibility FromInverseKilopascals(QuantityValue value) { return new Compressibility(value, CompressibilityUnit.InverseKilopascal); } @@ -350,7 +332,7 @@ public static Compressibility FromInverseKilopascals(double value) /// /// Creates a from . /// - public static Compressibility FromInverseMegapascals(double value) + public static Compressibility FromInverseMegapascals(QuantityValue value) { return new Compressibility(value, CompressibilityUnit.InverseMegapascal); } @@ -358,7 +340,7 @@ public static Compressibility FromInverseMegapascals(double value) /// /// Creates a from . /// - public static Compressibility FromInverseMillibars(double value) + public static Compressibility FromInverseMillibars(QuantityValue value) { return new Compressibility(value, CompressibilityUnit.InverseMillibar); } @@ -366,7 +348,7 @@ public static Compressibility FromInverseMillibars(double value) /// /// Creates a from . /// - public static Compressibility FromInversePascals(double value) + public static Compressibility FromInversePascals(QuantityValue value) { return new Compressibility(value, CompressibilityUnit.InversePascal); } @@ -374,7 +356,7 @@ public static Compressibility FromInversePascals(double value) /// /// Creates a from . /// - public static Compressibility FromInversePoundsForcePerSquareInch(double value) + public static Compressibility FromInversePoundsForcePerSquareInch(QuantityValue value) { return new Compressibility(value, CompressibilityUnit.InversePoundForcePerSquareInch); } @@ -385,7 +367,7 @@ public static Compressibility FromInversePoundsForcePerSquareInch(double value) /// Value to convert from. /// Unit to convert from. /// Compressibility unit value. - public static Compressibility From(double value, CompressibilityUnit fromUnit) + public static Compressibility From(QuantityValue value, CompressibilityUnit fromUnit) { return new Compressibility(value, fromUnit); } @@ -446,10 +428,7 @@ public static Compressibility Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Compressibility Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -477,11 +456,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Compressibility /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Compressibility result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -502,7 +477,7 @@ public static CompressibilityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -513,7 +488,7 @@ public static CompressibilityUnit ParseUnit(string str, IFormatProvider? provide return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out CompressibilityUnit unit) { return TryParseUnit(str, null, out unit); @@ -528,7 +503,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out Compressibil /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out CompressibilityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -547,35 +522,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Compressibility operator +(Compressibility left, Compressibility right) { - return new Compressibility(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Compressibility(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Compressibility operator -(Compressibility left, Compressibility right) { - return new Compressibility(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Compressibility(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -587,97 +562,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Compressibility left, Compressibility right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Compressibility left, Compressibility right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Compressibility left, Compressibility right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Compressibility left, Compressibility right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Compressibility other, Compressibility tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Compressibility left, Compressibility right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Compressibility other, Compressibility tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Compressibility left, Compressibility right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Compressibility other, Compressibility tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Compressibility otherQuantity)) + if (obj is not Compressibility otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Compressibility other, Compressibility tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Compressibility other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Compressibility. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Compressibility), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Compressibility otherQuantity)) throw new ArgumentException("Expected type Compressibility.", nameof(obj)); + if (obj is not Compressibility otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -689,158 +649,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Compressibility other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(CompressibilityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Compressibility to another Compressibility with the unit representation . - /// - /// The unit to convert to. - /// A Compressibility with the specified unit. - public Compressibility ToUnit(CompressibilityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Compressibility with the specified unit. - public Compressibility ToUnit(CompressibilityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Compressibility), Unit, typeof(Compressibility), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Compressibility)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(CompressibilityUnit unit, [NotNullWhen(true)] out Compressibility? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Compressibility? convertedOrNull = (Unit, unit) switch - { - // CompressibilityUnit -> BaseUnit - (CompressibilityUnit.InverseAtmosphere, CompressibilityUnit.InversePascal) => new Compressibility(_value * 101325, CompressibilityUnit.InversePascal), - (CompressibilityUnit.InverseBar, CompressibilityUnit.InversePascal) => new Compressibility(_value * 1e5, CompressibilityUnit.InversePascal), - (CompressibilityUnit.InverseKilopascal, CompressibilityUnit.InversePascal) => new Compressibility(_value * 1e3, CompressibilityUnit.InversePascal), - (CompressibilityUnit.InverseMegapascal, CompressibilityUnit.InversePascal) => new Compressibility(_value * 1e6, CompressibilityUnit.InversePascal), - (CompressibilityUnit.InverseMillibar, CompressibilityUnit.InversePascal) => new Compressibility(_value * 100, CompressibilityUnit.InversePascal), - (CompressibilityUnit.InversePoundForcePerSquareInch, CompressibilityUnit.InversePascal) => new Compressibility(_value * 6.894757293168361e3, CompressibilityUnit.InversePascal), - - // BaseUnit -> CompressibilityUnit - (CompressibilityUnit.InversePascal, CompressibilityUnit.InverseAtmosphere) => new Compressibility(_value / 101325, CompressibilityUnit.InverseAtmosphere), - (CompressibilityUnit.InversePascal, CompressibilityUnit.InverseBar) => new Compressibility(_value / 1e5, CompressibilityUnit.InverseBar), - (CompressibilityUnit.InversePascal, CompressibilityUnit.InverseKilopascal) => new Compressibility(_value / 1e3, CompressibilityUnit.InverseKilopascal), - (CompressibilityUnit.InversePascal, CompressibilityUnit.InverseMegapascal) => new Compressibility(_value / 1e6, CompressibilityUnit.InverseMegapascal), - (CompressibilityUnit.InversePascal, CompressibilityUnit.InverseMillibar) => new Compressibility(_value / 100, CompressibilityUnit.InverseMillibar), - (CompressibilityUnit.InversePascal, CompressibilityUnit.InversePoundForcePerSquareInch) => new Compressibility(_value / 6.894757293168361e3, CompressibilityUnit.InversePoundForcePerSquareInch), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Compressibility ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not CompressibilityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(CompressibilityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(CompressibilityUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(CompressibilityUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -855,7 +681,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Density.g.cs b/UnitsNet/GeneratedCode/Quantities/Density.g.cs index 69c65a4a4b..3a338ff4c0 100644 --- a/UnitsNet/GeneratedCode/Quantities/Density.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Density.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// http://en.wikipedia.org/wiki/Density /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Density : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -62,13 +61,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly DensityUnit? _unit; /// @@ -113,7 +112,7 @@ public static DensityInfo CreateDefault(Func - /// The for is [L^-3][M]. + /// The for is L^-3M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-3, 1, 0, 0, 0, 0, 0); @@ -128,70 +127,178 @@ public static DensityInfo CreateDefault(FuncAn of representing the default unit mappings for Density. public static IEnumerable> GetDefaultMappings() { - yield return new (DensityUnit.CentigramPerDeciliter, "CentigramPerDeciliter", "CentigramsPerDeciliter", BaseUnits.Undefined); - yield return new (DensityUnit.CentigramPerLiter, "CentigramPerLiter", "CentigramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Centigram)); - yield return new (DensityUnit.CentigramPerMilliliter, "CentigramPerMilliliter", "CentigramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Centigram)); - yield return new (DensityUnit.DecigramPerDeciliter, "DecigramPerDeciliter", "DecigramsPerDeciliter", BaseUnits.Undefined); - yield return new (DensityUnit.DecigramPerLiter, "DecigramPerLiter", "DecigramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Decigram)); - yield return new (DensityUnit.DecigramPerMilliliter, "DecigramPerMilliliter", "DecigramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Decigram)); - yield return new (DensityUnit.FemtogramPerDeciliter, "FemtogramPerDeciliter", "FemtogramsPerDeciliter", BaseUnits.Undefined); - yield return new (DensityUnit.FemtogramPerLiter, "FemtogramPerLiter", "FemtogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Femtogram)); - yield return new (DensityUnit.FemtogramPerMilliliter, "FemtogramPerMilliliter", "FemtogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Femtogram)); - yield return new (DensityUnit.GramPerCubicCentimeter, "GramPerCubicCentimeter", "GramsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram)); - yield return new (DensityUnit.GramPerCubicFoot, "GramPerCubicFoot", "GramsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Gram)); - yield return new (DensityUnit.GramPerCubicInch, "GramPerCubicInch", "GramsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Gram)); - yield return new (DensityUnit.GramPerCubicMeter, "GramPerCubicMeter", "GramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram)); - yield return new (DensityUnit.GramPerCubicMillimeter, "GramPerCubicMillimeter", "GramsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram)); - yield return new (DensityUnit.GramPerDeciliter, "GramPerDeciliter", "GramsPerDeciliter", BaseUnits.Undefined); - yield return new (DensityUnit.GramPerLiter, "GramPerLiter", "GramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Gram)); - yield return new (DensityUnit.GramPerMilliliter, "GramPerMilliliter", "GramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram)); - yield return new (DensityUnit.KilogramPerCubicCentimeter, "KilogramPerCubicCentimeter", "KilogramsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram)); + yield return new (DensityUnit.CentigramPerDeciliter, "CentigramPerDeciliter", "CentigramsPerDeciliter", BaseUnits.Undefined, + 10 + ); + yield return new (DensityUnit.CentigramPerLiter, "CentigramPerLiter", "CentigramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Centigram), + 100 + ); + yield return new (DensityUnit.CentigramPerMilliliter, "CentigramPerMilliliter", "CentigramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Centigram), + new QuantityValue(1, 10) + ); + yield return new (DensityUnit.DecigramPerDeciliter, "DecigramPerDeciliter", "DecigramsPerDeciliter", BaseUnits.Undefined, + 1 + ); + yield return new (DensityUnit.DecigramPerLiter, "DecigramPerLiter", "DecigramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Decigram), + 10 + ); + yield return new (DensityUnit.DecigramPerMilliliter, "DecigramPerMilliliter", "DecigramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Decigram), + new QuantityValue(1, 100) + ); + yield return new (DensityUnit.FemtogramPerDeciliter, "FemtogramPerDeciliter", "FemtogramsPerDeciliter", BaseUnits.Undefined, + 100000000000000 + ); + yield return new (DensityUnit.FemtogramPerLiter, "FemtogramPerLiter", "FemtogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Femtogram), + 1000000000000000 + ); + yield return new (DensityUnit.FemtogramPerMilliliter, "FemtogramPerMilliliter", "FemtogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Femtogram), + 1000000000000 + ); + yield return new (DensityUnit.GramPerCubicCentimeter, "GramPerCubicCentimeter", "GramsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram), + new QuantityValue(1, 1000) + ); + yield return new (DensityUnit.GramPerCubicFoot, "GramPerCubicFoot", "GramsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Gram), + new QuantityValue(55306341, 1953125) + ); + yield return new (DensityUnit.GramPerCubicInch, "GramPerCubicInch", "GramsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Gram), + new QuantityValue(2048383, 125000000) + ); + yield return new (DensityUnit.GramPerCubicMeter, "GramPerCubicMeter", "GramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram), + 1000 + ); + yield return new (DensityUnit.GramPerCubicMillimeter, "GramPerCubicMillimeter", "GramsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram), + new QuantityValue(1, 1000000) + ); + yield return new (DensityUnit.GramPerDeciliter, "GramPerDeciliter", "GramsPerDeciliter", BaseUnits.Undefined, + new QuantityValue(1, 10) + ); + yield return new (DensityUnit.GramPerLiter, "GramPerLiter", "GramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Gram), + 1 + ); + yield return new (DensityUnit.GramPerMilliliter, "GramPerMilliliter", "GramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram), + new QuantityValue(1, 1000) + ); + yield return new (DensityUnit.KilogramPerCubicCentimeter, "KilogramPerCubicCentimeter", "KilogramsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram), + new QuantityValue(1, 1000000) + ); yield return new (DensityUnit.KilogramPerCubicMeter, "KilogramPerCubicMeter", "KilogramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram)); - yield return new (DensityUnit.KilogramPerCubicMillimeter, "KilogramPerCubicMillimeter", "KilogramsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram)); - yield return new (DensityUnit.KilogramPerLiter, "KilogramPerLiter", "KilogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram)); - yield return new (DensityUnit.KilopoundPerCubicFoot, "KilopoundPerCubicFoot", "KilopoundsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Kilopound)); - yield return new (DensityUnit.KilopoundPerCubicInch, "KilopoundPerCubicInch", "KilopoundsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Kilopound)); - yield return new (DensityUnit.KilopoundPerCubicYard, "KilopoundPerCubicYard", "KilopoundsPerCubicYard", new BaseUnits(length: LengthUnit.Yard, mass: MassUnit.Kilopound)); - yield return new (DensityUnit.MicrogramPerCubicMeter, "MicrogramPerCubicMeter", "MicrogramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram)); - yield return new (DensityUnit.MicrogramPerDeciliter, "MicrogramPerDeciliter", "MicrogramsPerDeciliter", BaseUnits.Undefined); - yield return new (DensityUnit.MicrogramPerLiter, "MicrogramPerLiter", "MicrogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Microgram)); - yield return new (DensityUnit.MicrogramPerMilliliter, "MicrogramPerMilliliter", "MicrogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Microgram)); - yield return new (DensityUnit.MilligramPerCubicMeter, "MilligramPerCubicMeter", "MilligramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram)); - yield return new (DensityUnit.MilligramPerDeciliter, "MilligramPerDeciliter", "MilligramsPerDeciliter", BaseUnits.Undefined); - yield return new (DensityUnit.MilligramPerLiter, "MilligramPerLiter", "MilligramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Milligram)); - yield return new (DensityUnit.MilligramPerMilliliter, "MilligramPerMilliliter", "MilligramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Milligram)); - yield return new (DensityUnit.NanogramPerDeciliter, "NanogramPerDeciliter", "NanogramsPerDeciliter", BaseUnits.Undefined); - yield return new (DensityUnit.NanogramPerLiter, "NanogramPerLiter", "NanogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Nanogram)); - yield return new (DensityUnit.NanogramPerMilliliter, "NanogramPerMilliliter", "NanogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Nanogram)); - yield return new (DensityUnit.PicogramPerDeciliter, "PicogramPerDeciliter", "PicogramsPerDeciliter", BaseUnits.Undefined); - yield return new (DensityUnit.PicogramPerLiter, "PicogramPerLiter", "PicogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Picogram)); - yield return new (DensityUnit.PicogramPerMilliliter, "PicogramPerMilliliter", "PicogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Picogram)); - yield return new (DensityUnit.PoundPerCubicCentimeter, "PoundPerCubicCentimeter", "PoundsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Pound)); - yield return new (DensityUnit.PoundPerCubicFoot, "PoundPerCubicFoot", "PoundsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound)); - yield return new (DensityUnit.PoundPerCubicInch, "PoundPerCubicInch", "PoundsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound)); - yield return new (DensityUnit.PoundPerCubicMeter, "PoundPerCubicMeter", "PoundsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Pound)); - yield return new (DensityUnit.PoundPerCubicMillimeter, "PoundPerCubicMillimeter", "PoundsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Pound)); - yield return new (DensityUnit.PoundPerCubicYard, "PoundPerCubicYard", "PoundsPerCubicYard", new BaseUnits(length: LengthUnit.Yard, mass: MassUnit.Pound)); - yield return new (DensityUnit.PoundPerImperialGallon, "PoundPerImperialGallon", "PoundsPerImperialGallon", BaseUnits.Undefined); - yield return new (DensityUnit.PoundPerUSGallon, "PoundPerUSGallon", "PoundsPerUSGallon", BaseUnits.Undefined); - yield return new (DensityUnit.SlugPerCubicCentimeter, "SlugPerCubicCentimeter", "SlugsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Slug)); - yield return new (DensityUnit.SlugPerCubicFoot, "SlugPerCubicFoot", "SlugsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Slug)); - yield return new (DensityUnit.SlugPerCubicInch, "SlugPerCubicInch", "SlugsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Slug)); - yield return new (DensityUnit.SlugPerCubicMeter, "SlugPerCubicMeter", "SlugsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Slug)); - yield return new (DensityUnit.SlugPerCubicMillimeter, "SlugPerCubicMillimeter", "SlugsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Slug)); - yield return new (DensityUnit.TonnePerCubicCentimeter, "TonnePerCubicCentimeter", "TonnesPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Tonne)); - yield return new (DensityUnit.TonnePerCubicFoot, "TonnePerCubicFoot", "TonnesPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Tonne)); - yield return new (DensityUnit.TonnePerCubicInch, "TonnePerCubicInch", "TonnesPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Tonne)); - yield return new (DensityUnit.TonnePerCubicMeter, "TonnePerCubicMeter", "TonnesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Tonne)); - yield return new (DensityUnit.TonnePerCubicMillimeter, "TonnePerCubicMillimeter", "TonnesPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Tonne)); + yield return new (DensityUnit.KilogramPerCubicMillimeter, "KilogramPerCubicMillimeter", "KilogramsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram), + new QuantityValue(1, 1000000000) + ); + yield return new (DensityUnit.KilogramPerLiter, "KilogramPerLiter", "KilogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram), + new QuantityValue(1, 1000) + ); + yield return new (DensityUnit.KilopoundPerCubicFoot, "KilopoundPerCubicFoot", "KilopoundsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Kilopound), + new QuantityValue(221225364, 3543690390625) + ); + yield return new (DensityUnit.KilopoundPerCubicInch, "KilopoundPerCubicInch", "KilopoundsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Kilopound), + new QuantityValue(2048383, 56699046250000) + ); + yield return new (DensityUnit.KilopoundPerCubicYard, "KilopoundPerCubicYard", "KilopoundsPerCubicYard", new BaseUnits(length: LengthUnit.Yard, mass: MassUnit.Kilopound), + new QuantityValue(5973084828, 3543690390625) + ); + yield return new (DensityUnit.MicrogramPerCubicMeter, "MicrogramPerCubicMeter", "MicrogramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram), + 1000000000 + ); + yield return new (DensityUnit.MicrogramPerDeciliter, "MicrogramPerDeciliter", "MicrogramsPerDeciliter", BaseUnits.Undefined, + 100000 + ); + yield return new (DensityUnit.MicrogramPerLiter, "MicrogramPerLiter", "MicrogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Microgram), + 1000000 + ); + yield return new (DensityUnit.MicrogramPerMilliliter, "MicrogramPerMilliliter", "MicrogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Microgram), + 1000 + ); + yield return new (DensityUnit.MilligramPerCubicMeter, "MilligramPerCubicMeter", "MilligramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram), + 1000000 + ); + yield return new (DensityUnit.MilligramPerDeciliter, "MilligramPerDeciliter", "MilligramsPerDeciliter", BaseUnits.Undefined, + 100 + ); + yield return new (DensityUnit.MilligramPerLiter, "MilligramPerLiter", "MilligramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Milligram), + 1000 + ); + yield return new (DensityUnit.MilligramPerMilliliter, "MilligramPerMilliliter", "MilligramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Milligram), + 1 + ); + yield return new (DensityUnit.NanogramPerDeciliter, "NanogramPerDeciliter", "NanogramsPerDeciliter", BaseUnits.Undefined, + 100000000 + ); + yield return new (DensityUnit.NanogramPerLiter, "NanogramPerLiter", "NanogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Nanogram), + 1000000000 + ); + yield return new (DensityUnit.NanogramPerMilliliter, "NanogramPerMilliliter", "NanogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Nanogram), + 1000000 + ); + yield return new (DensityUnit.PicogramPerDeciliter, "PicogramPerDeciliter", "PicogramsPerDeciliter", BaseUnits.Undefined, + 100000000000 + ); + yield return new (DensityUnit.PicogramPerLiter, "PicogramPerLiter", "PicogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Picogram), + 1000000000000 + ); + yield return new (DensityUnit.PicogramPerMilliliter, "PicogramPerMilliliter", "PicogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Picogram), + 1000000000 + ); + yield return new (DensityUnit.PoundPerCubicCentimeter, "PoundPerCubicCentimeter", "PoundsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Pound), + new QuantityValue(100, 45359237) + ); + yield return new (DensityUnit.PoundPerCubicFoot, "PoundPerCubicFoot", "PoundsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound), + new QuantityValue(1769802912, 28349523125) + ); + yield return new (DensityUnit.PoundPerCubicInch, "PoundPerCubicInch", "PoundsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound), + new QuantityValue(2048383, 56699046250) + ); + yield return new (DensityUnit.PoundPerCubicMeter, "PoundPerCubicMeter", "PoundsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Pound), + new QuantityValue(100000000, 45359237) + ); + yield return new (DensityUnit.PoundPerCubicMillimeter, "PoundPerCubicMillimeter", "PoundsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Pound), + new QuantityValue(1, 453592370) + ); + yield return new (DensityUnit.PoundPerCubicYard, "PoundPerCubicYard", "PoundsPerCubicYard", new BaseUnits(length: LengthUnit.Yard, mass: MassUnit.Pound), + new QuantityValue(47784678624, 28349523125) + ); + yield return new (DensityUnit.PoundPerImperialGallon, "PoundPerImperialGallon", "PoundsPerImperialGallon", BaseUnits.Undefined, + new QuantityValue(454609, 45359237) + ); + yield return new (DensityUnit.PoundPerUSGallon, "PoundPerUSGallon", "PoundsPerUSGallon", BaseUnits.Undefined, + new QuantityValue(6145149, 736351250) + ); + yield return new (DensityUnit.SlugPerCubicCentimeter, "SlugPerCubicCentimeter", "SlugsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Slug), + new QuantityValue(609600, 8896443230521) + ); + yield return new (DensityUnit.SlugPerCubicFoot, "SlugPerCubicFoot", "SlugsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Slug), + new QuantityValue(10788718551552, 5560277019075625) + ); + yield return new (DensityUnit.SlugPerCubicInch, "SlugPerCubicInch", "SlugsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Slug), + new QuantityValue(6243471384, 5560277019075625) + ); + yield return new (DensityUnit.SlugPerCubicMeter, "SlugPerCubicMeter", "SlugsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Slug), + new QuantityValue(609600000000, 8896443230521) + ); + yield return new (DensityUnit.SlugPerCubicMillimeter, "SlugPerCubicMillimeter", "SlugsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Slug), + new QuantityValue(3048, 44482216152605) + ); + yield return new (DensityUnit.TonnePerCubicCentimeter, "TonnePerCubicCentimeter", "TonnesPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Tonne), + new QuantityValue(1, 1000000000) + ); + yield return new (DensityUnit.TonnePerCubicFoot, "TonnePerCubicFoot", "TonnesPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Tonne), + new QuantityValue(55306341, 1953125000000) + ); + yield return new (DensityUnit.TonnePerCubicInch, "TonnePerCubicInch", "TonnesPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Tonne), + new QuantityValue(2048383, 125000000000000) + ); + yield return new (DensityUnit.TonnePerCubicMeter, "TonnePerCubicMeter", "TonnesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Tonne), + new QuantityValue(1, 1000) + ); + yield return new (DensityUnit.TonnePerCubicMillimeter, "TonnePerCubicMillimeter", "TonnesPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Tonne), + new QuantityValue(1, 1000000000000) + ); } } static Density() { - Info = DensityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(DensityInfo.CreateDefault); } /// @@ -199,7 +306,7 @@ static Density() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Density(double value, DensityUnit unit) + public Density(QuantityValue value, DensityUnit unit) { _value = value; _unit = unit; @@ -213,7 +320,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -224,7 +331,8 @@ public Density(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -253,10 +361,8 @@ public Density(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public DensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -295,413 +401,289 @@ public Density(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentigramsPerDeciliter => As(DensityUnit.CentigramPerDeciliter); + public QuantityValue CentigramsPerDeciliter => this.As(DensityUnit.CentigramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentigramsPerLiter => As(DensityUnit.CentigramPerLiter); + public QuantityValue CentigramsPerLiter => this.As(DensityUnit.CentigramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentigramsPerMilliliter => As(DensityUnit.CentigramPerMilliliter); + public QuantityValue CentigramsPerMilliliter => this.As(DensityUnit.CentigramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecigramsPerDeciliter => As(DensityUnit.DecigramPerDeciliter); + public QuantityValue DecigramsPerDeciliter => this.As(DensityUnit.DecigramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecigramsPerLiter => As(DensityUnit.DecigramPerLiter); + public QuantityValue DecigramsPerLiter => this.As(DensityUnit.DecigramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecigramsPerMilliliter => As(DensityUnit.DecigramPerMilliliter); + public QuantityValue DecigramsPerMilliliter => this.As(DensityUnit.DecigramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double FemtogramsPerDeciliter => As(DensityUnit.FemtogramPerDeciliter); + public QuantityValue FemtogramsPerDeciliter => this.As(DensityUnit.FemtogramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double FemtogramsPerLiter => As(DensityUnit.FemtogramPerLiter); + public QuantityValue FemtogramsPerLiter => this.As(DensityUnit.FemtogramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double FemtogramsPerMilliliter => As(DensityUnit.FemtogramPerMilliliter); + public QuantityValue FemtogramsPerMilliliter => this.As(DensityUnit.FemtogramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerCubicCentimeter => As(DensityUnit.GramPerCubicCentimeter); + public QuantityValue GramsPerCubicCentimeter => this.As(DensityUnit.GramPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerCubicFoot => As(DensityUnit.GramPerCubicFoot); + public QuantityValue GramsPerCubicFoot => this.As(DensityUnit.GramPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerCubicInch => As(DensityUnit.GramPerCubicInch); + public QuantityValue GramsPerCubicInch => this.As(DensityUnit.GramPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerCubicMeter => As(DensityUnit.GramPerCubicMeter); + public QuantityValue GramsPerCubicMeter => this.As(DensityUnit.GramPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerCubicMillimeter => As(DensityUnit.GramPerCubicMillimeter); + public QuantityValue GramsPerCubicMillimeter => this.As(DensityUnit.GramPerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerDeciliter => As(DensityUnit.GramPerDeciliter); + public QuantityValue GramsPerDeciliter => this.As(DensityUnit.GramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerLiter => As(DensityUnit.GramPerLiter); + public QuantityValue GramsPerLiter => this.As(DensityUnit.GramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerMilliliter => As(DensityUnit.GramPerMilliliter); + public QuantityValue GramsPerMilliliter => this.As(DensityUnit.GramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerCubicCentimeter => As(DensityUnit.KilogramPerCubicCentimeter); + public QuantityValue KilogramsPerCubicCentimeter => this.As(DensityUnit.KilogramPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerCubicMeter => As(DensityUnit.KilogramPerCubicMeter); + public QuantityValue KilogramsPerCubicMeter => this.As(DensityUnit.KilogramPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerCubicMillimeter => As(DensityUnit.KilogramPerCubicMillimeter); + public QuantityValue KilogramsPerCubicMillimeter => this.As(DensityUnit.KilogramPerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerLiter => As(DensityUnit.KilogramPerLiter); + public QuantityValue KilogramsPerLiter => this.As(DensityUnit.KilogramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsPerCubicFoot => As(DensityUnit.KilopoundPerCubicFoot); + public QuantityValue KilopoundsPerCubicFoot => this.As(DensityUnit.KilopoundPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsPerCubicInch => As(DensityUnit.KilopoundPerCubicInch); + public QuantityValue KilopoundsPerCubicInch => this.As(DensityUnit.KilopoundPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsPerCubicYard => As(DensityUnit.KilopoundPerCubicYard); + public QuantityValue KilopoundsPerCubicYard => this.As(DensityUnit.KilopoundPerCubicYard); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerCubicMeter => As(DensityUnit.MicrogramPerCubicMeter); + public QuantityValue MicrogramsPerCubicMeter => this.As(DensityUnit.MicrogramPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerDeciliter => As(DensityUnit.MicrogramPerDeciliter); + public QuantityValue MicrogramsPerDeciliter => this.As(DensityUnit.MicrogramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerLiter => As(DensityUnit.MicrogramPerLiter); + public QuantityValue MicrogramsPerLiter => this.As(DensityUnit.MicrogramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerMilliliter => As(DensityUnit.MicrogramPerMilliliter); + public QuantityValue MicrogramsPerMilliliter => this.As(DensityUnit.MicrogramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerCubicMeter => As(DensityUnit.MilligramPerCubicMeter); + public QuantityValue MilligramsPerCubicMeter => this.As(DensityUnit.MilligramPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerDeciliter => As(DensityUnit.MilligramPerDeciliter); + public QuantityValue MilligramsPerDeciliter => this.As(DensityUnit.MilligramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerLiter => As(DensityUnit.MilligramPerLiter); + public QuantityValue MilligramsPerLiter => this.As(DensityUnit.MilligramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerMilliliter => As(DensityUnit.MilligramPerMilliliter); + public QuantityValue MilligramsPerMilliliter => this.As(DensityUnit.MilligramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanogramsPerDeciliter => As(DensityUnit.NanogramPerDeciliter); + public QuantityValue NanogramsPerDeciliter => this.As(DensityUnit.NanogramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanogramsPerLiter => As(DensityUnit.NanogramPerLiter); + public QuantityValue NanogramsPerLiter => this.As(DensityUnit.NanogramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanogramsPerMilliliter => As(DensityUnit.NanogramPerMilliliter); + public QuantityValue NanogramsPerMilliliter => this.As(DensityUnit.NanogramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicogramsPerDeciliter => As(DensityUnit.PicogramPerDeciliter); + public QuantityValue PicogramsPerDeciliter => this.As(DensityUnit.PicogramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicogramsPerLiter => As(DensityUnit.PicogramPerLiter); + public QuantityValue PicogramsPerLiter => this.As(DensityUnit.PicogramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicogramsPerMilliliter => As(DensityUnit.PicogramPerMilliliter); + public QuantityValue PicogramsPerMilliliter => this.As(DensityUnit.PicogramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerCubicCentimeter => As(DensityUnit.PoundPerCubicCentimeter); + public QuantityValue PoundsPerCubicCentimeter => this.As(DensityUnit.PoundPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerCubicFoot => As(DensityUnit.PoundPerCubicFoot); + public QuantityValue PoundsPerCubicFoot => this.As(DensityUnit.PoundPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerCubicInch => As(DensityUnit.PoundPerCubicInch); + public QuantityValue PoundsPerCubicInch => this.As(DensityUnit.PoundPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerCubicMeter => As(DensityUnit.PoundPerCubicMeter); + public QuantityValue PoundsPerCubicMeter => this.As(DensityUnit.PoundPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerCubicMillimeter => As(DensityUnit.PoundPerCubicMillimeter); + public QuantityValue PoundsPerCubicMillimeter => this.As(DensityUnit.PoundPerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerCubicYard => As(DensityUnit.PoundPerCubicYard); + public QuantityValue PoundsPerCubicYard => this.As(DensityUnit.PoundPerCubicYard); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerImperialGallon => As(DensityUnit.PoundPerImperialGallon); + public QuantityValue PoundsPerImperialGallon => this.As(DensityUnit.PoundPerImperialGallon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerUSGallon => As(DensityUnit.PoundPerUSGallon); + public QuantityValue PoundsPerUSGallon => this.As(DensityUnit.PoundPerUSGallon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SlugsPerCubicCentimeter => As(DensityUnit.SlugPerCubicCentimeter); + public QuantityValue SlugsPerCubicCentimeter => this.As(DensityUnit.SlugPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SlugsPerCubicFoot => As(DensityUnit.SlugPerCubicFoot); + public QuantityValue SlugsPerCubicFoot => this.As(DensityUnit.SlugPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SlugsPerCubicInch => As(DensityUnit.SlugPerCubicInch); + public QuantityValue SlugsPerCubicInch => this.As(DensityUnit.SlugPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SlugsPerCubicMeter => As(DensityUnit.SlugPerCubicMeter); + public QuantityValue SlugsPerCubicMeter => this.As(DensityUnit.SlugPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SlugsPerCubicMillimeter => As(DensityUnit.SlugPerCubicMillimeter); + public QuantityValue SlugsPerCubicMillimeter => this.As(DensityUnit.SlugPerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesPerCubicCentimeter => As(DensityUnit.TonnePerCubicCentimeter); + public QuantityValue TonnesPerCubicCentimeter => this.As(DensityUnit.TonnePerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesPerCubicFoot => As(DensityUnit.TonnePerCubicFoot); + public QuantityValue TonnesPerCubicFoot => this.As(DensityUnit.TonnePerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesPerCubicInch => As(DensityUnit.TonnePerCubicInch); + public QuantityValue TonnesPerCubicInch => this.As(DensityUnit.TonnePerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesPerCubicMeter => As(DensityUnit.TonnePerCubicMeter); + public QuantityValue TonnesPerCubicMeter => this.As(DensityUnit.TonnePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesPerCubicMillimeter => As(DensityUnit.TonnePerCubicMillimeter); + public QuantityValue TonnesPerCubicMillimeter => this.As(DensityUnit.TonnePerCubicMillimeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: DensityUnit -> BaseUnit - unitConverter.SetConversionFunction(DensityUnit.CentigramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.CentigramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.CentigramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.DecigramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.DecigramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.DecigramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.FemtogramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.FemtogramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.FemtogramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.GramPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.GramPerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.GramPerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.GramPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.GramPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.GramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.GramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.GramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilopoundPerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilopoundPerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilopoundPerCubicYard, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.MicrogramPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.MicrogramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.MicrogramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.MicrogramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.MilligramPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.MilligramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.MilligramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.MilligramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.NanogramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.NanogramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.NanogramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.PicogramPerDeciliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.PicogramPerLiter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.PicogramPerMilliliter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.PoundPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.PoundPerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.PoundPerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.PoundPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.PoundPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.PoundPerCubicYard, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.PoundPerImperialGallon, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.PoundPerUSGallon, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.SlugPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.SlugPerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.SlugPerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.SlugPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.SlugPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.TonnePerCubicCentimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.TonnePerCubicFoot, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.TonnePerCubicInch, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.TonnePerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.TonnePerCubicMillimeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> DensityUnit - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.CentigramPerDeciliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerLiter, quantity => quantity.ToUnit(DensityUnit.CentigramPerLiter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.CentigramPerMilliliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.DecigramPerDeciliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerLiter, quantity => quantity.ToUnit(DensityUnit.DecigramPerLiter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.DecigramPerMilliliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.FemtogramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.FemtogramPerDeciliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.FemtogramPerLiter, quantity => quantity.ToUnit(DensityUnit.FemtogramPerLiter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.FemtogramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.FemtogramPerMilliliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicCentimeter, quantity => quantity.ToUnit(DensityUnit.GramPerCubicCentimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicFoot, quantity => quantity.ToUnit(DensityUnit.GramPerCubicFoot)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicInch, quantity => quantity.ToUnit(DensityUnit.GramPerCubicInch)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.GramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicMillimeter, quantity => quantity.ToUnit(DensityUnit.GramPerCubicMillimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.GramPerDeciliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerLiter, quantity => quantity.ToUnit(DensityUnit.GramPerLiter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.GramPerMilliliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicCentimeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicCentimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicMillimeter, quantity => quantity.ToUnit(DensityUnit.KilogramPerCubicMillimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerLiter, quantity => quantity.ToUnit(DensityUnit.KilogramPerLiter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilopoundPerCubicFoot, quantity => quantity.ToUnit(DensityUnit.KilopoundPerCubicFoot)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilopoundPerCubicInch, quantity => quantity.ToUnit(DensityUnit.KilopoundPerCubicInch)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.KilopoundPerCubicYard, quantity => quantity.ToUnit(DensityUnit.KilopoundPerCubicYard)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.MicrogramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.MicrogramPerDeciliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerLiter, quantity => quantity.ToUnit(DensityUnit.MicrogramPerLiter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.MicrogramPerMilliliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.MilligramPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.MilligramPerDeciliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerLiter, quantity => quantity.ToUnit(DensityUnit.MilligramPerLiter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.MilligramPerMilliliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.NanogramPerDeciliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerLiter, quantity => quantity.ToUnit(DensityUnit.NanogramPerLiter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.NanogramPerMilliliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerDeciliter, quantity => quantity.ToUnit(DensityUnit.PicogramPerDeciliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerLiter, quantity => quantity.ToUnit(DensityUnit.PicogramPerLiter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerMilliliter, quantity => quantity.ToUnit(DensityUnit.PicogramPerMilliliter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicCentimeter, quantity => quantity.ToUnit(DensityUnit.PoundPerCubicCentimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicFoot, quantity => quantity.ToUnit(DensityUnit.PoundPerCubicFoot)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicInch, quantity => quantity.ToUnit(DensityUnit.PoundPerCubicInch)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.PoundPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicMillimeter, quantity => quantity.ToUnit(DensityUnit.PoundPerCubicMillimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicYard, quantity => quantity.ToUnit(DensityUnit.PoundPerCubicYard)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerImperialGallon, quantity => quantity.ToUnit(DensityUnit.PoundPerImperialGallon)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerUSGallon, quantity => quantity.ToUnit(DensityUnit.PoundPerUSGallon)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicCentimeter, quantity => quantity.ToUnit(DensityUnit.SlugPerCubicCentimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicFoot, quantity => quantity.ToUnit(DensityUnit.SlugPerCubicFoot)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicInch, quantity => quantity.ToUnit(DensityUnit.SlugPerCubicInch)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicMeter, quantity => quantity.ToUnit(DensityUnit.SlugPerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicMillimeter, quantity => quantity.ToUnit(DensityUnit.SlugPerCubicMillimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicCentimeter, quantity => quantity.ToUnit(DensityUnit.TonnePerCubicCentimeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicFoot, quantity => quantity.ToUnit(DensityUnit.TonnePerCubicFoot)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicInch, quantity => quantity.ToUnit(DensityUnit.TonnePerCubicInch)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicMeter, quantity => quantity.ToUnit(DensityUnit.TonnePerCubicMeter)); - unitConverter.SetConversionFunction(DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicMillimeter, quantity => quantity.ToUnit(DensityUnit.TonnePerCubicMillimeter)); - } - /// /// Get unit abbreviation string. /// @@ -730,7 +712,7 @@ public static string GetAbbreviation(DensityUnit unit, IFormatProvider? provider /// /// Creates a from . /// - public static Density FromCentigramsPerDeciliter(double value) + public static Density FromCentigramsPerDeciliter(QuantityValue value) { return new Density(value, DensityUnit.CentigramPerDeciliter); } @@ -738,7 +720,7 @@ public static Density FromCentigramsPerDeciliter(double value) /// /// Creates a from . /// - public static Density FromCentigramsPerLiter(double value) + public static Density FromCentigramsPerLiter(QuantityValue value) { return new Density(value, DensityUnit.CentigramPerLiter); } @@ -746,7 +728,7 @@ public static Density FromCentigramsPerLiter(double value) /// /// Creates a from . /// - public static Density FromCentigramsPerMilliliter(double value) + public static Density FromCentigramsPerMilliliter(QuantityValue value) { return new Density(value, DensityUnit.CentigramPerMilliliter); } @@ -754,7 +736,7 @@ public static Density FromCentigramsPerMilliliter(double value) /// /// Creates a from . /// - public static Density FromDecigramsPerDeciliter(double value) + public static Density FromDecigramsPerDeciliter(QuantityValue value) { return new Density(value, DensityUnit.DecigramPerDeciliter); } @@ -762,7 +744,7 @@ public static Density FromDecigramsPerDeciliter(double value) /// /// Creates a from . /// - public static Density FromDecigramsPerLiter(double value) + public static Density FromDecigramsPerLiter(QuantityValue value) { return new Density(value, DensityUnit.DecigramPerLiter); } @@ -770,7 +752,7 @@ public static Density FromDecigramsPerLiter(double value) /// /// Creates a from . /// - public static Density FromDecigramsPerMilliliter(double value) + public static Density FromDecigramsPerMilliliter(QuantityValue value) { return new Density(value, DensityUnit.DecigramPerMilliliter); } @@ -778,7 +760,7 @@ public static Density FromDecigramsPerMilliliter(double value) /// /// Creates a from . /// - public static Density FromFemtogramsPerDeciliter(double value) + public static Density FromFemtogramsPerDeciliter(QuantityValue value) { return new Density(value, DensityUnit.FemtogramPerDeciliter); } @@ -786,7 +768,7 @@ public static Density FromFemtogramsPerDeciliter(double value) /// /// Creates a from . /// - public static Density FromFemtogramsPerLiter(double value) + public static Density FromFemtogramsPerLiter(QuantityValue value) { return new Density(value, DensityUnit.FemtogramPerLiter); } @@ -794,7 +776,7 @@ public static Density FromFemtogramsPerLiter(double value) /// /// Creates a from . /// - public static Density FromFemtogramsPerMilliliter(double value) + public static Density FromFemtogramsPerMilliliter(QuantityValue value) { return new Density(value, DensityUnit.FemtogramPerMilliliter); } @@ -802,7 +784,7 @@ public static Density FromFemtogramsPerMilliliter(double value) /// /// Creates a from . /// - public static Density FromGramsPerCubicCentimeter(double value) + public static Density FromGramsPerCubicCentimeter(QuantityValue value) { return new Density(value, DensityUnit.GramPerCubicCentimeter); } @@ -810,7 +792,7 @@ public static Density FromGramsPerCubicCentimeter(double value) /// /// Creates a from . /// - public static Density FromGramsPerCubicFoot(double value) + public static Density FromGramsPerCubicFoot(QuantityValue value) { return new Density(value, DensityUnit.GramPerCubicFoot); } @@ -818,7 +800,7 @@ public static Density FromGramsPerCubicFoot(double value) /// /// Creates a from . /// - public static Density FromGramsPerCubicInch(double value) + public static Density FromGramsPerCubicInch(QuantityValue value) { return new Density(value, DensityUnit.GramPerCubicInch); } @@ -826,7 +808,7 @@ public static Density FromGramsPerCubicInch(double value) /// /// Creates a from . /// - public static Density FromGramsPerCubicMeter(double value) + public static Density FromGramsPerCubicMeter(QuantityValue value) { return new Density(value, DensityUnit.GramPerCubicMeter); } @@ -834,7 +816,7 @@ public static Density FromGramsPerCubicMeter(double value) /// /// Creates a from . /// - public static Density FromGramsPerCubicMillimeter(double value) + public static Density FromGramsPerCubicMillimeter(QuantityValue value) { return new Density(value, DensityUnit.GramPerCubicMillimeter); } @@ -842,7 +824,7 @@ public static Density FromGramsPerCubicMillimeter(double value) /// /// Creates a from . /// - public static Density FromGramsPerDeciliter(double value) + public static Density FromGramsPerDeciliter(QuantityValue value) { return new Density(value, DensityUnit.GramPerDeciliter); } @@ -850,7 +832,7 @@ public static Density FromGramsPerDeciliter(double value) /// /// Creates a from . /// - public static Density FromGramsPerLiter(double value) + public static Density FromGramsPerLiter(QuantityValue value) { return new Density(value, DensityUnit.GramPerLiter); } @@ -858,7 +840,7 @@ public static Density FromGramsPerLiter(double value) /// /// Creates a from . /// - public static Density FromGramsPerMilliliter(double value) + public static Density FromGramsPerMilliliter(QuantityValue value) { return new Density(value, DensityUnit.GramPerMilliliter); } @@ -866,7 +848,7 @@ public static Density FromGramsPerMilliliter(double value) /// /// Creates a from . /// - public static Density FromKilogramsPerCubicCentimeter(double value) + public static Density FromKilogramsPerCubicCentimeter(QuantityValue value) { return new Density(value, DensityUnit.KilogramPerCubicCentimeter); } @@ -874,7 +856,7 @@ public static Density FromKilogramsPerCubicCentimeter(double value) /// /// Creates a from . /// - public static Density FromKilogramsPerCubicMeter(double value) + public static Density FromKilogramsPerCubicMeter(QuantityValue value) { return new Density(value, DensityUnit.KilogramPerCubicMeter); } @@ -882,7 +864,7 @@ public static Density FromKilogramsPerCubicMeter(double value) /// /// Creates a from . /// - public static Density FromKilogramsPerCubicMillimeter(double value) + public static Density FromKilogramsPerCubicMillimeter(QuantityValue value) { return new Density(value, DensityUnit.KilogramPerCubicMillimeter); } @@ -890,7 +872,7 @@ public static Density FromKilogramsPerCubicMillimeter(double value) /// /// Creates a from . /// - public static Density FromKilogramsPerLiter(double value) + public static Density FromKilogramsPerLiter(QuantityValue value) { return new Density(value, DensityUnit.KilogramPerLiter); } @@ -898,7 +880,7 @@ public static Density FromKilogramsPerLiter(double value) /// /// Creates a from . /// - public static Density FromKilopoundsPerCubicFoot(double value) + public static Density FromKilopoundsPerCubicFoot(QuantityValue value) { return new Density(value, DensityUnit.KilopoundPerCubicFoot); } @@ -906,7 +888,7 @@ public static Density FromKilopoundsPerCubicFoot(double value) /// /// Creates a from . /// - public static Density FromKilopoundsPerCubicInch(double value) + public static Density FromKilopoundsPerCubicInch(QuantityValue value) { return new Density(value, DensityUnit.KilopoundPerCubicInch); } @@ -914,7 +896,7 @@ public static Density FromKilopoundsPerCubicInch(double value) /// /// Creates a from . /// - public static Density FromKilopoundsPerCubicYard(double value) + public static Density FromKilopoundsPerCubicYard(QuantityValue value) { return new Density(value, DensityUnit.KilopoundPerCubicYard); } @@ -922,7 +904,7 @@ public static Density FromKilopoundsPerCubicYard(double value) /// /// Creates a from . /// - public static Density FromMicrogramsPerCubicMeter(double value) + public static Density FromMicrogramsPerCubicMeter(QuantityValue value) { return new Density(value, DensityUnit.MicrogramPerCubicMeter); } @@ -930,7 +912,7 @@ public static Density FromMicrogramsPerCubicMeter(double value) /// /// Creates a from . /// - public static Density FromMicrogramsPerDeciliter(double value) + public static Density FromMicrogramsPerDeciliter(QuantityValue value) { return new Density(value, DensityUnit.MicrogramPerDeciliter); } @@ -938,7 +920,7 @@ public static Density FromMicrogramsPerDeciliter(double value) /// /// Creates a from . /// - public static Density FromMicrogramsPerLiter(double value) + public static Density FromMicrogramsPerLiter(QuantityValue value) { return new Density(value, DensityUnit.MicrogramPerLiter); } @@ -946,7 +928,7 @@ public static Density FromMicrogramsPerLiter(double value) /// /// Creates a from . /// - public static Density FromMicrogramsPerMilliliter(double value) + public static Density FromMicrogramsPerMilliliter(QuantityValue value) { return new Density(value, DensityUnit.MicrogramPerMilliliter); } @@ -954,7 +936,7 @@ public static Density FromMicrogramsPerMilliliter(double value) /// /// Creates a from . /// - public static Density FromMilligramsPerCubicMeter(double value) + public static Density FromMilligramsPerCubicMeter(QuantityValue value) { return new Density(value, DensityUnit.MilligramPerCubicMeter); } @@ -962,7 +944,7 @@ public static Density FromMilligramsPerCubicMeter(double value) /// /// Creates a from . /// - public static Density FromMilligramsPerDeciliter(double value) + public static Density FromMilligramsPerDeciliter(QuantityValue value) { return new Density(value, DensityUnit.MilligramPerDeciliter); } @@ -970,7 +952,7 @@ public static Density FromMilligramsPerDeciliter(double value) /// /// Creates a from . /// - public static Density FromMilligramsPerLiter(double value) + public static Density FromMilligramsPerLiter(QuantityValue value) { return new Density(value, DensityUnit.MilligramPerLiter); } @@ -978,7 +960,7 @@ public static Density FromMilligramsPerLiter(double value) /// /// Creates a from . /// - public static Density FromMilligramsPerMilliliter(double value) + public static Density FromMilligramsPerMilliliter(QuantityValue value) { return new Density(value, DensityUnit.MilligramPerMilliliter); } @@ -986,7 +968,7 @@ public static Density FromMilligramsPerMilliliter(double value) /// /// Creates a from . /// - public static Density FromNanogramsPerDeciliter(double value) + public static Density FromNanogramsPerDeciliter(QuantityValue value) { return new Density(value, DensityUnit.NanogramPerDeciliter); } @@ -994,7 +976,7 @@ public static Density FromNanogramsPerDeciliter(double value) /// /// Creates a from . /// - public static Density FromNanogramsPerLiter(double value) + public static Density FromNanogramsPerLiter(QuantityValue value) { return new Density(value, DensityUnit.NanogramPerLiter); } @@ -1002,7 +984,7 @@ public static Density FromNanogramsPerLiter(double value) /// /// Creates a from . /// - public static Density FromNanogramsPerMilliliter(double value) + public static Density FromNanogramsPerMilliliter(QuantityValue value) { return new Density(value, DensityUnit.NanogramPerMilliliter); } @@ -1010,7 +992,7 @@ public static Density FromNanogramsPerMilliliter(double value) /// /// Creates a from . /// - public static Density FromPicogramsPerDeciliter(double value) + public static Density FromPicogramsPerDeciliter(QuantityValue value) { return new Density(value, DensityUnit.PicogramPerDeciliter); } @@ -1018,7 +1000,7 @@ public static Density FromPicogramsPerDeciliter(double value) /// /// Creates a from . /// - public static Density FromPicogramsPerLiter(double value) + public static Density FromPicogramsPerLiter(QuantityValue value) { return new Density(value, DensityUnit.PicogramPerLiter); } @@ -1026,7 +1008,7 @@ public static Density FromPicogramsPerLiter(double value) /// /// Creates a from . /// - public static Density FromPicogramsPerMilliliter(double value) + public static Density FromPicogramsPerMilliliter(QuantityValue value) { return new Density(value, DensityUnit.PicogramPerMilliliter); } @@ -1034,7 +1016,7 @@ public static Density FromPicogramsPerMilliliter(double value) /// /// Creates a from . /// - public static Density FromPoundsPerCubicCentimeter(double value) + public static Density FromPoundsPerCubicCentimeter(QuantityValue value) { return new Density(value, DensityUnit.PoundPerCubicCentimeter); } @@ -1042,7 +1024,7 @@ public static Density FromPoundsPerCubicCentimeter(double value) /// /// Creates a from . /// - public static Density FromPoundsPerCubicFoot(double value) + public static Density FromPoundsPerCubicFoot(QuantityValue value) { return new Density(value, DensityUnit.PoundPerCubicFoot); } @@ -1050,7 +1032,7 @@ public static Density FromPoundsPerCubicFoot(double value) /// /// Creates a from . /// - public static Density FromPoundsPerCubicInch(double value) + public static Density FromPoundsPerCubicInch(QuantityValue value) { return new Density(value, DensityUnit.PoundPerCubicInch); } @@ -1058,7 +1040,7 @@ public static Density FromPoundsPerCubicInch(double value) /// /// Creates a from . /// - public static Density FromPoundsPerCubicMeter(double value) + public static Density FromPoundsPerCubicMeter(QuantityValue value) { return new Density(value, DensityUnit.PoundPerCubicMeter); } @@ -1066,7 +1048,7 @@ public static Density FromPoundsPerCubicMeter(double value) /// /// Creates a from . /// - public static Density FromPoundsPerCubicMillimeter(double value) + public static Density FromPoundsPerCubicMillimeter(QuantityValue value) { return new Density(value, DensityUnit.PoundPerCubicMillimeter); } @@ -1074,7 +1056,7 @@ public static Density FromPoundsPerCubicMillimeter(double value) /// /// Creates a from . /// - public static Density FromPoundsPerCubicYard(double value) + public static Density FromPoundsPerCubicYard(QuantityValue value) { return new Density(value, DensityUnit.PoundPerCubicYard); } @@ -1082,7 +1064,7 @@ public static Density FromPoundsPerCubicYard(double value) /// /// Creates a from . /// - public static Density FromPoundsPerImperialGallon(double value) + public static Density FromPoundsPerImperialGallon(QuantityValue value) { return new Density(value, DensityUnit.PoundPerImperialGallon); } @@ -1090,7 +1072,7 @@ public static Density FromPoundsPerImperialGallon(double value) /// /// Creates a from . /// - public static Density FromPoundsPerUSGallon(double value) + public static Density FromPoundsPerUSGallon(QuantityValue value) { return new Density(value, DensityUnit.PoundPerUSGallon); } @@ -1098,7 +1080,7 @@ public static Density FromPoundsPerUSGallon(double value) /// /// Creates a from . /// - public static Density FromSlugsPerCubicCentimeter(double value) + public static Density FromSlugsPerCubicCentimeter(QuantityValue value) { return new Density(value, DensityUnit.SlugPerCubicCentimeter); } @@ -1106,7 +1088,7 @@ public static Density FromSlugsPerCubicCentimeter(double value) /// /// Creates a from . /// - public static Density FromSlugsPerCubicFoot(double value) + public static Density FromSlugsPerCubicFoot(QuantityValue value) { return new Density(value, DensityUnit.SlugPerCubicFoot); } @@ -1114,7 +1096,7 @@ public static Density FromSlugsPerCubicFoot(double value) /// /// Creates a from . /// - public static Density FromSlugsPerCubicInch(double value) + public static Density FromSlugsPerCubicInch(QuantityValue value) { return new Density(value, DensityUnit.SlugPerCubicInch); } @@ -1122,7 +1104,7 @@ public static Density FromSlugsPerCubicInch(double value) /// /// Creates a from . /// - public static Density FromSlugsPerCubicMeter(double value) + public static Density FromSlugsPerCubicMeter(QuantityValue value) { return new Density(value, DensityUnit.SlugPerCubicMeter); } @@ -1130,7 +1112,7 @@ public static Density FromSlugsPerCubicMeter(double value) /// /// Creates a from . /// - public static Density FromSlugsPerCubicMillimeter(double value) + public static Density FromSlugsPerCubicMillimeter(QuantityValue value) { return new Density(value, DensityUnit.SlugPerCubicMillimeter); } @@ -1138,7 +1120,7 @@ public static Density FromSlugsPerCubicMillimeter(double value) /// /// Creates a from . /// - public static Density FromTonnesPerCubicCentimeter(double value) + public static Density FromTonnesPerCubicCentimeter(QuantityValue value) { return new Density(value, DensityUnit.TonnePerCubicCentimeter); } @@ -1146,7 +1128,7 @@ public static Density FromTonnesPerCubicCentimeter(double value) /// /// Creates a from . /// - public static Density FromTonnesPerCubicFoot(double value) + public static Density FromTonnesPerCubicFoot(QuantityValue value) { return new Density(value, DensityUnit.TonnePerCubicFoot); } @@ -1154,7 +1136,7 @@ public static Density FromTonnesPerCubicFoot(double value) /// /// Creates a from . /// - public static Density FromTonnesPerCubicInch(double value) + public static Density FromTonnesPerCubicInch(QuantityValue value) { return new Density(value, DensityUnit.TonnePerCubicInch); } @@ -1162,7 +1144,7 @@ public static Density FromTonnesPerCubicInch(double value) /// /// Creates a from . /// - public static Density FromTonnesPerCubicMeter(double value) + public static Density FromTonnesPerCubicMeter(QuantityValue value) { return new Density(value, DensityUnit.TonnePerCubicMeter); } @@ -1170,7 +1152,7 @@ public static Density FromTonnesPerCubicMeter(double value) /// /// Creates a from . /// - public static Density FromTonnesPerCubicMillimeter(double value) + public static Density FromTonnesPerCubicMillimeter(QuantityValue value) { return new Density(value, DensityUnit.TonnePerCubicMillimeter); } @@ -1181,7 +1163,7 @@ public static Density FromTonnesPerCubicMillimeter(double value) /// Value to convert from. /// Unit to convert from. /// Density unit value. - public static Density From(double value, DensityUnit fromUnit) + public static Density From(QuantityValue value, DensityUnit fromUnit) { return new Density(value, fromUnit); } @@ -1242,10 +1224,7 @@ public static Density Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Density Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -1273,11 +1252,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Density result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Density result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -1298,7 +1273,7 @@ public static DensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -1309,7 +1284,7 @@ public static DensityUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out DensityUnit unit) { return TryParseUnit(str, null, out unit); @@ -1324,7 +1299,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out DensityUnit /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out DensityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -1343,35 +1318,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Density operator +(Density left, Density right) { - return new Density(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Density(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Density operator -(Density left, Density right) { - return new Density(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Density(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -1384,7 +1359,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// The corresponding inverse quantity, . public SpecificVolume Inverse() { - return SpecificVolume.FromCubicMetersPerKilogram(1 / KilogramsPerCubicMeter); + return UnitConverter.Default.ConvertTo(Value, Unit, SpecificVolume.Info); } /// Get from * . @@ -1436,97 +1411,82 @@ public SpecificVolume Inverse() /// Returns true if less or equal to. public static bool operator <=(Density left, Density right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Density left, Density right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Density left, Density right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Density left, Density right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Density other, Density tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Density left, Density right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Density other, Density tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Density left, Density right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Density other, Density tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Density otherQuantity)) + if (obj is not Density otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Density other, Density tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Density other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Density. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Density), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Density otherQuantity)) throw new ArgumentException("Expected type Density.", nameof(obj)); + if (obj is not Density otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1538,256 +1498,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Density other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(DensityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Density to another Density with the unit representation . - /// - /// The unit to convert to. - /// A Density with the specified unit. - public Density ToUnit(DensityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Density with the specified unit. - public Density ToUnit(DensityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Density), Unit, typeof(Density), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Density)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(DensityUnit unit, [NotNullWhen(true)] out Density? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Density? convertedOrNull = (Unit, unit) switch - { - // DensityUnit -> BaseUnit - (DensityUnit.CentigramPerDeciliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-1) * 1e-2d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.CentigramPerLiter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1) * 1e-2d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.CentigramPerMilliliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-3) * 1e-2d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.DecigramPerDeciliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-1) * 1e-1d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.DecigramPerLiter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1) * 1e-1d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.DecigramPerMilliliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-3) * 1e-1d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.FemtogramPerDeciliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-1) * 1e-15d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.FemtogramPerLiter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1) * 1e-15d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.FemtogramPerMilliliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-3) * 1e-15d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.GramPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 1e-3, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.GramPerCubicFoot, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 0.001 / 0.028316846592, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.GramPerCubicInch, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 0.001 / 1.6387064e-5, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.GramPerCubicMeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 1e3, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.GramPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 1e-6, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.GramPerDeciliter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 1e-1, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.GramPerLiter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 1, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.GramPerMilliliter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 1e-3, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.KilogramPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-3) * 1e3d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.KilogramPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-6) * 1e3d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.KilogramPerLiter, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 1e3, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.KilopoundPerCubicFoot, DensityUnit.KilogramPerCubicMeter) => new Density((_value * 0.45359237 / 0.028316846592) * 1e3d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.KilopoundPerCubicInch, DensityUnit.KilogramPerCubicMeter) => new Density((_value * 0.45359237 / 1.6387064e-5) * 1e3d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.KilopoundPerCubicYard, DensityUnit.KilogramPerCubicMeter) => new Density((_value * 0.45359237 / 0.764554857984) * 1e3d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.MicrogramPerCubicMeter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e3) * 1e-6d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.MicrogramPerDeciliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-1) * 1e-6d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.MicrogramPerLiter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1) * 1e-6d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.MicrogramPerMilliliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-3) * 1e-6d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.MilligramPerCubicMeter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e3) * 1e-3d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.MilligramPerDeciliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-1) * 1e-3d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.MilligramPerLiter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1) * 1e-3d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.MilligramPerMilliliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-3) * 1e-3d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.NanogramPerDeciliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-1) * 1e-9d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.NanogramPerLiter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1) * 1e-9d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.NanogramPerMilliliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-3) * 1e-9d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.PicogramPerDeciliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-1) * 1e-12d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.PicogramPerLiter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1) * 1e-12d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.PicogramPerMilliliter, DensityUnit.KilogramPerCubicMeter) => new Density((_value / 1e-3) * 1e-12d, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.PoundPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 0.45359237e6, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.PoundPerCubicFoot, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 0.45359237 / 0.028316846592, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.PoundPerCubicInch, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 0.45359237 / 1.6387064e-5, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.PoundPerCubicMeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 0.45359237, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.PoundPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 0.45359237e9, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.PoundPerCubicYard, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 0.45359237 / 0.764554857984, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.PoundPerImperialGallon, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 0.45359237 / 0.00454609, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.PoundPerUSGallon, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 0.45359237 / 0.003785411784, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.SlugPerCubicCentimeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 0.45359237e6 * 9.80665 / 0.3048, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.SlugPerCubicFoot, DensityUnit.KilogramPerCubicMeter) => new Density(_value * (0.45359237 * 9.80665) / (0.3048 * 0.028316846592), DensityUnit.KilogramPerCubicMeter), - (DensityUnit.SlugPerCubicInch, DensityUnit.KilogramPerCubicMeter) => new Density(_value * (0.45359237 * 9.80665) / (0.3048 * 1.6387064e-5), DensityUnit.KilogramPerCubicMeter), - (DensityUnit.SlugPerCubicMeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 0.45359237 * 9.80665 / 0.3048, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.SlugPerCubicMillimeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 0.45359237e9 * 9.80665 / 0.3048, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.TonnePerCubicCentimeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 1e-9, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.TonnePerCubicFoot, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 1000 / 0.028316846592, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.TonnePerCubicInch, DensityUnit.KilogramPerCubicMeter) => new Density(_value * 1000 / 1.6387064e-5, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.TonnePerCubicMeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 0.001, DensityUnit.KilogramPerCubicMeter), - (DensityUnit.TonnePerCubicMillimeter, DensityUnit.KilogramPerCubicMeter) => new Density(_value / 1e-12, DensityUnit.KilogramPerCubicMeter), - - // BaseUnit -> DensityUnit - (DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerDeciliter) => new Density((_value * 1e-1) / 1e-2d, DensityUnit.CentigramPerDeciliter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerLiter) => new Density((_value * 1) / 1e-2d, DensityUnit.CentigramPerLiter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.CentigramPerMilliliter) => new Density((_value * 1e-3) / 1e-2d, DensityUnit.CentigramPerMilliliter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerDeciliter) => new Density((_value * 1e-1) / 1e-1d, DensityUnit.DecigramPerDeciliter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerLiter) => new Density((_value * 1) / 1e-1d, DensityUnit.DecigramPerLiter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.DecigramPerMilliliter) => new Density((_value * 1e-3) / 1e-1d, DensityUnit.DecigramPerMilliliter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.FemtogramPerDeciliter) => new Density((_value * 1e-1) / 1e-15d, DensityUnit.FemtogramPerDeciliter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.FemtogramPerLiter) => new Density((_value * 1) / 1e-15d, DensityUnit.FemtogramPerLiter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.FemtogramPerMilliliter) => new Density((_value * 1e-3) / 1e-15d, DensityUnit.FemtogramPerMilliliter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicCentimeter) => new Density(_value * 1e-3, DensityUnit.GramPerCubicCentimeter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicFoot) => new Density(_value * 0.028316846592 / 0.001, DensityUnit.GramPerCubicFoot), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicInch) => new Density(_value * 1.6387064e-5 / 0.001, DensityUnit.GramPerCubicInch), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicMeter) => new Density(_value * 1e3, DensityUnit.GramPerCubicMeter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerCubicMillimeter) => new Density(_value * 1e-6, DensityUnit.GramPerCubicMillimeter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerDeciliter) => new Density(_value * 1e-1, DensityUnit.GramPerDeciliter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerLiter) => new Density(_value * 1, DensityUnit.GramPerLiter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.GramPerMilliliter) => new Density(_value * 1e-3, DensityUnit.GramPerMilliliter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicCentimeter) => new Density((_value * 1e-3) / 1e3d, DensityUnit.KilogramPerCubicCentimeter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerCubicMillimeter) => new Density((_value * 1e-6) / 1e3d, DensityUnit.KilogramPerCubicMillimeter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.KilogramPerLiter) => new Density(_value / 1e3, DensityUnit.KilogramPerLiter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.KilopoundPerCubicFoot) => new Density((_value * 0.028316846592 / 0.45359237) / 1e3d, DensityUnit.KilopoundPerCubicFoot), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.KilopoundPerCubicInch) => new Density((_value * 1.6387064e-5 / 0.45359237) / 1e3d, DensityUnit.KilopoundPerCubicInch), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.KilopoundPerCubicYard) => new Density((_value * 0.764554857984 / 0.45359237) / 1e3d, DensityUnit.KilopoundPerCubicYard), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerCubicMeter) => new Density((_value * 1e3) / 1e-6d, DensityUnit.MicrogramPerCubicMeter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerDeciliter) => new Density((_value * 1e-1) / 1e-6d, DensityUnit.MicrogramPerDeciliter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerLiter) => new Density((_value * 1) / 1e-6d, DensityUnit.MicrogramPerLiter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.MicrogramPerMilliliter) => new Density((_value * 1e-3) / 1e-6d, DensityUnit.MicrogramPerMilliliter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerCubicMeter) => new Density((_value * 1e3) / 1e-3d, DensityUnit.MilligramPerCubicMeter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerDeciliter) => new Density((_value * 1e-1) / 1e-3d, DensityUnit.MilligramPerDeciliter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerLiter) => new Density((_value * 1) / 1e-3d, DensityUnit.MilligramPerLiter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.MilligramPerMilliliter) => new Density((_value * 1e-3) / 1e-3d, DensityUnit.MilligramPerMilliliter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerDeciliter) => new Density((_value * 1e-1) / 1e-9d, DensityUnit.NanogramPerDeciliter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerLiter) => new Density((_value * 1) / 1e-9d, DensityUnit.NanogramPerLiter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.NanogramPerMilliliter) => new Density((_value * 1e-3) / 1e-9d, DensityUnit.NanogramPerMilliliter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerDeciliter) => new Density((_value * 1e-1) / 1e-12d, DensityUnit.PicogramPerDeciliter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerLiter) => new Density((_value * 1) / 1e-12d, DensityUnit.PicogramPerLiter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.PicogramPerMilliliter) => new Density((_value * 1e-3) / 1e-12d, DensityUnit.PicogramPerMilliliter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicCentimeter) => new Density(_value / 0.45359237e6, DensityUnit.PoundPerCubicCentimeter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicFoot) => new Density(_value * 0.028316846592 / 0.45359237, DensityUnit.PoundPerCubicFoot), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicInch) => new Density(_value * 1.6387064e-5 / 0.45359237, DensityUnit.PoundPerCubicInch), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicMeter) => new Density(_value / 0.45359237, DensityUnit.PoundPerCubicMeter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicMillimeter) => new Density(_value / 0.45359237e9, DensityUnit.PoundPerCubicMillimeter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerCubicYard) => new Density(_value * 0.764554857984 / 0.45359237, DensityUnit.PoundPerCubicYard), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerImperialGallon) => new Density(_value * 0.00454609 / 0.45359237, DensityUnit.PoundPerImperialGallon), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.PoundPerUSGallon) => new Density(_value * 0.003785411784 / 0.45359237, DensityUnit.PoundPerUSGallon), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicCentimeter) => new Density(_value * 0.3048 / (0.45359237e6 * 9.80665), DensityUnit.SlugPerCubicCentimeter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicFoot) => new Density(_value * (0.3048 * 0.028316846592) / (0.45359237 * 9.80665), DensityUnit.SlugPerCubicFoot), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicInch) => new Density(_value * (0.3048 * 1.6387064e-5) / (0.45359237 * 9.80665), DensityUnit.SlugPerCubicInch), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicMeter) => new Density(_value * 0.3048 / (0.45359237 * 9.80665), DensityUnit.SlugPerCubicMeter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.SlugPerCubicMillimeter) => new Density(_value * 0.3048 / (0.45359237e9 * 9.80665), DensityUnit.SlugPerCubicMillimeter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicCentimeter) => new Density(_value * 1e-9, DensityUnit.TonnePerCubicCentimeter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicFoot) => new Density(_value * 0.028316846592 / 1000, DensityUnit.TonnePerCubicFoot), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicInch) => new Density(_value * 1.6387064e-5 / 1000, DensityUnit.TonnePerCubicInch), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicMeter) => new Density(_value * 0.001, DensityUnit.TonnePerCubicMeter), - (DensityUnit.KilogramPerCubicMeter, DensityUnit.TonnePerCubicMillimeter) => new Density(_value * 1e-12, DensityUnit.TonnePerCubicMillimeter), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Density ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not DensityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DensityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(DensityUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(DensityUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1802,7 +1530,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/DoseAreaProduct.g.cs b/UnitsNet/GeneratedCode/Quantities/DoseAreaProduct.g.cs index 0be48a838c..3ce4c85189 100644 --- a/UnitsNet/GeneratedCode/Quantities/DoseAreaProduct.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/DoseAreaProduct.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Dose_area_product /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct DoseAreaProduct : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly DoseAreaProductUnit? _unit; /// @@ -104,7 +103,7 @@ public static DoseAreaProductInfo CreateDefault(Func - /// The for is [T^-2][L^4]. + /// The for is T^-2L^4. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(4, 0, -2, 0, 0, 0, 0); @@ -119,39 +118,85 @@ public static DoseAreaProductInfo CreateDefault(FuncAn of representing the default unit mappings for DoseAreaProduct. public static IEnumerable> GetDefaultMappings() { - yield return new (DoseAreaProductUnit.CentigraySquareCentimeter, "CentigraySquareCentimeter", "CentigraySquareCentimeters", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.CentigraySquareDecimeter, "CentigraySquareDecimeter", "CentigraySquareDecimeters", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.CentigraySquareMeter, "CentigraySquareMeter", "CentigraySquareMeters", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.CentigraySquareMicrometer, "CentigraySquareMicrometer", "CentigraySquareMicrometers", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.CentigraySquareMillimeter, "CentigraySquareMillimeter", "CentigraySquareMillimeters", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.DecigraySquareCentimeter, "DecigraySquareCentimeter", "DecigraySquareCentimeters", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.DecigraySquareDecimeter, "DecigraySquareDecimeter", "DecigraySquareDecimeters", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.DecigraySquareMeter, "DecigraySquareMeter", "DecigraySquareMeters", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.DecigraySquareMicrometer, "DecigraySquareMicrometer", "DecigraySquareMicrometers", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.DecigraySquareMillimeter, "DecigraySquareMillimeter", "DecigraySquareMillimeters", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.GraySquareCentimeter, "GraySquareCentimeter", "GraySquareCentimeters", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.GraySquareDecimeter, "GraySquareDecimeter", "GraySquareDecimeters", BaseUnits.Undefined); + yield return new (DoseAreaProductUnit.CentigraySquareCentimeter, "CentigraySquareCentimeter", "CentigraySquareCentimeters", BaseUnits.Undefined, + 1000000 + ); + yield return new (DoseAreaProductUnit.CentigraySquareDecimeter, "CentigraySquareDecimeter", "CentigraySquareDecimeters", BaseUnits.Undefined, + 10000 + ); + yield return new (DoseAreaProductUnit.CentigraySquareMeter, "CentigraySquareMeter", "CentigraySquareMeters", BaseUnits.Undefined, + 100 + ); + yield return new (DoseAreaProductUnit.CentigraySquareMicrometer, "CentigraySquareMicrometer", "CentigraySquareMicrometers", BaseUnits.Undefined, + 100000000000000 + ); + yield return new (DoseAreaProductUnit.CentigraySquareMillimeter, "CentigraySquareMillimeter", "CentigraySquareMillimeters", BaseUnits.Undefined, + 100000000 + ); + yield return new (DoseAreaProductUnit.DecigraySquareCentimeter, "DecigraySquareCentimeter", "DecigraySquareCentimeters", BaseUnits.Undefined, + 100000 + ); + yield return new (DoseAreaProductUnit.DecigraySquareDecimeter, "DecigraySquareDecimeter", "DecigraySquareDecimeters", BaseUnits.Undefined, + 1000 + ); + yield return new (DoseAreaProductUnit.DecigraySquareMeter, "DecigraySquareMeter", "DecigraySquareMeters", BaseUnits.Undefined, + 10 + ); + yield return new (DoseAreaProductUnit.DecigraySquareMicrometer, "DecigraySquareMicrometer", "DecigraySquareMicrometers", BaseUnits.Undefined, + 10000000000000 + ); + yield return new (DoseAreaProductUnit.DecigraySquareMillimeter, "DecigraySquareMillimeter", "DecigraySquareMillimeters", BaseUnits.Undefined, + 10000000 + ); + yield return new (DoseAreaProductUnit.GraySquareCentimeter, "GraySquareCentimeter", "GraySquareCentimeters", BaseUnits.Undefined, + 10000 + ); + yield return new (DoseAreaProductUnit.GraySquareDecimeter, "GraySquareDecimeter", "GraySquareDecimeters", BaseUnits.Undefined, + 100 + ); yield return new (DoseAreaProductUnit.GraySquareMeter, "GraySquareMeter", "GraySquareMeters", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)); - yield return new (DoseAreaProductUnit.GraySquareMicrometer, "GraySquareMicrometer", "GraySquareMicrometers", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.GraySquareMillimeter, "GraySquareMillimeter", "GraySquareMillimeters", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.MicrograySquareCentimeter, "MicrograySquareCentimeter", "MicrograySquareCentimeters", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.MicrograySquareDecimeter, "MicrograySquareDecimeter", "MicrograySquareDecimeters", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.MicrograySquareMeter, "MicrograySquareMeter", "MicrograySquareMeters", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.MicrograySquareMicrometer, "MicrograySquareMicrometer", "MicrograySquareMicrometers", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.MicrograySquareMillimeter, "MicrograySquareMillimeter", "MicrograySquareMillimeters", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.MilligraySquareCentimeter, "MilligraySquareCentimeter", "MilligraySquareCentimeters", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.MilligraySquareDecimeter, "MilligraySquareDecimeter", "MilligraySquareDecimeters", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.MilligraySquareMeter, "MilligraySquareMeter", "MilligraySquareMeters", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.MilligraySquareMicrometer, "MilligraySquareMicrometer", "MilligraySquareMicrometers", BaseUnits.Undefined); - yield return new (DoseAreaProductUnit.MilligraySquareMillimeter, "MilligraySquareMillimeter", "MilligraySquareMillimeters", BaseUnits.Undefined); + yield return new (DoseAreaProductUnit.GraySquareMicrometer, "GraySquareMicrometer", "GraySquareMicrometers", BaseUnits.Undefined, + 1000000000000 + ); + yield return new (DoseAreaProductUnit.GraySquareMillimeter, "GraySquareMillimeter", "GraySquareMillimeters", BaseUnits.Undefined, + 1000000 + ); + yield return new (DoseAreaProductUnit.MicrograySquareCentimeter, "MicrograySquareCentimeter", "MicrograySquareCentimeters", BaseUnits.Undefined, + 10000000000 + ); + yield return new (DoseAreaProductUnit.MicrograySquareDecimeter, "MicrograySquareDecimeter", "MicrograySquareDecimeters", BaseUnits.Undefined, + 100000000 + ); + yield return new (DoseAreaProductUnit.MicrograySquareMeter, "MicrograySquareMeter", "MicrograySquareMeters", BaseUnits.Undefined, + 1000000 + ); + yield return new (DoseAreaProductUnit.MicrograySquareMicrometer, "MicrograySquareMicrometer", "MicrograySquareMicrometers", BaseUnits.Undefined, + 1000000000000000000 + ); + yield return new (DoseAreaProductUnit.MicrograySquareMillimeter, "MicrograySquareMillimeter", "MicrograySquareMillimeters", BaseUnits.Undefined, + 1000000000000 + ); + yield return new (DoseAreaProductUnit.MilligraySquareCentimeter, "MilligraySquareCentimeter", "MilligraySquareCentimeters", BaseUnits.Undefined, + 10000000 + ); + yield return new (DoseAreaProductUnit.MilligraySquareDecimeter, "MilligraySquareDecimeter", "MilligraySquareDecimeters", BaseUnits.Undefined, + 100000 + ); + yield return new (DoseAreaProductUnit.MilligraySquareMeter, "MilligraySquareMeter", "MilligraySquareMeters", BaseUnits.Undefined, + 1000 + ); + yield return new (DoseAreaProductUnit.MilligraySquareMicrometer, "MilligraySquareMicrometer", "MilligraySquareMicrometers", BaseUnits.Undefined, + 1000000000000000 + ); + yield return new (DoseAreaProductUnit.MilligraySquareMillimeter, "MilligraySquareMillimeter", "MilligraySquareMillimeters", BaseUnits.Undefined, + 1000000000 + ); } } static DoseAreaProduct() { - Info = DoseAreaProductInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(DoseAreaProductInfo.CreateDefault); } /// @@ -159,7 +204,7 @@ static DoseAreaProduct() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public DoseAreaProduct(double value, DoseAreaProductUnit unit) + public DoseAreaProduct(QuantityValue value, DoseAreaProductUnit unit) { _value = value; _unit = unit; @@ -173,7 +218,7 @@ public DoseAreaProduct(double value, DoseAreaProductUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public DoseAreaProduct(double value, UnitSystem unitSystem) + public DoseAreaProduct(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -184,7 +229,8 @@ public DoseAreaProduct(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -213,10 +259,8 @@ public DoseAreaProduct(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public DoseAreaProductUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -255,196 +299,134 @@ public DoseAreaProduct(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentigraySquareCentimeters => As(DoseAreaProductUnit.CentigraySquareCentimeter); + public QuantityValue CentigraySquareCentimeters => this.As(DoseAreaProductUnit.CentigraySquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentigraySquareDecimeters => As(DoseAreaProductUnit.CentigraySquareDecimeter); + public QuantityValue CentigraySquareDecimeters => this.As(DoseAreaProductUnit.CentigraySquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentigraySquareMeters => As(DoseAreaProductUnit.CentigraySquareMeter); + public QuantityValue CentigraySquareMeters => this.As(DoseAreaProductUnit.CentigraySquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentigraySquareMicrometers => As(DoseAreaProductUnit.CentigraySquareMicrometer); + public QuantityValue CentigraySquareMicrometers => this.As(DoseAreaProductUnit.CentigraySquareMicrometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentigraySquareMillimeters => As(DoseAreaProductUnit.CentigraySquareMillimeter); + public QuantityValue CentigraySquareMillimeters => this.As(DoseAreaProductUnit.CentigraySquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecigraySquareCentimeters => As(DoseAreaProductUnit.DecigraySquareCentimeter); + public QuantityValue DecigraySquareCentimeters => this.As(DoseAreaProductUnit.DecigraySquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecigraySquareDecimeters => As(DoseAreaProductUnit.DecigraySquareDecimeter); + public QuantityValue DecigraySquareDecimeters => this.As(DoseAreaProductUnit.DecigraySquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecigraySquareMeters => As(DoseAreaProductUnit.DecigraySquareMeter); + public QuantityValue DecigraySquareMeters => this.As(DoseAreaProductUnit.DecigraySquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecigraySquareMicrometers => As(DoseAreaProductUnit.DecigraySquareMicrometer); + public QuantityValue DecigraySquareMicrometers => this.As(DoseAreaProductUnit.DecigraySquareMicrometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecigraySquareMillimeters => As(DoseAreaProductUnit.DecigraySquareMillimeter); + public QuantityValue DecigraySquareMillimeters => this.As(DoseAreaProductUnit.DecigraySquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GraySquareCentimeters => As(DoseAreaProductUnit.GraySquareCentimeter); + public QuantityValue GraySquareCentimeters => this.As(DoseAreaProductUnit.GraySquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GraySquareDecimeters => As(DoseAreaProductUnit.GraySquareDecimeter); + public QuantityValue GraySquareDecimeters => this.As(DoseAreaProductUnit.GraySquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GraySquareMeters => As(DoseAreaProductUnit.GraySquareMeter); + public QuantityValue GraySquareMeters => this.As(DoseAreaProductUnit.GraySquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GraySquareMicrometers => As(DoseAreaProductUnit.GraySquareMicrometer); + public QuantityValue GraySquareMicrometers => this.As(DoseAreaProductUnit.GraySquareMicrometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GraySquareMillimeters => As(DoseAreaProductUnit.GraySquareMillimeter); + public QuantityValue GraySquareMillimeters => this.As(DoseAreaProductUnit.GraySquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrograySquareCentimeters => As(DoseAreaProductUnit.MicrograySquareCentimeter); + public QuantityValue MicrograySquareCentimeters => this.As(DoseAreaProductUnit.MicrograySquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrograySquareDecimeters => As(DoseAreaProductUnit.MicrograySquareDecimeter); + public QuantityValue MicrograySquareDecimeters => this.As(DoseAreaProductUnit.MicrograySquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrograySquareMeters => As(DoseAreaProductUnit.MicrograySquareMeter); + public QuantityValue MicrograySquareMeters => this.As(DoseAreaProductUnit.MicrograySquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrograySquareMicrometers => As(DoseAreaProductUnit.MicrograySquareMicrometer); + public QuantityValue MicrograySquareMicrometers => this.As(DoseAreaProductUnit.MicrograySquareMicrometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrograySquareMillimeters => As(DoseAreaProductUnit.MicrograySquareMillimeter); + public QuantityValue MicrograySquareMillimeters => this.As(DoseAreaProductUnit.MicrograySquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligraySquareCentimeters => As(DoseAreaProductUnit.MilligraySquareCentimeter); + public QuantityValue MilligraySquareCentimeters => this.As(DoseAreaProductUnit.MilligraySquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligraySquareDecimeters => As(DoseAreaProductUnit.MilligraySquareDecimeter); + public QuantityValue MilligraySquareDecimeters => this.As(DoseAreaProductUnit.MilligraySquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligraySquareMeters => As(DoseAreaProductUnit.MilligraySquareMeter); + public QuantityValue MilligraySquareMeters => this.As(DoseAreaProductUnit.MilligraySquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligraySquareMicrometers => As(DoseAreaProductUnit.MilligraySquareMicrometer); + public QuantityValue MilligraySquareMicrometers => this.As(DoseAreaProductUnit.MilligraySquareMicrometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligraySquareMillimeters => As(DoseAreaProductUnit.MilligraySquareMillimeter); + public QuantityValue MilligraySquareMillimeters => this.As(DoseAreaProductUnit.MilligraySquareMillimeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: DoseAreaProductUnit -> BaseUnit - unitConverter.SetConversionFunction(DoseAreaProductUnit.CentigraySquareCentimeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.CentigraySquareDecimeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.CentigraySquareMeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.CentigraySquareMicrometer, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.CentigraySquareMillimeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.DecigraySquareCentimeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.DecigraySquareDecimeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.DecigraySquareMeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.DecigraySquareMicrometer, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.DecigraySquareMillimeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareCentimeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareDecimeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMicrometer, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMillimeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.MicrograySquareCentimeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.MicrograySquareDecimeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.MicrograySquareMeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.MicrograySquareMicrometer, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.MicrograySquareMillimeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.MilligraySquareCentimeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.MilligraySquareDecimeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.MilligraySquareMeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.MilligraySquareMicrometer, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.MilligraySquareMillimeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.GraySquareMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> DoseAreaProductUnit - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.CentigraySquareCentimeter, quantity => quantity.ToUnit(DoseAreaProductUnit.CentigraySquareCentimeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.CentigraySquareDecimeter, quantity => quantity.ToUnit(DoseAreaProductUnit.CentigraySquareDecimeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.CentigraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.CentigraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.CentigraySquareMicrometer, quantity => quantity.ToUnit(DoseAreaProductUnit.CentigraySquareMicrometer)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.CentigraySquareMillimeter, quantity => quantity.ToUnit(DoseAreaProductUnit.CentigraySquareMillimeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.DecigraySquareCentimeter, quantity => quantity.ToUnit(DoseAreaProductUnit.DecigraySquareCentimeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.DecigraySquareDecimeter, quantity => quantity.ToUnit(DoseAreaProductUnit.DecigraySquareDecimeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.DecigraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.DecigraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.DecigraySquareMicrometer, quantity => quantity.ToUnit(DoseAreaProductUnit.DecigraySquareMicrometer)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.DecigraySquareMillimeter, quantity => quantity.ToUnit(DoseAreaProductUnit.DecigraySquareMillimeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.GraySquareCentimeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareCentimeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.GraySquareDecimeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareDecimeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.GraySquareMicrometer, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMicrometer)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.GraySquareMillimeter, quantity => quantity.ToUnit(DoseAreaProductUnit.GraySquareMillimeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MicrograySquareCentimeter, quantity => quantity.ToUnit(DoseAreaProductUnit.MicrograySquareCentimeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MicrograySquareDecimeter, quantity => quantity.ToUnit(DoseAreaProductUnit.MicrograySquareDecimeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MicrograySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.MicrograySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MicrograySquareMicrometer, quantity => quantity.ToUnit(DoseAreaProductUnit.MicrograySquareMicrometer)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MicrograySquareMillimeter, quantity => quantity.ToUnit(DoseAreaProductUnit.MicrograySquareMillimeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MilligraySquareCentimeter, quantity => quantity.ToUnit(DoseAreaProductUnit.MilligraySquareCentimeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MilligraySquareDecimeter, quantity => quantity.ToUnit(DoseAreaProductUnit.MilligraySquareDecimeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MilligraySquareMeter, quantity => quantity.ToUnit(DoseAreaProductUnit.MilligraySquareMeter)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MilligraySquareMicrometer, quantity => quantity.ToUnit(DoseAreaProductUnit.MilligraySquareMicrometer)); - unitConverter.SetConversionFunction(DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MilligraySquareMillimeter, quantity => quantity.ToUnit(DoseAreaProductUnit.MilligraySquareMillimeter)); - } - /// /// Get unit abbreviation string. /// @@ -473,7 +455,7 @@ public static string GetAbbreviation(DoseAreaProductUnit unit, IFormatProvider? /// /// Creates a from . /// - public static DoseAreaProduct FromCentigraySquareCentimeters(double value) + public static DoseAreaProduct FromCentigraySquareCentimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.CentigraySquareCentimeter); } @@ -481,7 +463,7 @@ public static DoseAreaProduct FromCentigraySquareCentimeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromCentigraySquareDecimeters(double value) + public static DoseAreaProduct FromCentigraySquareDecimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.CentigraySquareDecimeter); } @@ -489,7 +471,7 @@ public static DoseAreaProduct FromCentigraySquareDecimeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromCentigraySquareMeters(double value) + public static DoseAreaProduct FromCentigraySquareMeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.CentigraySquareMeter); } @@ -497,7 +479,7 @@ public static DoseAreaProduct FromCentigraySquareMeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromCentigraySquareMicrometers(double value) + public static DoseAreaProduct FromCentigraySquareMicrometers(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.CentigraySquareMicrometer); } @@ -505,7 +487,7 @@ public static DoseAreaProduct FromCentigraySquareMicrometers(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromCentigraySquareMillimeters(double value) + public static DoseAreaProduct FromCentigraySquareMillimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.CentigraySquareMillimeter); } @@ -513,7 +495,7 @@ public static DoseAreaProduct FromCentigraySquareMillimeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromDecigraySquareCentimeters(double value) + public static DoseAreaProduct FromDecigraySquareCentimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.DecigraySquareCentimeter); } @@ -521,7 +503,7 @@ public static DoseAreaProduct FromDecigraySquareCentimeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromDecigraySquareDecimeters(double value) + public static DoseAreaProduct FromDecigraySquareDecimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.DecigraySquareDecimeter); } @@ -529,7 +511,7 @@ public static DoseAreaProduct FromDecigraySquareDecimeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromDecigraySquareMeters(double value) + public static DoseAreaProduct FromDecigraySquareMeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.DecigraySquareMeter); } @@ -537,7 +519,7 @@ public static DoseAreaProduct FromDecigraySquareMeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromDecigraySquareMicrometers(double value) + public static DoseAreaProduct FromDecigraySquareMicrometers(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.DecigraySquareMicrometer); } @@ -545,7 +527,7 @@ public static DoseAreaProduct FromDecigraySquareMicrometers(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromDecigraySquareMillimeters(double value) + public static DoseAreaProduct FromDecigraySquareMillimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.DecigraySquareMillimeter); } @@ -553,7 +535,7 @@ public static DoseAreaProduct FromDecigraySquareMillimeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromGraySquareCentimeters(double value) + public static DoseAreaProduct FromGraySquareCentimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.GraySquareCentimeter); } @@ -561,7 +543,7 @@ public static DoseAreaProduct FromGraySquareCentimeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromGraySquareDecimeters(double value) + public static DoseAreaProduct FromGraySquareDecimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.GraySquareDecimeter); } @@ -569,7 +551,7 @@ public static DoseAreaProduct FromGraySquareDecimeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromGraySquareMeters(double value) + public static DoseAreaProduct FromGraySquareMeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.GraySquareMeter); } @@ -577,7 +559,7 @@ public static DoseAreaProduct FromGraySquareMeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromGraySquareMicrometers(double value) + public static DoseAreaProduct FromGraySquareMicrometers(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.GraySquareMicrometer); } @@ -585,7 +567,7 @@ public static DoseAreaProduct FromGraySquareMicrometers(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromGraySquareMillimeters(double value) + public static DoseAreaProduct FromGraySquareMillimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.GraySquareMillimeter); } @@ -593,7 +575,7 @@ public static DoseAreaProduct FromGraySquareMillimeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromMicrograySquareCentimeters(double value) + public static DoseAreaProduct FromMicrograySquareCentimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.MicrograySquareCentimeter); } @@ -601,7 +583,7 @@ public static DoseAreaProduct FromMicrograySquareCentimeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromMicrograySquareDecimeters(double value) + public static DoseAreaProduct FromMicrograySquareDecimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.MicrograySquareDecimeter); } @@ -609,7 +591,7 @@ public static DoseAreaProduct FromMicrograySquareDecimeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromMicrograySquareMeters(double value) + public static DoseAreaProduct FromMicrograySquareMeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.MicrograySquareMeter); } @@ -617,7 +599,7 @@ public static DoseAreaProduct FromMicrograySquareMeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromMicrograySquareMicrometers(double value) + public static DoseAreaProduct FromMicrograySquareMicrometers(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.MicrograySquareMicrometer); } @@ -625,7 +607,7 @@ public static DoseAreaProduct FromMicrograySquareMicrometers(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromMicrograySquareMillimeters(double value) + public static DoseAreaProduct FromMicrograySquareMillimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.MicrograySquareMillimeter); } @@ -633,7 +615,7 @@ public static DoseAreaProduct FromMicrograySquareMillimeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromMilligraySquareCentimeters(double value) + public static DoseAreaProduct FromMilligraySquareCentimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.MilligraySquareCentimeter); } @@ -641,7 +623,7 @@ public static DoseAreaProduct FromMilligraySquareCentimeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromMilligraySquareDecimeters(double value) + public static DoseAreaProduct FromMilligraySquareDecimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.MilligraySquareDecimeter); } @@ -649,7 +631,7 @@ public static DoseAreaProduct FromMilligraySquareDecimeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromMilligraySquareMeters(double value) + public static DoseAreaProduct FromMilligraySquareMeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.MilligraySquareMeter); } @@ -657,7 +639,7 @@ public static DoseAreaProduct FromMilligraySquareMeters(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromMilligraySquareMicrometers(double value) + public static DoseAreaProduct FromMilligraySquareMicrometers(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.MilligraySquareMicrometer); } @@ -665,7 +647,7 @@ public static DoseAreaProduct FromMilligraySquareMicrometers(double value) /// /// Creates a from . /// - public static DoseAreaProduct FromMilligraySquareMillimeters(double value) + public static DoseAreaProduct FromMilligraySquareMillimeters(QuantityValue value) { return new DoseAreaProduct(value, DoseAreaProductUnit.MilligraySquareMillimeter); } @@ -676,7 +658,7 @@ public static DoseAreaProduct FromMilligraySquareMillimeters(double value) /// Value to convert from. /// Unit to convert from. /// DoseAreaProduct unit value. - public static DoseAreaProduct From(double value, DoseAreaProductUnit fromUnit) + public static DoseAreaProduct From(QuantityValue value, DoseAreaProductUnit fromUnit) { return new DoseAreaProduct(value, fromUnit); } @@ -737,10 +719,7 @@ public static DoseAreaProduct Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static DoseAreaProduct Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -768,11 +747,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out DoseAreaProduct /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out DoseAreaProduct result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -793,7 +768,7 @@ public static DoseAreaProductUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -804,7 +779,7 @@ public static DoseAreaProductUnit ParseUnit(string str, IFormatProvider? provide return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out DoseAreaProductUnit unit) { return TryParseUnit(str, null, out unit); @@ -819,7 +794,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out DoseAreaProd /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out DoseAreaProductUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -838,35 +813,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static DoseAreaProduct operator +(DoseAreaProduct left, DoseAreaProduct right) { - return new DoseAreaProduct(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new DoseAreaProduct(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static DoseAreaProduct operator -(DoseAreaProduct left, DoseAreaProduct right) { - return new DoseAreaProduct(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new DoseAreaProduct(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static DoseAreaProduct operator *(double left, DoseAreaProduct right) + public static DoseAreaProduct operator *(QuantityValue left, DoseAreaProduct right) { return new DoseAreaProduct(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static DoseAreaProduct operator *(DoseAreaProduct left, double right) + public static DoseAreaProduct operator *(DoseAreaProduct left, QuantityValue right) { return new DoseAreaProduct(left.Value * right, left.Unit); } /// Get from dividing by value. - public static DoseAreaProduct operator /(DoseAreaProduct left, double right) + public static DoseAreaProduct operator /(DoseAreaProduct left, QuantityValue right) { return new DoseAreaProduct(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(DoseAreaProduct left, DoseAreaProduct right) + public static QuantityValue operator /(DoseAreaProduct left, DoseAreaProduct right) { return left.GraySquareMeters / right.GraySquareMeters; } @@ -878,97 +853,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(DoseAreaProduct left, DoseAreaProduct right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(DoseAreaProduct left, DoseAreaProduct right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(DoseAreaProduct left, DoseAreaProduct right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(DoseAreaProduct left, DoseAreaProduct right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(DoseAreaProduct other, DoseAreaProduct tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(DoseAreaProduct left, DoseAreaProduct right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(DoseAreaProduct other, DoseAreaProduct tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(DoseAreaProduct left, DoseAreaProduct right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(DoseAreaProduct other, DoseAreaProduct tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is DoseAreaProduct otherQuantity)) + if (obj is not DoseAreaProduct otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(DoseAreaProduct other, DoseAreaProduct tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(DoseAreaProduct other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current DoseAreaProduct. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(DoseAreaProduct), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is DoseAreaProduct otherQuantity)) throw new ArgumentException("Expected type DoseAreaProduct.", nameof(obj)); + if (obj is not DoseAreaProduct otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -980,194 +940,24 @@ public int CompareTo(object? obj) /// public int CompareTo(DoseAreaProduct other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(DoseAreaProductUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this DoseAreaProduct to another DoseAreaProduct with the unit representation . - /// - /// The unit to convert to. - /// A DoseAreaProduct with the specified unit. - public DoseAreaProduct ToUnit(DoseAreaProductUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A DoseAreaProduct with the specified unit. - public DoseAreaProduct ToUnit(DoseAreaProductUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(DoseAreaProduct), Unit, typeof(DoseAreaProduct), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (DoseAreaProduct)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(DoseAreaProductUnit unit, [NotNullWhen(true)] out DoseAreaProduct? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - DoseAreaProduct? convertedOrNull = (Unit, unit) switch - { - // DoseAreaProductUnit -> BaseUnit - (DoseAreaProductUnit.CentigraySquareCentimeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value / 10000) * 1e-2d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.CentigraySquareDecimeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value / 100) * 1e-2d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.CentigraySquareMeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value) * 1e-2d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.CentigraySquareMicrometer, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value / 1000000000000) * 1e-2d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.CentigraySquareMillimeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value / 1000000) * 1e-2d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.DecigraySquareCentimeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value / 10000) * 1e-1d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.DecigraySquareDecimeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value / 100) * 1e-1d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.DecigraySquareMeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value) * 1e-1d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.DecigraySquareMicrometer, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value / 1000000000000) * 1e-1d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.DecigraySquareMillimeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value / 1000000) * 1e-1d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.GraySquareCentimeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct(_value / 10000, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.GraySquareDecimeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct(_value / 100, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.GraySquareMicrometer, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct(_value / 1000000000000, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.GraySquareMillimeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct(_value / 1000000, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.MicrograySquareCentimeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value / 10000) * 1e-6d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.MicrograySquareDecimeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value / 100) * 1e-6d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.MicrograySquareMeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value) * 1e-6d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.MicrograySquareMicrometer, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value / 1000000000000) * 1e-6d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.MicrograySquareMillimeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value / 1000000) * 1e-6d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.MilligraySquareCentimeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value / 10000) * 1e-3d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.MilligraySquareDecimeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value / 100) * 1e-3d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.MilligraySquareMeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value) * 1e-3d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.MilligraySquareMicrometer, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value / 1000000000000) * 1e-3d, DoseAreaProductUnit.GraySquareMeter), - (DoseAreaProductUnit.MilligraySquareMillimeter, DoseAreaProductUnit.GraySquareMeter) => new DoseAreaProduct((_value / 1000000) * 1e-3d, DoseAreaProductUnit.GraySquareMeter), - - // BaseUnit -> DoseAreaProductUnit - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.CentigraySquareCentimeter) => new DoseAreaProduct((_value * 10000) / 1e-2d, DoseAreaProductUnit.CentigraySquareCentimeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.CentigraySquareDecimeter) => new DoseAreaProduct((_value * 100) / 1e-2d, DoseAreaProductUnit.CentigraySquareDecimeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.CentigraySquareMeter) => new DoseAreaProduct((_value) / 1e-2d, DoseAreaProductUnit.CentigraySquareMeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.CentigraySquareMicrometer) => new DoseAreaProduct((_value * 1000000000000) / 1e-2d, DoseAreaProductUnit.CentigraySquareMicrometer), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.CentigraySquareMillimeter) => new DoseAreaProduct((_value * 1000000) / 1e-2d, DoseAreaProductUnit.CentigraySquareMillimeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.DecigraySquareCentimeter) => new DoseAreaProduct((_value * 10000) / 1e-1d, DoseAreaProductUnit.DecigraySquareCentimeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.DecigraySquareDecimeter) => new DoseAreaProduct((_value * 100) / 1e-1d, DoseAreaProductUnit.DecigraySquareDecimeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.DecigraySquareMeter) => new DoseAreaProduct((_value) / 1e-1d, DoseAreaProductUnit.DecigraySquareMeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.DecigraySquareMicrometer) => new DoseAreaProduct((_value * 1000000000000) / 1e-1d, DoseAreaProductUnit.DecigraySquareMicrometer), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.DecigraySquareMillimeter) => new DoseAreaProduct((_value * 1000000) / 1e-1d, DoseAreaProductUnit.DecigraySquareMillimeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.GraySquareCentimeter) => new DoseAreaProduct(_value * 10000, DoseAreaProductUnit.GraySquareCentimeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.GraySquareDecimeter) => new DoseAreaProduct(_value * 100, DoseAreaProductUnit.GraySquareDecimeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.GraySquareMicrometer) => new DoseAreaProduct(_value * 1000000000000, DoseAreaProductUnit.GraySquareMicrometer), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.GraySquareMillimeter) => new DoseAreaProduct(_value * 1000000, DoseAreaProductUnit.GraySquareMillimeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MicrograySquareCentimeter) => new DoseAreaProduct((_value * 10000) / 1e-6d, DoseAreaProductUnit.MicrograySquareCentimeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MicrograySquareDecimeter) => new DoseAreaProduct((_value * 100) / 1e-6d, DoseAreaProductUnit.MicrograySquareDecimeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MicrograySquareMeter) => new DoseAreaProduct((_value) / 1e-6d, DoseAreaProductUnit.MicrograySquareMeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MicrograySquareMicrometer) => new DoseAreaProduct((_value * 1000000000000) / 1e-6d, DoseAreaProductUnit.MicrograySquareMicrometer), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MicrograySquareMillimeter) => new DoseAreaProduct((_value * 1000000) / 1e-6d, DoseAreaProductUnit.MicrograySquareMillimeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MilligraySquareCentimeter) => new DoseAreaProduct((_value * 10000) / 1e-3d, DoseAreaProductUnit.MilligraySquareCentimeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MilligraySquareDecimeter) => new DoseAreaProduct((_value * 100) / 1e-3d, DoseAreaProductUnit.MilligraySquareDecimeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MilligraySquareMeter) => new DoseAreaProduct((_value) / 1e-3d, DoseAreaProductUnit.MilligraySquareMeter), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MilligraySquareMicrometer) => new DoseAreaProduct((_value * 1000000000000) / 1e-3d, DoseAreaProductUnit.MilligraySquareMicrometer), - (DoseAreaProductUnit.GraySquareMeter, DoseAreaProductUnit.MilligraySquareMillimeter) => new DoseAreaProduct((_value * 1000000) / 1e-3d, DoseAreaProductUnit.MilligraySquareMillimeter), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public DoseAreaProduct ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not DoseAreaProductUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DoseAreaProductUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is DoseAreaProductUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DoseAreaProductUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(DoseAreaProductUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(DoseAreaProductUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1182,7 +972,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Duration.g.cs b/UnitsNet/GeneratedCode/Quantities/Duration.g.cs index 177523e824..2445da8ff1 100644 --- a/UnitsNet/GeneratedCode/Quantities/Duration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Duration.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Duration : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -67,13 +66,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly DurationUnit? _unit; /// @@ -118,7 +117,7 @@ public static DurationInfo CreateDefault(Func - /// The for is [T]. + /// The for is T. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 1, 0, 0, 0, 0); @@ -133,27 +132,49 @@ public static DurationInfo CreateDefault(FuncAn of representing the default unit mappings for Duration. public static IEnumerable> GetDefaultMappings() { - yield return new (DurationUnit.Day, "Day", "Days", new BaseUnits(time: DurationUnit.Day)); - yield return new (DurationUnit.Hour, "Hour", "Hours", new BaseUnits(time: DurationUnit.Hour)); - yield return new (DurationUnit.JulianYear, "JulianYear", "JulianYears", new BaseUnits(time: DurationUnit.JulianYear)); - yield return new (DurationUnit.Microsecond, "Microsecond", "Microseconds", new BaseUnits(time: DurationUnit.Microsecond)); - yield return new (DurationUnit.Millisecond, "Millisecond", "Milliseconds", new BaseUnits(time: DurationUnit.Millisecond)); - yield return new (DurationUnit.Minute, "Minute", "Minutes", new BaseUnits(time: DurationUnit.Minute)); - yield return new (DurationUnit.Month30, "Month30", "Months30", new BaseUnits(time: DurationUnit.Month30)); - yield return new (DurationUnit.Nanosecond, "Nanosecond", "Nanoseconds", new BaseUnits(time: DurationUnit.Nanosecond)); - yield return new (DurationUnit.Picosecond, "Picosecond", "Picoseconds", new BaseUnits(time: DurationUnit.Picosecond)); + yield return new (DurationUnit.Day, "Day", "Days", new BaseUnits(time: DurationUnit.Day), + new QuantityValue(1, 86400) + ); + yield return new (DurationUnit.Hour, "Hour", "Hours", new BaseUnits(time: DurationUnit.Hour), + new QuantityValue(1, 3600) + ); + yield return new (DurationUnit.JulianYear, "JulianYear", "JulianYears", new BaseUnits(time: DurationUnit.JulianYear), + new QuantityValue(1, 31557600) + ); + yield return new (DurationUnit.Microsecond, "Microsecond", "Microseconds", new BaseUnits(time: DurationUnit.Microsecond), + 1000000 + ); + yield return new (DurationUnit.Millisecond, "Millisecond", "Milliseconds", new BaseUnits(time: DurationUnit.Millisecond), + 1000 + ); + yield return new (DurationUnit.Minute, "Minute", "Minutes", new BaseUnits(time: DurationUnit.Minute), + new QuantityValue(1, 60) + ); + yield return new (DurationUnit.Month30, "Month30", "Months30", new BaseUnits(time: DurationUnit.Month30), + new QuantityValue(1, 2592000) + ); + yield return new (DurationUnit.Nanosecond, "Nanosecond", "Nanoseconds", new BaseUnits(time: DurationUnit.Nanosecond), + 1000000000 + ); + yield return new (DurationUnit.Picosecond, "Picosecond", "Picoseconds", new BaseUnits(time: DurationUnit.Picosecond), + 1000000000000 + ); yield return new (DurationUnit.Second, "Second", "Seconds", new BaseUnits(time: DurationUnit.Second)); - yield return new (DurationUnit.Sol, "Sol", "Sols", new BaseUnits(time: DurationUnit.Sol)); - yield return new (DurationUnit.Week, "Week", "Weeks", new BaseUnits(time: DurationUnit.Week)); - yield return new (DurationUnit.Year365, "Year365", "Years365", new BaseUnits(time: DurationUnit.Year365)); + yield return new (DurationUnit.Sol, "Sol", "Sols", new BaseUnits(time: DurationUnit.Sol), + new QuantityValue(250, 22193811) + ); + yield return new (DurationUnit.Week, "Week", "Weeks", new BaseUnits(time: DurationUnit.Week), + new QuantityValue(1, 604800) + ); + yield return new (DurationUnit.Year365, "Year365", "Years365", new BaseUnits(time: DurationUnit.Year365), + new QuantityValue(1, 31536000) + ); } } static Duration() { - Info = DurationInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(DurationInfo.CreateDefault); } /// @@ -161,7 +182,7 @@ static Duration() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Duration(double value, DurationUnit unit) + public Duration(QuantityValue value, DurationUnit unit) { _value = value; _unit = unit; @@ -175,7 +196,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -186,7 +207,8 @@ public Duration(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -215,10 +237,8 @@ public Duration(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public DurationUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -257,112 +277,74 @@ public Duration(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Days => As(DurationUnit.Day); + public QuantityValue Days => this.As(DurationUnit.Day); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Hours => As(DurationUnit.Hour); + public QuantityValue Hours => this.As(DurationUnit.Hour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double JulianYears => As(DurationUnit.JulianYear); + public QuantityValue JulianYears => this.As(DurationUnit.JulianYear); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microseconds => As(DurationUnit.Microsecond); + public QuantityValue Microseconds => this.As(DurationUnit.Microsecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Milliseconds => As(DurationUnit.Millisecond); + public QuantityValue Milliseconds => this.As(DurationUnit.Millisecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Minutes => As(DurationUnit.Minute); + public QuantityValue Minutes => this.As(DurationUnit.Minute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Months30 => As(DurationUnit.Month30); + public QuantityValue Months30 => this.As(DurationUnit.Month30); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanoseconds => As(DurationUnit.Nanosecond); + public QuantityValue Nanoseconds => this.As(DurationUnit.Nanosecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Picoseconds => As(DurationUnit.Picosecond); + public QuantityValue Picoseconds => this.As(DurationUnit.Picosecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Seconds => As(DurationUnit.Second); + public QuantityValue Seconds => this.As(DurationUnit.Second); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Sols => As(DurationUnit.Sol); + public QuantityValue Sols => this.As(DurationUnit.Sol); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Weeks => As(DurationUnit.Week); + public QuantityValue Weeks => this.As(DurationUnit.Week); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Years365 => As(DurationUnit.Year365); + public QuantityValue Years365 => this.As(DurationUnit.Year365); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: DurationUnit -> BaseUnit - unitConverter.SetConversionFunction(DurationUnit.Day, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); - unitConverter.SetConversionFunction(DurationUnit.Hour, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); - unitConverter.SetConversionFunction(DurationUnit.JulianYear, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); - unitConverter.SetConversionFunction(DurationUnit.Microsecond, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); - unitConverter.SetConversionFunction(DurationUnit.Millisecond, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); - unitConverter.SetConversionFunction(DurationUnit.Minute, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); - unitConverter.SetConversionFunction(DurationUnit.Month30, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); - unitConverter.SetConversionFunction(DurationUnit.Nanosecond, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); - unitConverter.SetConversionFunction(DurationUnit.Picosecond, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); - unitConverter.SetConversionFunction(DurationUnit.Sol, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); - unitConverter.SetConversionFunction(DurationUnit.Week, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); - unitConverter.SetConversionFunction(DurationUnit.Year365, DurationUnit.Second, quantity => quantity.ToUnit(DurationUnit.Second)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Second, quantity => quantity); - - // Register in unit converter: BaseUnit -> DurationUnit - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Day, quantity => quantity.ToUnit(DurationUnit.Day)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Hour, quantity => quantity.ToUnit(DurationUnit.Hour)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.JulianYear, quantity => quantity.ToUnit(DurationUnit.JulianYear)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Microsecond, quantity => quantity.ToUnit(DurationUnit.Microsecond)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Millisecond, quantity => quantity.ToUnit(DurationUnit.Millisecond)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Minute, quantity => quantity.ToUnit(DurationUnit.Minute)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Month30, quantity => quantity.ToUnit(DurationUnit.Month30)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Nanosecond, quantity => quantity.ToUnit(DurationUnit.Nanosecond)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Picosecond, quantity => quantity.ToUnit(DurationUnit.Picosecond)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Sol, quantity => quantity.ToUnit(DurationUnit.Sol)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Week, quantity => quantity.ToUnit(DurationUnit.Week)); - unitConverter.SetConversionFunction(DurationUnit.Second, DurationUnit.Year365, quantity => quantity.ToUnit(DurationUnit.Year365)); - } - /// /// Get unit abbreviation string. /// @@ -391,7 +373,7 @@ public static string GetAbbreviation(DurationUnit unit, IFormatProvider? provide /// /// Creates a from . /// - public static Duration FromDays(double value) + public static Duration FromDays(QuantityValue value) { return new Duration(value, DurationUnit.Day); } @@ -399,7 +381,7 @@ public static Duration FromDays(double value) /// /// Creates a from . /// - public static Duration FromHours(double value) + public static Duration FromHours(QuantityValue value) { return new Duration(value, DurationUnit.Hour); } @@ -407,7 +389,7 @@ public static Duration FromHours(double value) /// /// Creates a from . /// - public static Duration FromJulianYears(double value) + public static Duration FromJulianYears(QuantityValue value) { return new Duration(value, DurationUnit.JulianYear); } @@ -415,7 +397,7 @@ public static Duration FromJulianYears(double value) /// /// Creates a from . /// - public static Duration FromMicroseconds(double value) + public static Duration FromMicroseconds(QuantityValue value) { return new Duration(value, DurationUnit.Microsecond); } @@ -423,7 +405,7 @@ public static Duration FromMicroseconds(double value) /// /// Creates a from . /// - public static Duration FromMilliseconds(double value) + public static Duration FromMilliseconds(QuantityValue value) { return new Duration(value, DurationUnit.Millisecond); } @@ -431,7 +413,7 @@ public static Duration FromMilliseconds(double value) /// /// Creates a from . /// - public static Duration FromMinutes(double value) + public static Duration FromMinutes(QuantityValue value) { return new Duration(value, DurationUnit.Minute); } @@ -439,7 +421,7 @@ public static Duration FromMinutes(double value) /// /// Creates a from . /// - public static Duration FromMonths30(double value) + public static Duration FromMonths30(QuantityValue value) { return new Duration(value, DurationUnit.Month30); } @@ -447,7 +429,7 @@ public static Duration FromMonths30(double value) /// /// Creates a from . /// - public static Duration FromNanoseconds(double value) + public static Duration FromNanoseconds(QuantityValue value) { return new Duration(value, DurationUnit.Nanosecond); } @@ -455,7 +437,7 @@ public static Duration FromNanoseconds(double value) /// /// Creates a from . /// - public static Duration FromPicoseconds(double value) + public static Duration FromPicoseconds(QuantityValue value) { return new Duration(value, DurationUnit.Picosecond); } @@ -463,7 +445,7 @@ public static Duration FromPicoseconds(double value) /// /// Creates a from . /// - public static Duration FromSeconds(double value) + public static Duration FromSeconds(QuantityValue value) { return new Duration(value, DurationUnit.Second); } @@ -471,7 +453,7 @@ public static Duration FromSeconds(double value) /// /// Creates a from . /// - public static Duration FromSols(double value) + public static Duration FromSols(QuantityValue value) { return new Duration(value, DurationUnit.Sol); } @@ -479,7 +461,7 @@ public static Duration FromSols(double value) /// /// Creates a from . /// - public static Duration FromWeeks(double value) + public static Duration FromWeeks(QuantityValue value) { return new Duration(value, DurationUnit.Week); } @@ -487,7 +469,7 @@ public static Duration FromWeeks(double value) /// /// Creates a from . /// - public static Duration FromYears365(double value) + public static Duration FromYears365(QuantityValue value) { return new Duration(value, DurationUnit.Year365); } @@ -498,7 +480,7 @@ public static Duration FromYears365(double value) /// Value to convert from. /// Unit to convert from. /// Duration unit value. - public static Duration From(double value, DurationUnit fromUnit) + public static Duration From(QuantityValue value, DurationUnit fromUnit) { return new Duration(value, fromUnit); } @@ -559,10 +541,7 @@ public static Duration Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Duration Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -590,11 +569,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Duration result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Duration result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -615,7 +590,7 @@ public static DurationUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -626,7 +601,7 @@ public static DurationUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out DurationUnit unit) { return TryParseUnit(str, null, out unit); @@ -641,7 +616,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out DurationUnit /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out DurationUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -660,35 +635,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Duration operator +(Duration left, Duration right) { - return new Duration(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Duration(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Duration operator -(Duration left, Duration right) { - return new Duration(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Duration(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -794,97 +769,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Duration left, Duration right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Duration left, Duration right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Duration left, Duration right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Duration left, Duration right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Duration other, Duration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Duration left, Duration right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Duration other, Duration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Duration left, Duration right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Duration other, Duration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Duration otherQuantity)) + if (obj is not Duration otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Duration other, Duration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Duration other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Duration. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Duration), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Duration otherQuantity)) throw new ArgumentException("Expected type Duration.", nameof(obj)); + if (obj is not Duration otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -896,170 +856,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Duration other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(DurationUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this Duration to another Duration with the unit representation . - /// - /// The unit to convert to. - /// A Duration with the specified unit. - public Duration ToUnit(DurationUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Duration with the specified unit. - public Duration ToUnit(DurationUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Duration), Unit, typeof(Duration), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Duration)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(DurationUnit unit, [NotNullWhen(true)] out Duration? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Duration? convertedOrNull = (Unit, unit) switch - { - // DurationUnit -> BaseUnit - (DurationUnit.Day, DurationUnit.Second) => new Duration(_value * 24 * 3600, DurationUnit.Second), - (DurationUnit.Hour, DurationUnit.Second) => new Duration(_value * 3600, DurationUnit.Second), - (DurationUnit.JulianYear, DurationUnit.Second) => new Duration(_value * 365.25 * 24 * 3600, DurationUnit.Second), - (DurationUnit.Microsecond, DurationUnit.Second) => new Duration((_value) * 1e-6d, DurationUnit.Second), - (DurationUnit.Millisecond, DurationUnit.Second) => new Duration((_value) * 1e-3d, DurationUnit.Second), - (DurationUnit.Minute, DurationUnit.Second) => new Duration(_value * 60, DurationUnit.Second), - (DurationUnit.Month30, DurationUnit.Second) => new Duration(_value * 30 * 24 * 3600, DurationUnit.Second), - (DurationUnit.Nanosecond, DurationUnit.Second) => new Duration((_value) * 1e-9d, DurationUnit.Second), - (DurationUnit.Picosecond, DurationUnit.Second) => new Duration((_value) * 1e-12d, DurationUnit.Second), - (DurationUnit.Sol, DurationUnit.Second) => new Duration(_value * 88775.244, DurationUnit.Second), - (DurationUnit.Week, DurationUnit.Second) => new Duration(_value * 7 * 24 * 3600, DurationUnit.Second), - (DurationUnit.Year365, DurationUnit.Second) => new Duration(_value * 365 * 24 * 3600, DurationUnit.Second), - - // BaseUnit -> DurationUnit - (DurationUnit.Second, DurationUnit.Day) => new Duration(_value / (24 * 3600), DurationUnit.Day), - (DurationUnit.Second, DurationUnit.Hour) => new Duration(_value / 3600, DurationUnit.Hour), - (DurationUnit.Second, DurationUnit.JulianYear) => new Duration(_value / (365.25 * 24 * 3600), DurationUnit.JulianYear), - (DurationUnit.Second, DurationUnit.Microsecond) => new Duration((_value) / 1e-6d, DurationUnit.Microsecond), - (DurationUnit.Second, DurationUnit.Millisecond) => new Duration((_value) / 1e-3d, DurationUnit.Millisecond), - (DurationUnit.Second, DurationUnit.Minute) => new Duration(_value / 60, DurationUnit.Minute), - (DurationUnit.Second, DurationUnit.Month30) => new Duration(_value / (30 * 24 * 3600), DurationUnit.Month30), - (DurationUnit.Second, DurationUnit.Nanosecond) => new Duration((_value) / 1e-9d, DurationUnit.Nanosecond), - (DurationUnit.Second, DurationUnit.Picosecond) => new Duration((_value) / 1e-12d, DurationUnit.Picosecond), - (DurationUnit.Second, DurationUnit.Sol) => new Duration(_value / 88775.244, DurationUnit.Sol), - (DurationUnit.Second, DurationUnit.Week) => new Duration(_value / (7 * 24 * 3600), DurationUnit.Week), - (DurationUnit.Second, DurationUnit.Year365) => new Duration(_value / (365 * 24 * 3600), DurationUnit.Year365), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Duration ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not DurationUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DurationUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(DurationUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(DurationUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1074,7 +888,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs index e30c0a0a43..00b1974193 100644 --- a/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/DynamicViscosity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Viscosity#Dynamic_.28shear.29_viscosity /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct DynamicViscosity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -57,13 +56,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly DynamicViscosityUnit? _unit; /// @@ -108,7 +107,7 @@ public static DynamicViscosityInfo CreateDefault(Func - /// The for is [T^-1][L^-1][M]. + /// The for is T^-1L^-1M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 1, -1, 0, 0, 0, 0); @@ -123,24 +122,40 @@ public static DynamicViscosityInfo CreateDefault(FuncAn of representing the default unit mappings for DynamicViscosity. public static IEnumerable> GetDefaultMappings() { - yield return new (DynamicViscosityUnit.Centipoise, "Centipoise", "Centipoise", BaseUnits.Undefined); - yield return new (DynamicViscosityUnit.MicropascalSecond, "MicropascalSecond", "MicropascalSeconds", BaseUnits.Undefined); - yield return new (DynamicViscosityUnit.MillipascalSecond, "MillipascalSecond", "MillipascalSeconds", BaseUnits.Undefined); + yield return new (DynamicViscosityUnit.Centipoise, "Centipoise", "Centipoise", BaseUnits.Undefined, + 1000 + ); + yield return new (DynamicViscosityUnit.MicropascalSecond, "MicropascalSecond", "MicropascalSeconds", BaseUnits.Undefined, + 1000000 + ); + yield return new (DynamicViscosityUnit.MillipascalSecond, "MillipascalSecond", "MillipascalSeconds", BaseUnits.Undefined, + 1000 + ); yield return new (DynamicViscosityUnit.NewtonSecondPerMeterSquared, "NewtonSecondPerMeterSquared", "NewtonSecondsPerMeterSquared", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (DynamicViscosityUnit.PascalSecond, "PascalSecond", "PascalSeconds", BaseUnits.Undefined); - yield return new (DynamicViscosityUnit.Poise, "Poise", "Poise", BaseUnits.Undefined); - yield return new (DynamicViscosityUnit.PoundForceSecondPerSquareFoot, "PoundForceSecondPerSquareFoot", "PoundsForceSecondPerSquareFoot", BaseUnits.Undefined); - yield return new (DynamicViscosityUnit.PoundForceSecondPerSquareInch, "PoundForceSecondPerSquareInch", "PoundsForceSecondPerSquareInch", BaseUnits.Undefined); - yield return new (DynamicViscosityUnit.PoundPerFootSecond, "PoundPerFootSecond", "PoundsPerFootSecond", BaseUnits.Undefined); - yield return new (DynamicViscosityUnit.Reyn, "Reyn", "Reyns", BaseUnits.Undefined); + yield return new (DynamicViscosityUnit.PascalSecond, "PascalSecond", "PascalSeconds", BaseUnits.Undefined, + 1 + ); + yield return new (DynamicViscosityUnit.Poise, "Poise", "Poise", BaseUnits.Undefined, + 10 + ); + yield return new (DynamicViscosityUnit.PoundForceSecondPerSquareFoot, "PoundForceSecondPerSquareFoot", "PoundsForceSecondPerSquareFoot", BaseUnits.Undefined, + new QuantityValue(185806080000, 8896443230521) + ); + yield return new (DynamicViscosityUnit.PoundForceSecondPerSquareInch, "PoundForceSecondPerSquareInch", "PoundsForceSecondPerSquareInch", BaseUnits.Undefined, + new QuantityValue(1290320000, 8896443230521) + ); + yield return new (DynamicViscosityUnit.PoundPerFootSecond, "PoundPerFootSecond", "PoundsPerFootSecond", BaseUnits.Undefined, + new QuantityValue(30480000, 45359237) + ); + yield return new (DynamicViscosityUnit.Reyn, "Reyn", "Reyns", BaseUnits.Undefined, + new QuantityValue(1290320000, 8896443230521) + ); } } static DynamicViscosity() { - Info = DynamicViscosityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(DynamicViscosityInfo.CreateDefault); } /// @@ -148,7 +163,7 @@ static DynamicViscosity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public DynamicViscosity(double value, DynamicViscosityUnit unit) + public DynamicViscosity(QuantityValue value, DynamicViscosityUnit unit) { _value = value; _unit = unit; @@ -162,7 +177,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -173,7 +188,8 @@ public DynamicViscosity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -202,10 +218,8 @@ public DynamicViscosity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public DynamicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -244,91 +258,59 @@ public DynamicViscosity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Centipoise => As(DynamicViscosityUnit.Centipoise); + public QuantityValue Centipoise => this.As(DynamicViscosityUnit.Centipoise); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicropascalSeconds => As(DynamicViscosityUnit.MicropascalSecond); + public QuantityValue MicropascalSeconds => this.As(DynamicViscosityUnit.MicropascalSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillipascalSeconds => As(DynamicViscosityUnit.MillipascalSecond); + public QuantityValue MillipascalSeconds => this.As(DynamicViscosityUnit.MillipascalSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonSecondsPerMeterSquared => As(DynamicViscosityUnit.NewtonSecondPerMeterSquared); + public QuantityValue NewtonSecondsPerMeterSquared => this.As(DynamicViscosityUnit.NewtonSecondPerMeterSquared); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PascalSeconds => As(DynamicViscosityUnit.PascalSecond); + public QuantityValue PascalSeconds => this.As(DynamicViscosityUnit.PascalSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Poise => As(DynamicViscosityUnit.Poise); + public QuantityValue Poise => this.As(DynamicViscosityUnit.Poise); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsForceSecondPerSquareFoot => As(DynamicViscosityUnit.PoundForceSecondPerSquareFoot); + public QuantityValue PoundsForceSecondPerSquareFoot => this.As(DynamicViscosityUnit.PoundForceSecondPerSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsForceSecondPerSquareInch => As(DynamicViscosityUnit.PoundForceSecondPerSquareInch); + public QuantityValue PoundsForceSecondPerSquareInch => this.As(DynamicViscosityUnit.PoundForceSecondPerSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerFootSecond => As(DynamicViscosityUnit.PoundPerFootSecond); + public QuantityValue PoundsPerFootSecond => this.As(DynamicViscosityUnit.PoundPerFootSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Reyns => As(DynamicViscosityUnit.Reyn); + public QuantityValue Reyns => this.As(DynamicViscosityUnit.Reyn); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: DynamicViscosityUnit -> BaseUnit - unitConverter.SetConversionFunction(DynamicViscosityUnit.Centipoise, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.MicropascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.MillipascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.PascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.Poise, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.PoundForceSecondPerSquareFoot, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.PoundForceSecondPerSquareInch, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.PoundPerFootSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.Reyn, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity.ToUnit(DynamicViscosityUnit.NewtonSecondPerMeterSquared)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.NewtonSecondPerMeterSquared, quantity => quantity); - - // Register in unit converter: BaseUnit -> DynamicViscosityUnit - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Centipoise, quantity => quantity.ToUnit(DynamicViscosityUnit.Centipoise)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.MicropascalSecond, quantity => quantity.ToUnit(DynamicViscosityUnit.MicropascalSecond)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.MillipascalSecond, quantity => quantity.ToUnit(DynamicViscosityUnit.MillipascalSecond)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PascalSecond, quantity => quantity.ToUnit(DynamicViscosityUnit.PascalSecond)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Poise, quantity => quantity.ToUnit(DynamicViscosityUnit.Poise)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundForceSecondPerSquareFoot, quantity => quantity.ToUnit(DynamicViscosityUnit.PoundForceSecondPerSquareFoot)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundForceSecondPerSquareInch, quantity => quantity.ToUnit(DynamicViscosityUnit.PoundForceSecondPerSquareInch)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundPerFootSecond, quantity => quantity.ToUnit(DynamicViscosityUnit.PoundPerFootSecond)); - unitConverter.SetConversionFunction(DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Reyn, quantity => quantity.ToUnit(DynamicViscosityUnit.Reyn)); - } - /// /// Get unit abbreviation string. /// @@ -357,7 +339,7 @@ public static string GetAbbreviation(DynamicViscosityUnit unit, IFormatProvider? /// /// Creates a from . /// - public static DynamicViscosity FromCentipoise(double value) + public static DynamicViscosity FromCentipoise(QuantityValue value) { return new DynamicViscosity(value, DynamicViscosityUnit.Centipoise); } @@ -365,7 +347,7 @@ public static DynamicViscosity FromCentipoise(double value) /// /// Creates a from . /// - public static DynamicViscosity FromMicropascalSeconds(double value) + public static DynamicViscosity FromMicropascalSeconds(QuantityValue value) { return new DynamicViscosity(value, DynamicViscosityUnit.MicropascalSecond); } @@ -373,7 +355,7 @@ public static DynamicViscosity FromMicropascalSeconds(double value) /// /// Creates a from . /// - public static DynamicViscosity FromMillipascalSeconds(double value) + public static DynamicViscosity FromMillipascalSeconds(QuantityValue value) { return new DynamicViscosity(value, DynamicViscosityUnit.MillipascalSecond); } @@ -381,7 +363,7 @@ public static DynamicViscosity FromMillipascalSeconds(double value) /// /// Creates a from . /// - public static DynamicViscosity FromNewtonSecondsPerMeterSquared(double value) + public static DynamicViscosity FromNewtonSecondsPerMeterSquared(QuantityValue value) { return new DynamicViscosity(value, DynamicViscosityUnit.NewtonSecondPerMeterSquared); } @@ -389,7 +371,7 @@ public static DynamicViscosity FromNewtonSecondsPerMeterSquared(double value) /// /// Creates a from . /// - public static DynamicViscosity FromPascalSeconds(double value) + public static DynamicViscosity FromPascalSeconds(QuantityValue value) { return new DynamicViscosity(value, DynamicViscosityUnit.PascalSecond); } @@ -397,7 +379,7 @@ public static DynamicViscosity FromPascalSeconds(double value) /// /// Creates a from . /// - public static DynamicViscosity FromPoise(double value) + public static DynamicViscosity FromPoise(QuantityValue value) { return new DynamicViscosity(value, DynamicViscosityUnit.Poise); } @@ -405,7 +387,7 @@ public static DynamicViscosity FromPoise(double value) /// /// Creates a from . /// - public static DynamicViscosity FromPoundsForceSecondPerSquareFoot(double value) + public static DynamicViscosity FromPoundsForceSecondPerSquareFoot(QuantityValue value) { return new DynamicViscosity(value, DynamicViscosityUnit.PoundForceSecondPerSquareFoot); } @@ -413,7 +395,7 @@ public static DynamicViscosity FromPoundsForceSecondPerSquareFoot(double value) /// /// Creates a from . /// - public static DynamicViscosity FromPoundsForceSecondPerSquareInch(double value) + public static DynamicViscosity FromPoundsForceSecondPerSquareInch(QuantityValue value) { return new DynamicViscosity(value, DynamicViscosityUnit.PoundForceSecondPerSquareInch); } @@ -421,7 +403,7 @@ public static DynamicViscosity FromPoundsForceSecondPerSquareInch(double value) /// /// Creates a from . /// - public static DynamicViscosity FromPoundsPerFootSecond(double value) + public static DynamicViscosity FromPoundsPerFootSecond(QuantityValue value) { return new DynamicViscosity(value, DynamicViscosityUnit.PoundPerFootSecond); } @@ -429,7 +411,7 @@ public static DynamicViscosity FromPoundsPerFootSecond(double value) /// /// Creates a from . /// - public static DynamicViscosity FromReyns(double value) + public static DynamicViscosity FromReyns(QuantityValue value) { return new DynamicViscosity(value, DynamicViscosityUnit.Reyn); } @@ -440,7 +422,7 @@ public static DynamicViscosity FromReyns(double value) /// Value to convert from. /// Unit to convert from. /// DynamicViscosity unit value. - public static DynamicViscosity From(double value, DynamicViscosityUnit fromUnit) + public static DynamicViscosity From(QuantityValue value, DynamicViscosityUnit fromUnit) { return new DynamicViscosity(value, fromUnit); } @@ -501,10 +483,7 @@ public static DynamicViscosity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static DynamicViscosity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -532,11 +511,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out DynamicViscosity /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out DynamicViscosity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -557,7 +532,7 @@ public static DynamicViscosityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -568,7 +543,7 @@ public static DynamicViscosityUnit ParseUnit(string str, IFormatProvider? provid return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out DynamicViscosityUnit unit) { return TryParseUnit(str, null, out unit); @@ -583,7 +558,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out DynamicVisco /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out DynamicViscosityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -602,35 +577,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static DynamicViscosity operator +(DynamicViscosity left, DynamicViscosity right) { - return new DynamicViscosity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new DynamicViscosity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static DynamicViscosity operator -(DynamicViscosity left, DynamicViscosity right) { - return new DynamicViscosity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new DynamicViscosity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -658,97 +633,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(DynamicViscosity left, DynamicViscosity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(DynamicViscosity left, DynamicViscosity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(DynamicViscosity left, DynamicViscosity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(DynamicViscosity left, DynamicViscosity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(DynamicViscosity other, DynamicViscosity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(DynamicViscosity left, DynamicViscosity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(DynamicViscosity other, DynamicViscosity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(DynamicViscosity left, DynamicViscosity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(DynamicViscosity other, DynamicViscosity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is DynamicViscosity otherQuantity)) + if (obj is not DynamicViscosity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(DynamicViscosity other, DynamicViscosity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(DynamicViscosity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current DynamicViscosity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(DynamicViscosity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is DynamicViscosity otherQuantity)) throw new ArgumentException("Expected type DynamicViscosity.", nameof(obj)); + if (obj is not DynamicViscosity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -760,164 +720,24 @@ public int CompareTo(object? obj) /// public int CompareTo(DynamicViscosity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(DynamicViscosityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this DynamicViscosity to another DynamicViscosity with the unit representation . - /// - /// The unit to convert to. - /// A DynamicViscosity with the specified unit. - public DynamicViscosity ToUnit(DynamicViscosityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A DynamicViscosity with the specified unit. - public DynamicViscosity ToUnit(DynamicViscosityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(DynamicViscosity), Unit, typeof(DynamicViscosity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (DynamicViscosity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(DynamicViscosityUnit unit, [NotNullWhen(true)] out DynamicViscosity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - DynamicViscosity? convertedOrNull = (Unit, unit) switch - { - // DynamicViscosityUnit -> BaseUnit - (DynamicViscosityUnit.Centipoise, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity((_value / 10) * 1e-2d, DynamicViscosityUnit.NewtonSecondPerMeterSquared), - (DynamicViscosityUnit.MicropascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity((_value) * 1e-6d, DynamicViscosityUnit.NewtonSecondPerMeterSquared), - (DynamicViscosityUnit.MillipascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity((_value) * 1e-3d, DynamicViscosityUnit.NewtonSecondPerMeterSquared), - (DynamicViscosityUnit.PascalSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity(_value, DynamicViscosityUnit.NewtonSecondPerMeterSquared), - (DynamicViscosityUnit.Poise, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity(_value / 10, DynamicViscosityUnit.NewtonSecondPerMeterSquared), - (DynamicViscosityUnit.PoundForceSecondPerSquareFoot, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity(_value * 4.4482216152605 / 9.290304e-2, DynamicViscosityUnit.NewtonSecondPerMeterSquared), - (DynamicViscosityUnit.PoundForceSecondPerSquareInch, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity(_value * 4.4482216152605 / 0.00064516, DynamicViscosityUnit.NewtonSecondPerMeterSquared), - (DynamicViscosityUnit.PoundPerFootSecond, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity(_value * 0.45359237 / 0.3048, DynamicViscosityUnit.NewtonSecondPerMeterSquared), - (DynamicViscosityUnit.Reyn, DynamicViscosityUnit.NewtonSecondPerMeterSquared) => new DynamicViscosity(_value * 4.4482216152605 / 0.00064516, DynamicViscosityUnit.NewtonSecondPerMeterSquared), - - // BaseUnit -> DynamicViscosityUnit - (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Centipoise) => new DynamicViscosity((_value * 10) / 1e-2d, DynamicViscosityUnit.Centipoise), - (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.MicropascalSecond) => new DynamicViscosity((_value) / 1e-6d, DynamicViscosityUnit.MicropascalSecond), - (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.MillipascalSecond) => new DynamicViscosity((_value) / 1e-3d, DynamicViscosityUnit.MillipascalSecond), - (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PascalSecond) => new DynamicViscosity(_value, DynamicViscosityUnit.PascalSecond), - (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Poise) => new DynamicViscosity(_value * 10, DynamicViscosityUnit.Poise), - (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundForceSecondPerSquareFoot) => new DynamicViscosity(_value * 9.290304e-2 / 4.4482216152605, DynamicViscosityUnit.PoundForceSecondPerSquareFoot), - (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundForceSecondPerSquareInch) => new DynamicViscosity(_value * 0.00064516 / 4.4482216152605, DynamicViscosityUnit.PoundForceSecondPerSquareInch), - (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.PoundPerFootSecond) => new DynamicViscosity(_value * 0.3048 / 0.45359237, DynamicViscosityUnit.PoundPerFootSecond), - (DynamicViscosityUnit.NewtonSecondPerMeterSquared, DynamicViscosityUnit.Reyn) => new DynamicViscosity(_value * 0.00064516 / 4.4482216152605, DynamicViscosityUnit.Reyn), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public DynamicViscosity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not DynamicViscosityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(DynamicViscosityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(DynamicViscosityUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(DynamicViscosityUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -932,7 +752,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs index 30e7fa91cc..4f154d8406 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricAdmittance.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,7 +37,8 @@ namespace UnitsNet /// [Obsolete("Admittance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricConductance or ElectricSusceptance instead.")] [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricAdmittance : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -54,13 +53,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricAdmittanceUnit? _unit; /// @@ -105,7 +104,7 @@ public static ElectricAdmittanceInfo CreateDefault(Func - /// The for is [T^3][L^-2][M^-1][I^2]. + /// The for is T^3L^-2M^-1I^2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); @@ -120,30 +119,58 @@ public static ElectricAdmittanceInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricAdmittance. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricAdmittanceUnit.Gigamho, "Gigamho", "Gigamhos", BaseUnits.Undefined); - yield return new (ElectricAdmittanceUnit.Gigasiemens, "Gigasiemens", "Gigasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricAdmittanceUnit.Kilomho, "Kilomho", "Kilomhos", BaseUnits.Undefined); - yield return new (ElectricAdmittanceUnit.Kilosiemens, "Kilosiemens", "Kilosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricAdmittanceUnit.Megamho, "Megamho", "Megamhos", BaseUnits.Undefined); - yield return new (ElectricAdmittanceUnit.Megasiemens, "Megasiemens", "Megasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricAdmittanceUnit.Mho, "Mho", "Mhos", BaseUnits.Undefined); - yield return new (ElectricAdmittanceUnit.Micromho, "Micromho", "Micromhos", BaseUnits.Undefined); - yield return new (ElectricAdmittanceUnit.Microsiemens, "Microsiemens", "Microsiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere)); - yield return new (ElectricAdmittanceUnit.Millimho, "Millimho", "Millimhos", BaseUnits.Undefined); - yield return new (ElectricAdmittanceUnit.Millisiemens, "Millisiemens", "Millisiemens", BaseUnits.Undefined); - yield return new (ElectricAdmittanceUnit.Nanomho, "Nanomho", "Nanomhos", BaseUnits.Undefined); - yield return new (ElectricAdmittanceUnit.Nanosiemens, "Nanosiemens", "Nanosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricAdmittanceUnit.Gigamho, "Gigamho", "Gigamhos", BaseUnits.Undefined, + new QuantityValue(1, 1000000000) + ); + yield return new (ElectricAdmittanceUnit.Gigasiemens, "Gigasiemens", "Gigasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000000) + ); + yield return new (ElectricAdmittanceUnit.Kilomho, "Kilomho", "Kilomhos", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (ElectricAdmittanceUnit.Kilosiemens, "Kilosiemens", "Kilosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000) + ); + yield return new (ElectricAdmittanceUnit.Megamho, "Megamho", "Megamhos", BaseUnits.Undefined, + new QuantityValue(1, 1000000) + ); + yield return new (ElectricAdmittanceUnit.Megasiemens, "Megasiemens", "Megasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000) + ); + yield return new (ElectricAdmittanceUnit.Mho, "Mho", "Mhos", BaseUnits.Undefined, + 1 + ); + yield return new (ElectricAdmittanceUnit.Micromho, "Micromho", "Micromhos", BaseUnits.Undefined, + 1000000 + ); + yield return new (ElectricAdmittanceUnit.Microsiemens, "Microsiemens", "Microsiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), + 1000000 + ); + yield return new (ElectricAdmittanceUnit.Millimho, "Millimho", "Millimhos", BaseUnits.Undefined, + 1000 + ); + yield return new (ElectricAdmittanceUnit.Millisiemens, "Millisiemens", "Millisiemens", BaseUnits.Undefined, + 1000 + ); + yield return new (ElectricAdmittanceUnit.Nanomho, "Nanomho", "Nanomhos", BaseUnits.Undefined, + 1000000000 + ); + yield return new (ElectricAdmittanceUnit.Nanosiemens, "Nanosiemens", "Nanosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere), + 1000000000 + ); yield return new (ElectricAdmittanceUnit.Siemens, "Siemens", "Siemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricAdmittanceUnit.Teramho, "Teramho", "Teramhos", BaseUnits.Undefined); - yield return new (ElectricAdmittanceUnit.Terasiemens, "Terasiemens", "Terasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricAdmittanceUnit.Teramho, "Teramho", "Teramhos", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000) + ); + yield return new (ElectricAdmittanceUnit.Terasiemens, "Terasiemens", "Terasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000000000) + ); } } static ElectricAdmittance() { - Info = ElectricAdmittanceInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricAdmittanceInfo.CreateDefault); } /// @@ -151,7 +178,7 @@ static ElectricAdmittance() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricAdmittance(double value, ElectricAdmittanceUnit unit) + public ElectricAdmittance(QuantityValue value, ElectricAdmittanceUnit unit) { _value = value; _unit = unit; @@ -165,7 +192,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -176,7 +203,8 @@ public ElectricAdmittance(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -205,10 +233,8 @@ public ElectricAdmittance(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricAdmittanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -247,133 +273,89 @@ public ElectricAdmittance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigamhos => As(ElectricAdmittanceUnit.Gigamho); + public QuantityValue Gigamhos => this.As(ElectricAdmittanceUnit.Gigamho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigasiemens => As(ElectricAdmittanceUnit.Gigasiemens); + public QuantityValue Gigasiemens => this.As(ElectricAdmittanceUnit.Gigasiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilomhos => As(ElectricAdmittanceUnit.Kilomho); + public QuantityValue Kilomhos => this.As(ElectricAdmittanceUnit.Kilomho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilosiemens => As(ElectricAdmittanceUnit.Kilosiemens); + public QuantityValue Kilosiemens => this.As(ElectricAdmittanceUnit.Kilosiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megamhos => As(ElectricAdmittanceUnit.Megamho); + public QuantityValue Megamhos => this.As(ElectricAdmittanceUnit.Megamho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megasiemens => As(ElectricAdmittanceUnit.Megasiemens); + public QuantityValue Megasiemens => this.As(ElectricAdmittanceUnit.Megasiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Mhos => As(ElectricAdmittanceUnit.Mho); + public QuantityValue Mhos => this.As(ElectricAdmittanceUnit.Mho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Micromhos => As(ElectricAdmittanceUnit.Micromho); + public QuantityValue Micromhos => this.As(ElectricAdmittanceUnit.Micromho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microsiemens => As(ElectricAdmittanceUnit.Microsiemens); + public QuantityValue Microsiemens => this.As(ElectricAdmittanceUnit.Microsiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millimhos => As(ElectricAdmittanceUnit.Millimho); + public QuantityValue Millimhos => this.As(ElectricAdmittanceUnit.Millimho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millisiemens => As(ElectricAdmittanceUnit.Millisiemens); + public QuantityValue Millisiemens => this.As(ElectricAdmittanceUnit.Millisiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanomhos => As(ElectricAdmittanceUnit.Nanomho); + public QuantityValue Nanomhos => this.As(ElectricAdmittanceUnit.Nanomho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanosiemens => As(ElectricAdmittanceUnit.Nanosiemens); + public QuantityValue Nanosiemens => this.As(ElectricAdmittanceUnit.Nanosiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Siemens => As(ElectricAdmittanceUnit.Siemens); + public QuantityValue Siemens => this.As(ElectricAdmittanceUnit.Siemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Teramhos => As(ElectricAdmittanceUnit.Teramho); + public QuantityValue Teramhos => this.As(ElectricAdmittanceUnit.Teramho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Terasiemens => As(ElectricAdmittanceUnit.Terasiemens); + public QuantityValue Terasiemens => this.As(ElectricAdmittanceUnit.Terasiemens); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricAdmittanceUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Gigamho, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Gigasiemens, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Kilomho, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Kilosiemens, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Megamho, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Megasiemens, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Mho, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Micromho, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Microsiemens, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Millimho, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Millisiemens, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Nanomho, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Nanosiemens, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Teramho, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Terasiemens, ElectricAdmittanceUnit.Siemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Siemens)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Siemens, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricAdmittanceUnit - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Gigamho, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Gigamho)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Gigasiemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Gigasiemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Kilomho, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Kilomho)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Kilosiemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Kilosiemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Megamho, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Megamho)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Megasiemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Megasiemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Mho, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Mho)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Micromho, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Micromho)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Microsiemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Microsiemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Millimho, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Millimho)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Millisiemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Millisiemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Nanomho, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Nanomho)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Nanosiemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Nanosiemens)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Teramho, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Teramho)); - unitConverter.SetConversionFunction(ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Terasiemens, quantity => quantity.ToUnit(ElectricAdmittanceUnit.Terasiemens)); - } - /// /// Get unit abbreviation string. /// @@ -402,7 +384,7 @@ public static string GetAbbreviation(ElectricAdmittanceUnit unit, IFormatProvide /// /// Creates a from . /// - public static ElectricAdmittance FromGigamhos(double value) + public static ElectricAdmittance FromGigamhos(QuantityValue value) { return new ElectricAdmittance(value, ElectricAdmittanceUnit.Gigamho); } @@ -410,7 +392,7 @@ public static ElectricAdmittance FromGigamhos(double value) /// /// Creates a from . /// - public static ElectricAdmittance FromGigasiemens(double value) + public static ElectricAdmittance FromGigasiemens(QuantityValue value) { return new ElectricAdmittance(value, ElectricAdmittanceUnit.Gigasiemens); } @@ -418,7 +400,7 @@ public static ElectricAdmittance FromGigasiemens(double value) /// /// Creates a from . /// - public static ElectricAdmittance FromKilomhos(double value) + public static ElectricAdmittance FromKilomhos(QuantityValue value) { return new ElectricAdmittance(value, ElectricAdmittanceUnit.Kilomho); } @@ -426,7 +408,7 @@ public static ElectricAdmittance FromKilomhos(double value) /// /// Creates a from . /// - public static ElectricAdmittance FromKilosiemens(double value) + public static ElectricAdmittance FromKilosiemens(QuantityValue value) { return new ElectricAdmittance(value, ElectricAdmittanceUnit.Kilosiemens); } @@ -434,7 +416,7 @@ public static ElectricAdmittance FromKilosiemens(double value) /// /// Creates a from . /// - public static ElectricAdmittance FromMegamhos(double value) + public static ElectricAdmittance FromMegamhos(QuantityValue value) { return new ElectricAdmittance(value, ElectricAdmittanceUnit.Megamho); } @@ -442,7 +424,7 @@ public static ElectricAdmittance FromMegamhos(double value) /// /// Creates a from . /// - public static ElectricAdmittance FromMegasiemens(double value) + public static ElectricAdmittance FromMegasiemens(QuantityValue value) { return new ElectricAdmittance(value, ElectricAdmittanceUnit.Megasiemens); } @@ -450,7 +432,7 @@ public static ElectricAdmittance FromMegasiemens(double value) /// /// Creates a from . /// - public static ElectricAdmittance FromMhos(double value) + public static ElectricAdmittance FromMhos(QuantityValue value) { return new ElectricAdmittance(value, ElectricAdmittanceUnit.Mho); } @@ -458,7 +440,7 @@ public static ElectricAdmittance FromMhos(double value) /// /// Creates a from . /// - public static ElectricAdmittance FromMicromhos(double value) + public static ElectricAdmittance FromMicromhos(QuantityValue value) { return new ElectricAdmittance(value, ElectricAdmittanceUnit.Micromho); } @@ -466,7 +448,7 @@ public static ElectricAdmittance FromMicromhos(double value) /// /// Creates a from . /// - public static ElectricAdmittance FromMicrosiemens(double value) + public static ElectricAdmittance FromMicrosiemens(QuantityValue value) { return new ElectricAdmittance(value, ElectricAdmittanceUnit.Microsiemens); } @@ -474,7 +456,7 @@ public static ElectricAdmittance FromMicrosiemens(double value) /// /// Creates a from . /// - public static ElectricAdmittance FromMillimhos(double value) + public static ElectricAdmittance FromMillimhos(QuantityValue value) { return new ElectricAdmittance(value, ElectricAdmittanceUnit.Millimho); } @@ -482,7 +464,7 @@ public static ElectricAdmittance FromMillimhos(double value) /// /// Creates a from . /// - public static ElectricAdmittance FromMillisiemens(double value) + public static ElectricAdmittance FromMillisiemens(QuantityValue value) { return new ElectricAdmittance(value, ElectricAdmittanceUnit.Millisiemens); } @@ -490,7 +472,7 @@ public static ElectricAdmittance FromMillisiemens(double value) /// /// Creates a from . /// - public static ElectricAdmittance FromNanomhos(double value) + public static ElectricAdmittance FromNanomhos(QuantityValue value) { return new ElectricAdmittance(value, ElectricAdmittanceUnit.Nanomho); } @@ -498,7 +480,7 @@ public static ElectricAdmittance FromNanomhos(double value) /// /// Creates a from . /// - public static ElectricAdmittance FromNanosiemens(double value) + public static ElectricAdmittance FromNanosiemens(QuantityValue value) { return new ElectricAdmittance(value, ElectricAdmittanceUnit.Nanosiemens); } @@ -506,7 +488,7 @@ public static ElectricAdmittance FromNanosiemens(double value) /// /// Creates a from . /// - public static ElectricAdmittance FromSiemens(double value) + public static ElectricAdmittance FromSiemens(QuantityValue value) { return new ElectricAdmittance(value, ElectricAdmittanceUnit.Siemens); } @@ -514,7 +496,7 @@ public static ElectricAdmittance FromSiemens(double value) /// /// Creates a from . /// - public static ElectricAdmittance FromTeramhos(double value) + public static ElectricAdmittance FromTeramhos(QuantityValue value) { return new ElectricAdmittance(value, ElectricAdmittanceUnit.Teramho); } @@ -522,7 +504,7 @@ public static ElectricAdmittance FromTeramhos(double value) /// /// Creates a from . /// - public static ElectricAdmittance FromTerasiemens(double value) + public static ElectricAdmittance FromTerasiemens(QuantityValue value) { return new ElectricAdmittance(value, ElectricAdmittanceUnit.Terasiemens); } @@ -533,7 +515,7 @@ public static ElectricAdmittance FromTerasiemens(double value) /// Value to convert from. /// Unit to convert from. /// ElectricAdmittance unit value. - public static ElectricAdmittance From(double value, ElectricAdmittanceUnit fromUnit) + public static ElectricAdmittance From(QuantityValue value, ElectricAdmittanceUnit fromUnit) { return new ElectricAdmittance(value, fromUnit); } @@ -594,10 +576,7 @@ public static ElectricAdmittance Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricAdmittance Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -625,11 +604,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricAdmittan /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricAdmittance result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -650,7 +625,7 @@ public static ElectricAdmittanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -661,7 +636,7 @@ public static ElectricAdmittanceUnit ParseUnit(string str, IFormatProvider? prov return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricAdmittanceUnit unit) { return TryParseUnit(str, null, out unit); @@ -676,7 +651,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricAdmi /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricAdmittanceUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -695,35 +670,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricAdmittance operator +(ElectricAdmittance left, ElectricAdmittance right) { - return new ElectricAdmittance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricAdmittance(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricAdmittance operator -(ElectricAdmittance left, ElectricAdmittance right) { - return new ElectricAdmittance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricAdmittance(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -735,97 +710,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricAdmittance left, ElectricAdmittance right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricAdmittance left, ElectricAdmittance right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricAdmittance left, ElectricAdmittance right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricAdmittance left, ElectricAdmittance right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricAdmittance other, ElectricAdmittance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricAdmittance left, ElectricAdmittance right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricAdmittance other, ElectricAdmittance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricAdmittance left, ElectricAdmittance right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricAdmittance other, ElectricAdmittance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricAdmittance otherQuantity)) + if (obj is not ElectricAdmittance otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricAdmittance other, ElectricAdmittance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricAdmittance other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricAdmittance. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricAdmittance), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricAdmittance otherQuantity)) throw new ArgumentException("Expected type ElectricAdmittance.", nameof(obj)); + if (obj is not ElectricAdmittance otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -837,176 +797,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricAdmittance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricAdmittanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this ElectricAdmittance to another ElectricAdmittance with the unit representation . - /// - /// The unit to convert to. - /// A ElectricAdmittance with the specified unit. - public ElectricAdmittance ToUnit(ElectricAdmittanceUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricAdmittance with the specified unit. - public ElectricAdmittance ToUnit(ElectricAdmittanceUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricAdmittance), Unit, typeof(ElectricAdmittance), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricAdmittance)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricAdmittanceUnit unit, [NotNullWhen(true)] out ElectricAdmittance? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricAdmittance? convertedOrNull = (Unit, unit) switch - { - // ElectricAdmittanceUnit -> BaseUnit - (ElectricAdmittanceUnit.Gigamho, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance((_value) * 1e9d, ElectricAdmittanceUnit.Siemens), - (ElectricAdmittanceUnit.Gigasiemens, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance((_value) * 1e9d, ElectricAdmittanceUnit.Siemens), - (ElectricAdmittanceUnit.Kilomho, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance((_value) * 1e3d, ElectricAdmittanceUnit.Siemens), - (ElectricAdmittanceUnit.Kilosiemens, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance((_value) * 1e3d, ElectricAdmittanceUnit.Siemens), - (ElectricAdmittanceUnit.Megamho, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance((_value) * 1e6d, ElectricAdmittanceUnit.Siemens), - (ElectricAdmittanceUnit.Megasiemens, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance((_value) * 1e6d, ElectricAdmittanceUnit.Siemens), - (ElectricAdmittanceUnit.Mho, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance(_value, ElectricAdmittanceUnit.Siemens), - (ElectricAdmittanceUnit.Micromho, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance((_value) * 1e-6d, ElectricAdmittanceUnit.Siemens), - (ElectricAdmittanceUnit.Microsiemens, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance((_value) * 1e-6d, ElectricAdmittanceUnit.Siemens), - (ElectricAdmittanceUnit.Millimho, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance((_value) * 1e-3d, ElectricAdmittanceUnit.Siemens), - (ElectricAdmittanceUnit.Millisiemens, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance((_value) * 1e-3d, ElectricAdmittanceUnit.Siemens), - (ElectricAdmittanceUnit.Nanomho, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance((_value) * 1e-9d, ElectricAdmittanceUnit.Siemens), - (ElectricAdmittanceUnit.Nanosiemens, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance((_value) * 1e-9d, ElectricAdmittanceUnit.Siemens), - (ElectricAdmittanceUnit.Teramho, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance((_value) * 1e12d, ElectricAdmittanceUnit.Siemens), - (ElectricAdmittanceUnit.Terasiemens, ElectricAdmittanceUnit.Siemens) => new ElectricAdmittance((_value) * 1e12d, ElectricAdmittanceUnit.Siemens), - - // BaseUnit -> ElectricAdmittanceUnit - (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Gigamho) => new ElectricAdmittance((_value) / 1e9d, ElectricAdmittanceUnit.Gigamho), - (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Gigasiemens) => new ElectricAdmittance((_value) / 1e9d, ElectricAdmittanceUnit.Gigasiemens), - (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Kilomho) => new ElectricAdmittance((_value) / 1e3d, ElectricAdmittanceUnit.Kilomho), - (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Kilosiemens) => new ElectricAdmittance((_value) / 1e3d, ElectricAdmittanceUnit.Kilosiemens), - (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Megamho) => new ElectricAdmittance((_value) / 1e6d, ElectricAdmittanceUnit.Megamho), - (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Megasiemens) => new ElectricAdmittance((_value) / 1e6d, ElectricAdmittanceUnit.Megasiemens), - (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Mho) => new ElectricAdmittance(_value, ElectricAdmittanceUnit.Mho), - (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Micromho) => new ElectricAdmittance((_value) / 1e-6d, ElectricAdmittanceUnit.Micromho), - (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Microsiemens) => new ElectricAdmittance((_value) / 1e-6d, ElectricAdmittanceUnit.Microsiemens), - (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Millimho) => new ElectricAdmittance((_value) / 1e-3d, ElectricAdmittanceUnit.Millimho), - (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Millisiemens) => new ElectricAdmittance((_value) / 1e-3d, ElectricAdmittanceUnit.Millisiemens), - (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Nanomho) => new ElectricAdmittance((_value) / 1e-9d, ElectricAdmittanceUnit.Nanomho), - (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Nanosiemens) => new ElectricAdmittance((_value) / 1e-9d, ElectricAdmittanceUnit.Nanosiemens), - (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Teramho) => new ElectricAdmittance((_value) / 1e12d, ElectricAdmittanceUnit.Teramho), - (ElectricAdmittanceUnit.Siemens, ElectricAdmittanceUnit.Terasiemens) => new ElectricAdmittance((_value) / 1e12d, ElectricAdmittanceUnit.Terasiemens), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricAdmittance ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricAdmittanceUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricAdmittanceUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ElectricAdmittanceUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricAdmittanceUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1021,7 +829,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricApparentEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricApparentEnergy.g.cs index 914f9d6380..46ea4297ef 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricApparentEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricApparentEnergy.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricApparentEnergy : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricApparentEnergyUnit? _unit; /// @@ -101,7 +100,7 @@ public static ElectricApparentEnergyInfo CreateDefault(Func - /// The for is [T^-2][L^2][M]. + /// The for is T^-2L^2M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); @@ -116,17 +115,19 @@ public static ElectricApparentEnergyInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricApparentEnergy. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricApparentEnergyUnit.KilovoltampereHour, "KilovoltampereHour", "KilovoltampereHours", BaseUnits.Undefined); - yield return new (ElectricApparentEnergyUnit.MegavoltampereHour, "MegavoltampereHour", "MegavoltampereHours", BaseUnits.Undefined); + yield return new (ElectricApparentEnergyUnit.KilovoltampereHour, "KilovoltampereHour", "KilovoltampereHours", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (ElectricApparentEnergyUnit.MegavoltampereHour, "MegavoltampereHour", "MegavoltampereHours", BaseUnits.Undefined, + new QuantityValue(1, 1000000) + ); yield return new (ElectricApparentEnergyUnit.VoltampereHour, "VoltampereHour", "VoltampereHours", BaseUnits.Undefined); } } static ElectricApparentEnergy() { - Info = ElectricApparentEnergyInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricApparentEnergyInfo.CreateDefault); } /// @@ -134,7 +135,7 @@ static ElectricApparentEnergy() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricApparentEnergy(double value, ElectricApparentEnergyUnit unit) + public ElectricApparentEnergy(QuantityValue value, ElectricApparentEnergyUnit unit) { _value = value; _unit = unit; @@ -148,7 +149,7 @@ public ElectricApparentEnergy(double value, ElectricApparentEnergyUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricApparentEnergy(double value, UnitSystem unitSystem) + public ElectricApparentEnergy(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -159,7 +160,8 @@ public ElectricApparentEnergy(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -188,10 +190,8 @@ public ElectricApparentEnergy(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricApparentEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -230,42 +230,24 @@ public ElectricApparentEnergy(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilovoltampereHours => As(ElectricApparentEnergyUnit.KilovoltampereHour); + public QuantityValue KilovoltampereHours => this.As(ElectricApparentEnergyUnit.KilovoltampereHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegavoltampereHours => As(ElectricApparentEnergyUnit.MegavoltampereHour); + public QuantityValue MegavoltampereHours => this.As(ElectricApparentEnergyUnit.MegavoltampereHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double VoltampereHours => As(ElectricApparentEnergyUnit.VoltampereHour); + public QuantityValue VoltampereHours => this.As(ElectricApparentEnergyUnit.VoltampereHour); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricApparentEnergyUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricApparentEnergyUnit.KilovoltampereHour, ElectricApparentEnergyUnit.VoltampereHour, quantity => quantity.ToUnit(ElectricApparentEnergyUnit.VoltampereHour)); - unitConverter.SetConversionFunction(ElectricApparentEnergyUnit.MegavoltampereHour, ElectricApparentEnergyUnit.VoltampereHour, quantity => quantity.ToUnit(ElectricApparentEnergyUnit.VoltampereHour)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricApparentEnergyUnit.VoltampereHour, ElectricApparentEnergyUnit.VoltampereHour, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricApparentEnergyUnit - unitConverter.SetConversionFunction(ElectricApparentEnergyUnit.VoltampereHour, ElectricApparentEnergyUnit.KilovoltampereHour, quantity => quantity.ToUnit(ElectricApparentEnergyUnit.KilovoltampereHour)); - unitConverter.SetConversionFunction(ElectricApparentEnergyUnit.VoltampereHour, ElectricApparentEnergyUnit.MegavoltampereHour, quantity => quantity.ToUnit(ElectricApparentEnergyUnit.MegavoltampereHour)); - } - /// /// Get unit abbreviation string. /// @@ -294,7 +276,7 @@ public static string GetAbbreviation(ElectricApparentEnergyUnit unit, IFormatPro /// /// Creates a from . /// - public static ElectricApparentEnergy FromKilovoltampereHours(double value) + public static ElectricApparentEnergy FromKilovoltampereHours(QuantityValue value) { return new ElectricApparentEnergy(value, ElectricApparentEnergyUnit.KilovoltampereHour); } @@ -302,7 +284,7 @@ public static ElectricApparentEnergy FromKilovoltampereHours(double value) /// /// Creates a from . /// - public static ElectricApparentEnergy FromMegavoltampereHours(double value) + public static ElectricApparentEnergy FromMegavoltampereHours(QuantityValue value) { return new ElectricApparentEnergy(value, ElectricApparentEnergyUnit.MegavoltampereHour); } @@ -310,7 +292,7 @@ public static ElectricApparentEnergy FromMegavoltampereHours(double value) /// /// Creates a from . /// - public static ElectricApparentEnergy FromVoltampereHours(double value) + public static ElectricApparentEnergy FromVoltampereHours(QuantityValue value) { return new ElectricApparentEnergy(value, ElectricApparentEnergyUnit.VoltampereHour); } @@ -321,7 +303,7 @@ public static ElectricApparentEnergy FromVoltampereHours(double value) /// Value to convert from. /// Unit to convert from. /// ElectricApparentEnergy unit value. - public static ElectricApparentEnergy From(double value, ElectricApparentEnergyUnit fromUnit) + public static ElectricApparentEnergy From(QuantityValue value, ElectricApparentEnergyUnit fromUnit) { return new ElectricApparentEnergy(value, fromUnit); } @@ -382,10 +364,7 @@ public static ElectricApparentEnergy Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricApparentEnergy Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -413,11 +392,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricApparent /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricApparentEnergy result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -438,7 +413,7 @@ public static ElectricApparentEnergyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -449,7 +424,7 @@ public static ElectricApparentEnergyUnit ParseUnit(string str, IFormatProvider? return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricApparentEnergyUnit unit) { return TryParseUnit(str, null, out unit); @@ -464,7 +439,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricAppa /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricApparentEnergyUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -483,35 +458,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricApparentEnergy operator +(ElectricApparentEnergy left, ElectricApparentEnergy right) { - return new ElectricApparentEnergy(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricApparentEnergy(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricApparentEnergy operator -(ElectricApparentEnergy left, ElectricApparentEnergy right) { - return new ElectricApparentEnergy(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricApparentEnergy(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static ElectricApparentEnergy operator *(double left, ElectricApparentEnergy right) + public static ElectricApparentEnergy operator *(QuantityValue left, ElectricApparentEnergy right) { return new ElectricApparentEnergy(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricApparentEnergy operator *(ElectricApparentEnergy left, double right) + public static ElectricApparentEnergy operator *(ElectricApparentEnergy left, QuantityValue right) { return new ElectricApparentEnergy(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricApparentEnergy operator /(ElectricApparentEnergy left, double right) + public static ElectricApparentEnergy operator /(ElectricApparentEnergy left, QuantityValue right) { return new ElectricApparentEnergy(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricApparentEnergy left, ElectricApparentEnergy right) + public static QuantityValue operator /(ElectricApparentEnergy left, ElectricApparentEnergy right) { return left.VoltampereHours / right.VoltampereHours; } @@ -523,97 +498,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricApparentEnergy left, ElectricApparentEnergy right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricApparentEnergy left, ElectricApparentEnergy right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricApparentEnergy left, ElectricApparentEnergy right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricApparentEnergy left, ElectricApparentEnergy right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricApparentEnergy other, ElectricApparentEnergy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricApparentEnergy left, ElectricApparentEnergy right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricApparentEnergy other, ElectricApparentEnergy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricApparentEnergy left, ElectricApparentEnergy right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricApparentEnergy other, ElectricApparentEnergy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricApparentEnergy otherQuantity)) + if (obj is not ElectricApparentEnergy otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricApparentEnergy other, ElectricApparentEnergy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricApparentEnergy other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricApparentEnergy. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricApparentEnergy), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricApparentEnergy otherQuantity)) throw new ArgumentException("Expected type ElectricApparentEnergy.", nameof(obj)); + if (obj is not ElectricApparentEnergy otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -625,150 +585,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricApparentEnergy other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricApparentEnergyUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this ElectricApparentEnergy to another ElectricApparentEnergy with the unit representation . - /// - /// The unit to convert to. - /// A ElectricApparentEnergy with the specified unit. - public ElectricApparentEnergy ToUnit(ElectricApparentEnergyUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricApparentEnergy with the specified unit. - public ElectricApparentEnergy ToUnit(ElectricApparentEnergyUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricApparentEnergy), Unit, typeof(ElectricApparentEnergy), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricApparentEnergy)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricApparentEnergyUnit unit, [NotNullWhen(true)] out ElectricApparentEnergy? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricApparentEnergy? convertedOrNull = (Unit, unit) switch - { - // ElectricApparentEnergyUnit -> BaseUnit - (ElectricApparentEnergyUnit.KilovoltampereHour, ElectricApparentEnergyUnit.VoltampereHour) => new ElectricApparentEnergy((_value) * 1e3d, ElectricApparentEnergyUnit.VoltampereHour), - (ElectricApparentEnergyUnit.MegavoltampereHour, ElectricApparentEnergyUnit.VoltampereHour) => new ElectricApparentEnergy((_value) * 1e6d, ElectricApparentEnergyUnit.VoltampereHour), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> ElectricApparentEnergyUnit - (ElectricApparentEnergyUnit.VoltampereHour, ElectricApparentEnergyUnit.KilovoltampereHour) => new ElectricApparentEnergy((_value) / 1e3d, ElectricApparentEnergyUnit.KilovoltampereHour), - (ElectricApparentEnergyUnit.VoltampereHour, ElectricApparentEnergyUnit.MegavoltampereHour) => new ElectricApparentEnergy((_value) / 1e6d, ElectricApparentEnergyUnit.MegavoltampereHour), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricApparentEnergy ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricApparentEnergyUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricApparentEnergyUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ElectricApparentEnergyUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricApparentEnergyUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricApparentEnergyUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(ElectricApparentEnergyUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -783,7 +617,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricApparentPower.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricApparentPower.g.cs index 6a23a7aa8f..e882e19426 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricApparentPower.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricApparentPower.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/AC_power#Active,_reactive,_apparent,_and_complex_power_in_sinusoidal_steady-state /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricApparentPower : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricApparentPowerUnit? _unit; /// @@ -104,7 +103,7 @@ public static ElectricApparentPowerInfo CreateDefault(Func - /// The for is [T^-3][L^2][M]. + /// The for is T^-3L^2M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); @@ -119,20 +118,28 @@ public static ElectricApparentPowerInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricApparentPower. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricApparentPowerUnit.Gigavoltampere, "Gigavoltampere", "Gigavoltamperes", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond)); - yield return new (ElectricApparentPowerUnit.Kilovoltampere, "Kilovoltampere", "Kilovoltamperes", BaseUnits.Undefined); - yield return new (ElectricApparentPowerUnit.Megavoltampere, "Megavoltampere", "Megavoltamperes", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ElectricApparentPowerUnit.Microvoltampere, "Microvoltampere", "Microvoltamperes", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second)); - yield return new (ElectricApparentPowerUnit.Millivoltampere, "Millivoltampere", "Millivoltamperes", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second)); + yield return new (ElectricApparentPowerUnit.Gigavoltampere, "Gigavoltampere", "Gigavoltamperes", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond), + new QuantityValue(1, 1000000000) + ); + yield return new (ElectricApparentPowerUnit.Kilovoltampere, "Kilovoltampere", "Kilovoltamperes", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (ElectricApparentPowerUnit.Megavoltampere, "Megavoltampere", "Megavoltamperes", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (ElectricApparentPowerUnit.Microvoltampere, "Microvoltampere", "Microvoltamperes", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second), + 1000000 + ); + yield return new (ElectricApparentPowerUnit.Millivoltampere, "Millivoltampere", "Millivoltamperes", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second), + 1000 + ); yield return new (ElectricApparentPowerUnit.Voltampere, "Voltampere", "Voltamperes", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); } } static ElectricApparentPower() { - Info = ElectricApparentPowerInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricApparentPowerInfo.CreateDefault); } /// @@ -140,7 +147,7 @@ static ElectricApparentPower() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricApparentPower(double value, ElectricApparentPowerUnit unit) + public ElectricApparentPower(QuantityValue value, ElectricApparentPowerUnit unit) { _value = value; _unit = unit; @@ -154,7 +161,7 @@ public ElectricApparentPower(double value, ElectricApparentPowerUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricApparentPower(double value, UnitSystem unitSystem) + public ElectricApparentPower(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -165,7 +172,8 @@ public ElectricApparentPower(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -194,10 +202,8 @@ public ElectricApparentPower(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricApparentPowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -236,63 +242,39 @@ public ElectricApparentPower(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigavoltamperes => As(ElectricApparentPowerUnit.Gigavoltampere); + public QuantityValue Gigavoltamperes => this.As(ElectricApparentPowerUnit.Gigavoltampere); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilovoltamperes => As(ElectricApparentPowerUnit.Kilovoltampere); + public QuantityValue Kilovoltamperes => this.As(ElectricApparentPowerUnit.Kilovoltampere); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megavoltamperes => As(ElectricApparentPowerUnit.Megavoltampere); + public QuantityValue Megavoltamperes => this.As(ElectricApparentPowerUnit.Megavoltampere); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microvoltamperes => As(ElectricApparentPowerUnit.Microvoltampere); + public QuantityValue Microvoltamperes => this.As(ElectricApparentPowerUnit.Microvoltampere); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millivoltamperes => As(ElectricApparentPowerUnit.Millivoltampere); + public QuantityValue Millivoltamperes => this.As(ElectricApparentPowerUnit.Millivoltampere); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Voltamperes => As(ElectricApparentPowerUnit.Voltampere); + public QuantityValue Voltamperes => this.As(ElectricApparentPowerUnit.Voltampere); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricApparentPowerUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricApparentPowerUnit.Gigavoltampere, ElectricApparentPowerUnit.Voltampere, quantity => quantity.ToUnit(ElectricApparentPowerUnit.Voltampere)); - unitConverter.SetConversionFunction(ElectricApparentPowerUnit.Kilovoltampere, ElectricApparentPowerUnit.Voltampere, quantity => quantity.ToUnit(ElectricApparentPowerUnit.Voltampere)); - unitConverter.SetConversionFunction(ElectricApparentPowerUnit.Megavoltampere, ElectricApparentPowerUnit.Voltampere, quantity => quantity.ToUnit(ElectricApparentPowerUnit.Voltampere)); - unitConverter.SetConversionFunction(ElectricApparentPowerUnit.Microvoltampere, ElectricApparentPowerUnit.Voltampere, quantity => quantity.ToUnit(ElectricApparentPowerUnit.Voltampere)); - unitConverter.SetConversionFunction(ElectricApparentPowerUnit.Millivoltampere, ElectricApparentPowerUnit.Voltampere, quantity => quantity.ToUnit(ElectricApparentPowerUnit.Voltampere)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricApparentPowerUnit.Voltampere, ElectricApparentPowerUnit.Voltampere, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricApparentPowerUnit - unitConverter.SetConversionFunction(ElectricApparentPowerUnit.Voltampere, ElectricApparentPowerUnit.Gigavoltampere, quantity => quantity.ToUnit(ElectricApparentPowerUnit.Gigavoltampere)); - unitConverter.SetConversionFunction(ElectricApparentPowerUnit.Voltampere, ElectricApparentPowerUnit.Kilovoltampere, quantity => quantity.ToUnit(ElectricApparentPowerUnit.Kilovoltampere)); - unitConverter.SetConversionFunction(ElectricApparentPowerUnit.Voltampere, ElectricApparentPowerUnit.Megavoltampere, quantity => quantity.ToUnit(ElectricApparentPowerUnit.Megavoltampere)); - unitConverter.SetConversionFunction(ElectricApparentPowerUnit.Voltampere, ElectricApparentPowerUnit.Microvoltampere, quantity => quantity.ToUnit(ElectricApparentPowerUnit.Microvoltampere)); - unitConverter.SetConversionFunction(ElectricApparentPowerUnit.Voltampere, ElectricApparentPowerUnit.Millivoltampere, quantity => quantity.ToUnit(ElectricApparentPowerUnit.Millivoltampere)); - } - /// /// Get unit abbreviation string. /// @@ -321,7 +303,7 @@ public static string GetAbbreviation(ElectricApparentPowerUnit unit, IFormatProv /// /// Creates a from . /// - public static ElectricApparentPower FromGigavoltamperes(double value) + public static ElectricApparentPower FromGigavoltamperes(QuantityValue value) { return new ElectricApparentPower(value, ElectricApparentPowerUnit.Gigavoltampere); } @@ -329,7 +311,7 @@ public static ElectricApparentPower FromGigavoltamperes(double value) /// /// Creates a from . /// - public static ElectricApparentPower FromKilovoltamperes(double value) + public static ElectricApparentPower FromKilovoltamperes(QuantityValue value) { return new ElectricApparentPower(value, ElectricApparentPowerUnit.Kilovoltampere); } @@ -337,7 +319,7 @@ public static ElectricApparentPower FromKilovoltamperes(double value) /// /// Creates a from . /// - public static ElectricApparentPower FromMegavoltamperes(double value) + public static ElectricApparentPower FromMegavoltamperes(QuantityValue value) { return new ElectricApparentPower(value, ElectricApparentPowerUnit.Megavoltampere); } @@ -345,7 +327,7 @@ public static ElectricApparentPower FromMegavoltamperes(double value) /// /// Creates a from . /// - public static ElectricApparentPower FromMicrovoltamperes(double value) + public static ElectricApparentPower FromMicrovoltamperes(QuantityValue value) { return new ElectricApparentPower(value, ElectricApparentPowerUnit.Microvoltampere); } @@ -353,7 +335,7 @@ public static ElectricApparentPower FromMicrovoltamperes(double value) /// /// Creates a from . /// - public static ElectricApparentPower FromMillivoltamperes(double value) + public static ElectricApparentPower FromMillivoltamperes(QuantityValue value) { return new ElectricApparentPower(value, ElectricApparentPowerUnit.Millivoltampere); } @@ -361,7 +343,7 @@ public static ElectricApparentPower FromMillivoltamperes(double value) /// /// Creates a from . /// - public static ElectricApparentPower FromVoltamperes(double value) + public static ElectricApparentPower FromVoltamperes(QuantityValue value) { return new ElectricApparentPower(value, ElectricApparentPowerUnit.Voltampere); } @@ -372,7 +354,7 @@ public static ElectricApparentPower FromVoltamperes(double value) /// Value to convert from. /// Unit to convert from. /// ElectricApparentPower unit value. - public static ElectricApparentPower From(double value, ElectricApparentPowerUnit fromUnit) + public static ElectricApparentPower From(QuantityValue value, ElectricApparentPowerUnit fromUnit) { return new ElectricApparentPower(value, fromUnit); } @@ -433,10 +415,7 @@ public static ElectricApparentPower Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricApparentPower Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -464,11 +443,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricApparent /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricApparentPower result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -489,7 +464,7 @@ public static ElectricApparentPowerUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -500,7 +475,7 @@ public static ElectricApparentPowerUnit ParseUnit(string str, IFormatProvider? p return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricApparentPowerUnit unit) { return TryParseUnit(str, null, out unit); @@ -515,7 +490,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricAppa /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricApparentPowerUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -534,35 +509,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricApparentPower operator +(ElectricApparentPower left, ElectricApparentPower right) { - return new ElectricApparentPower(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricApparentPower(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricApparentPower operator -(ElectricApparentPower left, ElectricApparentPower right) { - return new ElectricApparentPower(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricApparentPower(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static ElectricApparentPower operator *(double left, ElectricApparentPower right) + public static ElectricApparentPower operator *(QuantityValue left, ElectricApparentPower right) { return new ElectricApparentPower(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricApparentPower operator *(ElectricApparentPower left, double right) + public static ElectricApparentPower operator *(ElectricApparentPower left, QuantityValue right) { return new ElectricApparentPower(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricApparentPower operator /(ElectricApparentPower left, double right) + public static ElectricApparentPower operator /(ElectricApparentPower left, QuantityValue right) { return new ElectricApparentPower(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricApparentPower left, ElectricApparentPower right) + public static QuantityValue operator /(ElectricApparentPower left, ElectricApparentPower right) { return left.Voltamperes / right.Voltamperes; } @@ -574,97 +549,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricApparentPower left, ElectricApparentPower right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricApparentPower left, ElectricApparentPower right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricApparentPower left, ElectricApparentPower right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricApparentPower left, ElectricApparentPower right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricApparentPower other, ElectricApparentPower tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricApparentPower left, ElectricApparentPower right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricApparentPower other, ElectricApparentPower tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricApparentPower left, ElectricApparentPower right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricApparentPower other, ElectricApparentPower tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricApparentPower otherQuantity)) + if (obj is not ElectricApparentPower otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricApparentPower other, ElectricApparentPower tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricApparentPower other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricApparentPower. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricApparentPower), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricApparentPower otherQuantity)) throw new ArgumentException("Expected type ElectricApparentPower.", nameof(obj)); + if (obj is not ElectricApparentPower otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -676,156 +636,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricApparentPower other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricApparentPowerUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this ElectricApparentPower to another ElectricApparentPower with the unit representation . - /// - /// The unit to convert to. - /// A ElectricApparentPower with the specified unit. - public ElectricApparentPower ToUnit(ElectricApparentPowerUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricApparentPower with the specified unit. - public ElectricApparentPower ToUnit(ElectricApparentPowerUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricApparentPower), Unit, typeof(ElectricApparentPower), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricApparentPower)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricApparentPowerUnit unit, [NotNullWhen(true)] out ElectricApparentPower? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricApparentPower? convertedOrNull = (Unit, unit) switch - { - // ElectricApparentPowerUnit -> BaseUnit - (ElectricApparentPowerUnit.Gigavoltampere, ElectricApparentPowerUnit.Voltampere) => new ElectricApparentPower((_value) * 1e9d, ElectricApparentPowerUnit.Voltampere), - (ElectricApparentPowerUnit.Kilovoltampere, ElectricApparentPowerUnit.Voltampere) => new ElectricApparentPower((_value) * 1e3d, ElectricApparentPowerUnit.Voltampere), - (ElectricApparentPowerUnit.Megavoltampere, ElectricApparentPowerUnit.Voltampere) => new ElectricApparentPower((_value) * 1e6d, ElectricApparentPowerUnit.Voltampere), - (ElectricApparentPowerUnit.Microvoltampere, ElectricApparentPowerUnit.Voltampere) => new ElectricApparentPower((_value) * 1e-6d, ElectricApparentPowerUnit.Voltampere), - (ElectricApparentPowerUnit.Millivoltampere, ElectricApparentPowerUnit.Voltampere) => new ElectricApparentPower((_value) * 1e-3d, ElectricApparentPowerUnit.Voltampere), - - // BaseUnit -> ElectricApparentPowerUnit - (ElectricApparentPowerUnit.Voltampere, ElectricApparentPowerUnit.Gigavoltampere) => new ElectricApparentPower((_value) / 1e9d, ElectricApparentPowerUnit.Gigavoltampere), - (ElectricApparentPowerUnit.Voltampere, ElectricApparentPowerUnit.Kilovoltampere) => new ElectricApparentPower((_value) / 1e3d, ElectricApparentPowerUnit.Kilovoltampere), - (ElectricApparentPowerUnit.Voltampere, ElectricApparentPowerUnit.Megavoltampere) => new ElectricApparentPower((_value) / 1e6d, ElectricApparentPowerUnit.Megavoltampere), - (ElectricApparentPowerUnit.Voltampere, ElectricApparentPowerUnit.Microvoltampere) => new ElectricApparentPower((_value) / 1e-6d, ElectricApparentPowerUnit.Microvoltampere), - (ElectricApparentPowerUnit.Voltampere, ElectricApparentPowerUnit.Millivoltampere) => new ElectricApparentPower((_value) / 1e-3d, ElectricApparentPowerUnit.Millivoltampere), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricApparentPower ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricApparentPowerUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricApparentPowerUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ElectricApparentPowerUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricApparentPowerUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ElectricApparentPowerUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricApparentPowerUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -840,7 +668,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCapacitance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCapacitance.g.cs index d3b195abdd..6babf0cf88 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCapacitance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCapacitance.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Capacitance /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricCapacitance : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricCapacitanceUnit? _unit; /// @@ -104,7 +103,7 @@ public static ElectricCapacitanceInfo CreateDefault(Func - /// The for is [T^4][L^-2][M^-1][I^2]. + /// The for is T^4L^-2M^-1I^2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, -1, 4, 2, 0, 0, 0); @@ -120,20 +119,30 @@ public static ElectricCapacitanceInfo CreateDefault(Func> GetDefaultMappings() { yield return new (ElectricCapacitanceUnit.Farad, "Farad", "Farads", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricCapacitanceUnit.Kilofarad, "Kilofarad", "Kilofarads", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricCapacitanceUnit.Megafarad, "Megafarad", "Megafarads", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricCapacitanceUnit.Microfarad, "Microfarad", "Microfarads", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere)); - yield return new (ElectricCapacitanceUnit.Millifarad, "Millifarad", "Millifarads", BaseUnits.Undefined); - yield return new (ElectricCapacitanceUnit.Nanofarad, "Nanofarad", "Nanofarads", BaseUnits.Undefined); - yield return new (ElectricCapacitanceUnit.Picofarad, "Picofarad", "Picofarads", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere)); + yield return new (ElectricCapacitanceUnit.Kilofarad, "Kilofarad", "Kilofarads", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000) + ); + yield return new (ElectricCapacitanceUnit.Megafarad, "Megafarad", "Megafarads", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000) + ); + yield return new (ElectricCapacitanceUnit.Microfarad, "Microfarad", "Microfarads", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), + 1000000 + ); + yield return new (ElectricCapacitanceUnit.Millifarad, "Millifarad", "Millifarads", BaseUnits.Undefined, + 1000 + ); + yield return new (ElectricCapacitanceUnit.Nanofarad, "Nanofarad", "Nanofarads", BaseUnits.Undefined, + 1000000000 + ); + yield return new (ElectricCapacitanceUnit.Picofarad, "Picofarad", "Picofarads", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere), + 1000000000000 + ); } } static ElectricCapacitance() { - Info = ElectricCapacitanceInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricCapacitanceInfo.CreateDefault); } /// @@ -141,7 +150,7 @@ static ElectricCapacitance() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricCapacitance(double value, ElectricCapacitanceUnit unit) + public ElectricCapacitance(QuantityValue value, ElectricCapacitanceUnit unit) { _value = value; _unit = unit; @@ -155,7 +164,7 @@ public ElectricCapacitance(double value, ElectricCapacitanceUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricCapacitance(double value, UnitSystem unitSystem) + public ElectricCapacitance(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -166,7 +175,8 @@ public ElectricCapacitance(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -195,10 +205,8 @@ public ElectricCapacitance(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricCapacitanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -237,70 +245,44 @@ public ElectricCapacitance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Farads => As(ElectricCapacitanceUnit.Farad); + public QuantityValue Farads => this.As(ElectricCapacitanceUnit.Farad); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilofarads => As(ElectricCapacitanceUnit.Kilofarad); + public QuantityValue Kilofarads => this.As(ElectricCapacitanceUnit.Kilofarad); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megafarads => As(ElectricCapacitanceUnit.Megafarad); + public QuantityValue Megafarads => this.As(ElectricCapacitanceUnit.Megafarad); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microfarads => As(ElectricCapacitanceUnit.Microfarad); + public QuantityValue Microfarads => this.As(ElectricCapacitanceUnit.Microfarad); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millifarads => As(ElectricCapacitanceUnit.Millifarad); + public QuantityValue Millifarads => this.As(ElectricCapacitanceUnit.Millifarad); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanofarads => As(ElectricCapacitanceUnit.Nanofarad); + public QuantityValue Nanofarads => this.As(ElectricCapacitanceUnit.Nanofarad); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Picofarads => As(ElectricCapacitanceUnit.Picofarad); + public QuantityValue Picofarads => this.As(ElectricCapacitanceUnit.Picofarad); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricCapacitanceUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricCapacitanceUnit.Kilofarad, ElectricCapacitanceUnit.Farad, quantity => quantity.ToUnit(ElectricCapacitanceUnit.Farad)); - unitConverter.SetConversionFunction(ElectricCapacitanceUnit.Megafarad, ElectricCapacitanceUnit.Farad, quantity => quantity.ToUnit(ElectricCapacitanceUnit.Farad)); - unitConverter.SetConversionFunction(ElectricCapacitanceUnit.Microfarad, ElectricCapacitanceUnit.Farad, quantity => quantity.ToUnit(ElectricCapacitanceUnit.Farad)); - unitConverter.SetConversionFunction(ElectricCapacitanceUnit.Millifarad, ElectricCapacitanceUnit.Farad, quantity => quantity.ToUnit(ElectricCapacitanceUnit.Farad)); - unitConverter.SetConversionFunction(ElectricCapacitanceUnit.Nanofarad, ElectricCapacitanceUnit.Farad, quantity => quantity.ToUnit(ElectricCapacitanceUnit.Farad)); - unitConverter.SetConversionFunction(ElectricCapacitanceUnit.Picofarad, ElectricCapacitanceUnit.Farad, quantity => quantity.ToUnit(ElectricCapacitanceUnit.Farad)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricCapacitanceUnit.Farad, ElectricCapacitanceUnit.Farad, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricCapacitanceUnit - unitConverter.SetConversionFunction(ElectricCapacitanceUnit.Farad, ElectricCapacitanceUnit.Kilofarad, quantity => quantity.ToUnit(ElectricCapacitanceUnit.Kilofarad)); - unitConverter.SetConversionFunction(ElectricCapacitanceUnit.Farad, ElectricCapacitanceUnit.Megafarad, quantity => quantity.ToUnit(ElectricCapacitanceUnit.Megafarad)); - unitConverter.SetConversionFunction(ElectricCapacitanceUnit.Farad, ElectricCapacitanceUnit.Microfarad, quantity => quantity.ToUnit(ElectricCapacitanceUnit.Microfarad)); - unitConverter.SetConversionFunction(ElectricCapacitanceUnit.Farad, ElectricCapacitanceUnit.Millifarad, quantity => quantity.ToUnit(ElectricCapacitanceUnit.Millifarad)); - unitConverter.SetConversionFunction(ElectricCapacitanceUnit.Farad, ElectricCapacitanceUnit.Nanofarad, quantity => quantity.ToUnit(ElectricCapacitanceUnit.Nanofarad)); - unitConverter.SetConversionFunction(ElectricCapacitanceUnit.Farad, ElectricCapacitanceUnit.Picofarad, quantity => quantity.ToUnit(ElectricCapacitanceUnit.Picofarad)); - } - /// /// Get unit abbreviation string. /// @@ -329,7 +311,7 @@ public static string GetAbbreviation(ElectricCapacitanceUnit unit, IFormatProvid /// /// Creates a from . /// - public static ElectricCapacitance FromFarads(double value) + public static ElectricCapacitance FromFarads(QuantityValue value) { return new ElectricCapacitance(value, ElectricCapacitanceUnit.Farad); } @@ -337,7 +319,7 @@ public static ElectricCapacitance FromFarads(double value) /// /// Creates a from . /// - public static ElectricCapacitance FromKilofarads(double value) + public static ElectricCapacitance FromKilofarads(QuantityValue value) { return new ElectricCapacitance(value, ElectricCapacitanceUnit.Kilofarad); } @@ -345,7 +327,7 @@ public static ElectricCapacitance FromKilofarads(double value) /// /// Creates a from . /// - public static ElectricCapacitance FromMegafarads(double value) + public static ElectricCapacitance FromMegafarads(QuantityValue value) { return new ElectricCapacitance(value, ElectricCapacitanceUnit.Megafarad); } @@ -353,7 +335,7 @@ public static ElectricCapacitance FromMegafarads(double value) /// /// Creates a from . /// - public static ElectricCapacitance FromMicrofarads(double value) + public static ElectricCapacitance FromMicrofarads(QuantityValue value) { return new ElectricCapacitance(value, ElectricCapacitanceUnit.Microfarad); } @@ -361,7 +343,7 @@ public static ElectricCapacitance FromMicrofarads(double value) /// /// Creates a from . /// - public static ElectricCapacitance FromMillifarads(double value) + public static ElectricCapacitance FromMillifarads(QuantityValue value) { return new ElectricCapacitance(value, ElectricCapacitanceUnit.Millifarad); } @@ -369,7 +351,7 @@ public static ElectricCapacitance FromMillifarads(double value) /// /// Creates a from . /// - public static ElectricCapacitance FromNanofarads(double value) + public static ElectricCapacitance FromNanofarads(QuantityValue value) { return new ElectricCapacitance(value, ElectricCapacitanceUnit.Nanofarad); } @@ -377,7 +359,7 @@ public static ElectricCapacitance FromNanofarads(double value) /// /// Creates a from . /// - public static ElectricCapacitance FromPicofarads(double value) + public static ElectricCapacitance FromPicofarads(QuantityValue value) { return new ElectricCapacitance(value, ElectricCapacitanceUnit.Picofarad); } @@ -388,7 +370,7 @@ public static ElectricCapacitance FromPicofarads(double value) /// Value to convert from. /// Unit to convert from. /// ElectricCapacitance unit value. - public static ElectricCapacitance From(double value, ElectricCapacitanceUnit fromUnit) + public static ElectricCapacitance From(QuantityValue value, ElectricCapacitanceUnit fromUnit) { return new ElectricCapacitance(value, fromUnit); } @@ -449,10 +431,7 @@ public static ElectricCapacitance Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricCapacitance Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -480,11 +459,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricCapacita /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricCapacitance result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -505,7 +480,7 @@ public static ElectricCapacitanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -516,7 +491,7 @@ public static ElectricCapacitanceUnit ParseUnit(string str, IFormatProvider? pro return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricCapacitanceUnit unit) { return TryParseUnit(str, null, out unit); @@ -531,7 +506,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricCapa /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricCapacitanceUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -550,35 +525,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricCapacitance operator +(ElectricCapacitance left, ElectricCapacitance right) { - return new ElectricCapacitance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricCapacitance(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricCapacitance operator -(ElectricCapacitance left, ElectricCapacitance right) { - return new ElectricCapacitance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricCapacitance(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static ElectricCapacitance operator *(double left, ElectricCapacitance right) + public static ElectricCapacitance operator *(QuantityValue left, ElectricCapacitance right) { return new ElectricCapacitance(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricCapacitance operator *(ElectricCapacitance left, double right) + public static ElectricCapacitance operator *(ElectricCapacitance left, QuantityValue right) { return new ElectricCapacitance(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricCapacitance operator /(ElectricCapacitance left, double right) + public static ElectricCapacitance operator /(ElectricCapacitance left, QuantityValue right) { return new ElectricCapacitance(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricCapacitance left, ElectricCapacitance right) + public static QuantityValue operator /(ElectricCapacitance left, ElectricCapacitance right) { return left.Farads / right.Farads; } @@ -590,97 +565,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricCapacitance left, ElectricCapacitance right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricCapacitance left, ElectricCapacitance right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricCapacitance left, ElectricCapacitance right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricCapacitance left, ElectricCapacitance right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricCapacitance other, ElectricCapacitance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricCapacitance left, ElectricCapacitance right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricCapacitance other, ElectricCapacitance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricCapacitance left, ElectricCapacitance right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricCapacitance other, ElectricCapacitance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricCapacitance otherQuantity)) + if (obj is not ElectricCapacitance otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricCapacitance other, ElectricCapacitance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricCapacitance other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricCapacitance. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricCapacitance), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricCapacitance otherQuantity)) throw new ArgumentException("Expected type ElectricCapacitance.", nameof(obj)); + if (obj is not ElectricCapacitance otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -692,158 +652,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricCapacitance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricCapacitanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this ElectricCapacitance to another ElectricCapacitance with the unit representation . - /// - /// The unit to convert to. - /// A ElectricCapacitance with the specified unit. - public ElectricCapacitance ToUnit(ElectricCapacitanceUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricCapacitance with the specified unit. - public ElectricCapacitance ToUnit(ElectricCapacitanceUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricCapacitance), Unit, typeof(ElectricCapacitance), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricCapacitance)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricCapacitanceUnit unit, [NotNullWhen(true)] out ElectricCapacitance? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricCapacitance? convertedOrNull = (Unit, unit) switch - { - // ElectricCapacitanceUnit -> BaseUnit - (ElectricCapacitanceUnit.Kilofarad, ElectricCapacitanceUnit.Farad) => new ElectricCapacitance((_value) * 1e3d, ElectricCapacitanceUnit.Farad), - (ElectricCapacitanceUnit.Megafarad, ElectricCapacitanceUnit.Farad) => new ElectricCapacitance((_value) * 1e6d, ElectricCapacitanceUnit.Farad), - (ElectricCapacitanceUnit.Microfarad, ElectricCapacitanceUnit.Farad) => new ElectricCapacitance((_value) * 1e-6d, ElectricCapacitanceUnit.Farad), - (ElectricCapacitanceUnit.Millifarad, ElectricCapacitanceUnit.Farad) => new ElectricCapacitance((_value) * 1e-3d, ElectricCapacitanceUnit.Farad), - (ElectricCapacitanceUnit.Nanofarad, ElectricCapacitanceUnit.Farad) => new ElectricCapacitance((_value) * 1e-9d, ElectricCapacitanceUnit.Farad), - (ElectricCapacitanceUnit.Picofarad, ElectricCapacitanceUnit.Farad) => new ElectricCapacitance((_value) * 1e-12d, ElectricCapacitanceUnit.Farad), - - // BaseUnit -> ElectricCapacitanceUnit - (ElectricCapacitanceUnit.Farad, ElectricCapacitanceUnit.Kilofarad) => new ElectricCapacitance((_value) / 1e3d, ElectricCapacitanceUnit.Kilofarad), - (ElectricCapacitanceUnit.Farad, ElectricCapacitanceUnit.Megafarad) => new ElectricCapacitance((_value) / 1e6d, ElectricCapacitanceUnit.Megafarad), - (ElectricCapacitanceUnit.Farad, ElectricCapacitanceUnit.Microfarad) => new ElectricCapacitance((_value) / 1e-6d, ElectricCapacitanceUnit.Microfarad), - (ElectricCapacitanceUnit.Farad, ElectricCapacitanceUnit.Millifarad) => new ElectricCapacitance((_value) / 1e-3d, ElectricCapacitanceUnit.Millifarad), - (ElectricCapacitanceUnit.Farad, ElectricCapacitanceUnit.Nanofarad) => new ElectricCapacitance((_value) / 1e-9d, ElectricCapacitanceUnit.Nanofarad), - (ElectricCapacitanceUnit.Farad, ElectricCapacitanceUnit.Picofarad) => new ElectricCapacitance((_value) / 1e-12d, ElectricCapacitanceUnit.Picofarad), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricCapacitance ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricCapacitanceUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCapacitanceUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ElectricCapacitanceUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCapacitanceUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ElectricCapacitanceUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricCapacitanceUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -858,7 +684,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs index 6334ba710e..bf0a2e2578 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCharge.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electric_charge /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricCharge : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -58,13 +57,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricChargeUnit? _unit; /// @@ -109,7 +108,7 @@ public static ElectricChargeInfo CreateDefault(Func - /// The for is [T][I]. + /// The for is TI. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 1, 1, 0, 0, 0); @@ -124,25 +123,43 @@ public static ElectricChargeInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricCharge. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricChargeUnit.AmpereHour, "AmpereHour", "AmpereHours", new BaseUnits(time: DurationUnit.Hour, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricChargeUnit.AmpereHour, "AmpereHour", "AmpereHours", new BaseUnits(time: DurationUnit.Hour, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 3600) + ); yield return new (ElectricChargeUnit.Coulomb, "Coulomb", "Coulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricChargeUnit.KiloampereHour, "KiloampereHour", "KiloampereHours", new BaseUnits(time: DurationUnit.Hour, current: ElectricCurrentUnit.Kiloampere)); - yield return new (ElectricChargeUnit.Kilocoulomb, "Kilocoulomb", "Kilocoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Kiloampere)); - yield return new (ElectricChargeUnit.MegaampereHour, "MegaampereHour", "MegaampereHours", new BaseUnits(time: DurationUnit.Hour, current: ElectricCurrentUnit.Megaampere)); - yield return new (ElectricChargeUnit.Megacoulomb, "Megacoulomb", "Megacoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Megaampere)); - yield return new (ElectricChargeUnit.Microcoulomb, "Microcoulomb", "Microcoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere)); - yield return new (ElectricChargeUnit.MilliampereHour, "MilliampereHour", "MilliampereHours", new BaseUnits(time: DurationUnit.Hour, current: ElectricCurrentUnit.Milliampere)); - yield return new (ElectricChargeUnit.Millicoulomb, "Millicoulomb", "Millicoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere)); - yield return new (ElectricChargeUnit.Nanocoulomb, "Nanocoulomb", "Nanocoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Nanoampere)); - yield return new (ElectricChargeUnit.Picocoulomb, "Picocoulomb", "Picocoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Picoampere)); + yield return new (ElectricChargeUnit.KiloampereHour, "KiloampereHour", "KiloampereHours", new BaseUnits(time: DurationUnit.Hour, current: ElectricCurrentUnit.Kiloampere), + new QuantityValue(1, 3600000) + ); + yield return new (ElectricChargeUnit.Kilocoulomb, "Kilocoulomb", "Kilocoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Kiloampere), + new QuantityValue(1, 1000) + ); + yield return new (ElectricChargeUnit.MegaampereHour, "MegaampereHour", "MegaampereHours", new BaseUnits(time: DurationUnit.Hour, current: ElectricCurrentUnit.Megaampere), + new QuantityValue(1, 3600000000) + ); + yield return new (ElectricChargeUnit.Megacoulomb, "Megacoulomb", "Megacoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Megaampere), + new QuantityValue(1, 1000000) + ); + yield return new (ElectricChargeUnit.Microcoulomb, "Microcoulomb", "Microcoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere), + 1000000 + ); + yield return new (ElectricChargeUnit.MilliampereHour, "MilliampereHour", "MilliampereHours", new BaseUnits(time: DurationUnit.Hour, current: ElectricCurrentUnit.Milliampere), + new QuantityValue(5, 18) + ); + yield return new (ElectricChargeUnit.Millicoulomb, "Millicoulomb", "Millicoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), + 1000 + ); + yield return new (ElectricChargeUnit.Nanocoulomb, "Nanocoulomb", "Nanocoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Nanoampere), + 1000000000 + ); + yield return new (ElectricChargeUnit.Picocoulomb, "Picocoulomb", "Picocoulombs", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Picoampere), + 1000000000000 + ); } } static ElectricCharge() { - Info = ElectricChargeInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricChargeInfo.CreateDefault); } /// @@ -150,7 +167,7 @@ static ElectricCharge() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricCharge(double value, ElectricChargeUnit unit) + public ElectricCharge(QuantityValue value, ElectricChargeUnit unit) { _value = value; _unit = unit; @@ -164,7 +181,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -175,7 +192,8 @@ public ElectricCharge(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -204,10 +222,8 @@ public ElectricCharge(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricChargeUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -246,98 +262,64 @@ public ElectricCharge(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AmpereHours => As(ElectricChargeUnit.AmpereHour); + public QuantityValue AmpereHours => this.As(ElectricChargeUnit.AmpereHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Coulombs => As(ElectricChargeUnit.Coulomb); + public QuantityValue Coulombs => this.As(ElectricChargeUnit.Coulomb); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KiloampereHours => As(ElectricChargeUnit.KiloampereHour); + public QuantityValue KiloampereHours => this.As(ElectricChargeUnit.KiloampereHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilocoulombs => As(ElectricChargeUnit.Kilocoulomb); + public QuantityValue Kilocoulombs => this.As(ElectricChargeUnit.Kilocoulomb); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegaampereHours => As(ElectricChargeUnit.MegaampereHour); + public QuantityValue MegaampereHours => this.As(ElectricChargeUnit.MegaampereHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megacoulombs => As(ElectricChargeUnit.Megacoulomb); + public QuantityValue Megacoulombs => this.As(ElectricChargeUnit.Megacoulomb); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microcoulombs => As(ElectricChargeUnit.Microcoulomb); + public QuantityValue Microcoulombs => this.As(ElectricChargeUnit.Microcoulomb); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliampereHours => As(ElectricChargeUnit.MilliampereHour); + public QuantityValue MilliampereHours => this.As(ElectricChargeUnit.MilliampereHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millicoulombs => As(ElectricChargeUnit.Millicoulomb); + public QuantityValue Millicoulombs => this.As(ElectricChargeUnit.Millicoulomb); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanocoulombs => As(ElectricChargeUnit.Nanocoulomb); + public QuantityValue Nanocoulombs => this.As(ElectricChargeUnit.Nanocoulomb); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Picocoulombs => As(ElectricChargeUnit.Picocoulomb); + public QuantityValue Picocoulombs => this.As(ElectricChargeUnit.Picocoulomb); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricChargeUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricChargeUnit.AmpereHour, ElectricChargeUnit.Coulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Coulomb)); - unitConverter.SetConversionFunction(ElectricChargeUnit.KiloampereHour, ElectricChargeUnit.Coulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Coulomb)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Kilocoulomb, ElectricChargeUnit.Coulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Coulomb)); - unitConverter.SetConversionFunction(ElectricChargeUnit.MegaampereHour, ElectricChargeUnit.Coulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Coulomb)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Megacoulomb, ElectricChargeUnit.Coulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Coulomb)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Microcoulomb, ElectricChargeUnit.Coulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Coulomb)); - unitConverter.SetConversionFunction(ElectricChargeUnit.MilliampereHour, ElectricChargeUnit.Coulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Coulomb)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Millicoulomb, ElectricChargeUnit.Coulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Coulomb)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Nanocoulomb, ElectricChargeUnit.Coulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Coulomb)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Picocoulomb, ElectricChargeUnit.Coulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Coulomb)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.Coulomb, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricChargeUnit - unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.AmpereHour, quantity => quantity.ToUnit(ElectricChargeUnit.AmpereHour)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.KiloampereHour, quantity => quantity.ToUnit(ElectricChargeUnit.KiloampereHour)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.Kilocoulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Kilocoulomb)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.MegaampereHour, quantity => quantity.ToUnit(ElectricChargeUnit.MegaampereHour)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.Megacoulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Megacoulomb)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.Microcoulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Microcoulomb)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.MilliampereHour, quantity => quantity.ToUnit(ElectricChargeUnit.MilliampereHour)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.Millicoulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Millicoulomb)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.Nanocoulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Nanocoulomb)); - unitConverter.SetConversionFunction(ElectricChargeUnit.Coulomb, ElectricChargeUnit.Picocoulomb, quantity => quantity.ToUnit(ElectricChargeUnit.Picocoulomb)); - } - /// /// Get unit abbreviation string. /// @@ -366,7 +348,7 @@ public static string GetAbbreviation(ElectricChargeUnit unit, IFormatProvider? p /// /// Creates a from . /// - public static ElectricCharge FromAmpereHours(double value) + public static ElectricCharge FromAmpereHours(QuantityValue value) { return new ElectricCharge(value, ElectricChargeUnit.AmpereHour); } @@ -374,7 +356,7 @@ public static ElectricCharge FromAmpereHours(double value) /// /// Creates a from . /// - public static ElectricCharge FromCoulombs(double value) + public static ElectricCharge FromCoulombs(QuantityValue value) { return new ElectricCharge(value, ElectricChargeUnit.Coulomb); } @@ -382,7 +364,7 @@ public static ElectricCharge FromCoulombs(double value) /// /// Creates a from . /// - public static ElectricCharge FromKiloampereHours(double value) + public static ElectricCharge FromKiloampereHours(QuantityValue value) { return new ElectricCharge(value, ElectricChargeUnit.KiloampereHour); } @@ -390,7 +372,7 @@ public static ElectricCharge FromKiloampereHours(double value) /// /// Creates a from . /// - public static ElectricCharge FromKilocoulombs(double value) + public static ElectricCharge FromKilocoulombs(QuantityValue value) { return new ElectricCharge(value, ElectricChargeUnit.Kilocoulomb); } @@ -398,7 +380,7 @@ public static ElectricCharge FromKilocoulombs(double value) /// /// Creates a from . /// - public static ElectricCharge FromMegaampereHours(double value) + public static ElectricCharge FromMegaampereHours(QuantityValue value) { return new ElectricCharge(value, ElectricChargeUnit.MegaampereHour); } @@ -406,7 +388,7 @@ public static ElectricCharge FromMegaampereHours(double value) /// /// Creates a from . /// - public static ElectricCharge FromMegacoulombs(double value) + public static ElectricCharge FromMegacoulombs(QuantityValue value) { return new ElectricCharge(value, ElectricChargeUnit.Megacoulomb); } @@ -414,7 +396,7 @@ public static ElectricCharge FromMegacoulombs(double value) /// /// Creates a from . /// - public static ElectricCharge FromMicrocoulombs(double value) + public static ElectricCharge FromMicrocoulombs(QuantityValue value) { return new ElectricCharge(value, ElectricChargeUnit.Microcoulomb); } @@ -422,7 +404,7 @@ public static ElectricCharge FromMicrocoulombs(double value) /// /// Creates a from . /// - public static ElectricCharge FromMilliampereHours(double value) + public static ElectricCharge FromMilliampereHours(QuantityValue value) { return new ElectricCharge(value, ElectricChargeUnit.MilliampereHour); } @@ -430,7 +412,7 @@ public static ElectricCharge FromMilliampereHours(double value) /// /// Creates a from . /// - public static ElectricCharge FromMillicoulombs(double value) + public static ElectricCharge FromMillicoulombs(QuantityValue value) { return new ElectricCharge(value, ElectricChargeUnit.Millicoulomb); } @@ -438,7 +420,7 @@ public static ElectricCharge FromMillicoulombs(double value) /// /// Creates a from . /// - public static ElectricCharge FromNanocoulombs(double value) + public static ElectricCharge FromNanocoulombs(QuantityValue value) { return new ElectricCharge(value, ElectricChargeUnit.Nanocoulomb); } @@ -446,7 +428,7 @@ public static ElectricCharge FromNanocoulombs(double value) /// /// Creates a from . /// - public static ElectricCharge FromPicocoulombs(double value) + public static ElectricCharge FromPicocoulombs(QuantityValue value) { return new ElectricCharge(value, ElectricChargeUnit.Picocoulomb); } @@ -457,7 +439,7 @@ public static ElectricCharge FromPicocoulombs(double value) /// Value to convert from. /// Unit to convert from. /// ElectricCharge unit value. - public static ElectricCharge From(double value, ElectricChargeUnit fromUnit) + public static ElectricCharge From(QuantityValue value, ElectricChargeUnit fromUnit) { return new ElectricCharge(value, fromUnit); } @@ -518,10 +500,7 @@ public static ElectricCharge Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricCharge Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -549,11 +528,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricCharge r /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricCharge result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -574,7 +549,7 @@ public static ElectricChargeUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -585,7 +560,7 @@ public static ElectricChargeUnit ParseUnit(string str, IFormatProvider? provider return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricChargeUnit unit) { return TryParseUnit(str, null, out unit); @@ -600,7 +575,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricChar /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricChargeUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -619,35 +594,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricCharge operator +(ElectricCharge left, ElectricCharge right) { - return new ElectricCharge(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricCharge(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricCharge operator -(ElectricCharge left, ElectricCharge right) { - return new ElectricCharge(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricCharge(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -681,97 +656,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricCharge left, ElectricCharge right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricCharge left, ElectricCharge right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricCharge left, ElectricCharge right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricCharge left, ElectricCharge right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricCharge other, ElectricCharge tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricCharge left, ElectricCharge right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricCharge other, ElectricCharge tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricCharge left, ElectricCharge right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricCharge other, ElectricCharge tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricCharge otherQuantity)) + if (obj is not ElectricCharge otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricCharge other, ElectricCharge tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricCharge other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricCharge. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricCharge), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricCharge otherQuantity)) throw new ArgumentException("Expected type ElectricCharge.", nameof(obj)); + if (obj is not ElectricCharge otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -783,166 +743,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricCharge other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricChargeUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this ElectricCharge to another ElectricCharge with the unit representation . - /// - /// The unit to convert to. - /// A ElectricCharge with the specified unit. - public ElectricCharge ToUnit(ElectricChargeUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricCharge with the specified unit. - public ElectricCharge ToUnit(ElectricChargeUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricCharge), Unit, typeof(ElectricCharge), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricCharge)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricChargeUnit unit, [NotNullWhen(true)] out ElectricCharge? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricCharge? convertedOrNull = (Unit, unit) switch - { - // ElectricChargeUnit -> BaseUnit - (ElectricChargeUnit.AmpereHour, ElectricChargeUnit.Coulomb) => new ElectricCharge(_value * 3600, ElectricChargeUnit.Coulomb), - (ElectricChargeUnit.KiloampereHour, ElectricChargeUnit.Coulomb) => new ElectricCharge((_value * 3600) * 1e3d, ElectricChargeUnit.Coulomb), - (ElectricChargeUnit.Kilocoulomb, ElectricChargeUnit.Coulomb) => new ElectricCharge((_value) * 1e3d, ElectricChargeUnit.Coulomb), - (ElectricChargeUnit.MegaampereHour, ElectricChargeUnit.Coulomb) => new ElectricCharge((_value * 3600) * 1e6d, ElectricChargeUnit.Coulomb), - (ElectricChargeUnit.Megacoulomb, ElectricChargeUnit.Coulomb) => new ElectricCharge((_value) * 1e6d, ElectricChargeUnit.Coulomb), - (ElectricChargeUnit.Microcoulomb, ElectricChargeUnit.Coulomb) => new ElectricCharge((_value) * 1e-6d, ElectricChargeUnit.Coulomb), - (ElectricChargeUnit.MilliampereHour, ElectricChargeUnit.Coulomb) => new ElectricCharge((_value * 3600) * 1e-3d, ElectricChargeUnit.Coulomb), - (ElectricChargeUnit.Millicoulomb, ElectricChargeUnit.Coulomb) => new ElectricCharge((_value) * 1e-3d, ElectricChargeUnit.Coulomb), - (ElectricChargeUnit.Nanocoulomb, ElectricChargeUnit.Coulomb) => new ElectricCharge((_value) * 1e-9d, ElectricChargeUnit.Coulomb), - (ElectricChargeUnit.Picocoulomb, ElectricChargeUnit.Coulomb) => new ElectricCharge((_value) * 1e-12d, ElectricChargeUnit.Coulomb), - - // BaseUnit -> ElectricChargeUnit - (ElectricChargeUnit.Coulomb, ElectricChargeUnit.AmpereHour) => new ElectricCharge(_value / 3600, ElectricChargeUnit.AmpereHour), - (ElectricChargeUnit.Coulomb, ElectricChargeUnit.KiloampereHour) => new ElectricCharge((_value / 3600) / 1e3d, ElectricChargeUnit.KiloampereHour), - (ElectricChargeUnit.Coulomb, ElectricChargeUnit.Kilocoulomb) => new ElectricCharge((_value) / 1e3d, ElectricChargeUnit.Kilocoulomb), - (ElectricChargeUnit.Coulomb, ElectricChargeUnit.MegaampereHour) => new ElectricCharge((_value / 3600) / 1e6d, ElectricChargeUnit.MegaampereHour), - (ElectricChargeUnit.Coulomb, ElectricChargeUnit.Megacoulomb) => new ElectricCharge((_value) / 1e6d, ElectricChargeUnit.Megacoulomb), - (ElectricChargeUnit.Coulomb, ElectricChargeUnit.Microcoulomb) => new ElectricCharge((_value) / 1e-6d, ElectricChargeUnit.Microcoulomb), - (ElectricChargeUnit.Coulomb, ElectricChargeUnit.MilliampereHour) => new ElectricCharge((_value / 3600) / 1e-3d, ElectricChargeUnit.MilliampereHour), - (ElectricChargeUnit.Coulomb, ElectricChargeUnit.Millicoulomb) => new ElectricCharge((_value) / 1e-3d, ElectricChargeUnit.Millicoulomb), - (ElectricChargeUnit.Coulomb, ElectricChargeUnit.Nanocoulomb) => new ElectricCharge((_value) / 1e-9d, ElectricChargeUnit.Nanocoulomb), - (ElectricChargeUnit.Coulomb, ElectricChargeUnit.Picocoulomb) => new ElectricCharge((_value) / 1e-12d, ElectricChargeUnit.Picocoulomb), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricCharge ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricChargeUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricChargeUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ElectricChargeUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricChargeUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -957,7 +775,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs index faa3420561..f44b0b6fb0 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricChargeDensity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Charge_density /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricChargeDensity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricChargeDensityUnit? _unit; /// @@ -104,7 +103,7 @@ public static ElectricChargeDensityInfo CreateDefault(Func - /// The for is [T][L^-3][I]. + /// The for is TL^-3I. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-3, 0, 1, 1, 0, 0, 0); @@ -125,9 +124,7 @@ public static IEnumerable> GetDefaultM static ElectricChargeDensity() { - Info = ElectricChargeDensityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricChargeDensityInfo.CreateDefault); } /// @@ -135,7 +132,7 @@ static ElectricChargeDensity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricChargeDensity(double value, ElectricChargeDensityUnit unit) + public ElectricChargeDensity(QuantityValue value, ElectricChargeDensityUnit unit) { _value = value; _unit = unit; @@ -149,7 +146,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -160,7 +157,8 @@ public ElectricChargeDensity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -189,10 +187,8 @@ public ElectricChargeDensity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricChargeDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -231,28 +227,14 @@ public ElectricChargeDensity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CoulombsPerCubicMeter => As(ElectricChargeDensityUnit.CoulombPerCubicMeter); + public QuantityValue CoulombsPerCubicMeter => this.As(ElectricChargeDensityUnit.CoulombPerCubicMeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricChargeDensityUnit -> BaseUnit - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricChargeDensityUnit.CoulombPerCubicMeter, ElectricChargeDensityUnit.CoulombPerCubicMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricChargeDensityUnit - } - /// /// Get unit abbreviation string. /// @@ -281,7 +263,7 @@ public static string GetAbbreviation(ElectricChargeDensityUnit unit, IFormatProv /// /// Creates a from . /// - public static ElectricChargeDensity FromCoulombsPerCubicMeter(double value) + public static ElectricChargeDensity FromCoulombsPerCubicMeter(QuantityValue value) { return new ElectricChargeDensity(value, ElectricChargeDensityUnit.CoulombPerCubicMeter); } @@ -292,7 +274,7 @@ public static ElectricChargeDensity FromCoulombsPerCubicMeter(double value) /// Value to convert from. /// Unit to convert from. /// ElectricChargeDensity unit value. - public static ElectricChargeDensity From(double value, ElectricChargeDensityUnit fromUnit) + public static ElectricChargeDensity From(QuantityValue value, ElectricChargeDensityUnit fromUnit) { return new ElectricChargeDensity(value, fromUnit); } @@ -353,10 +335,7 @@ public static ElectricChargeDensity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricChargeDensity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -384,11 +363,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricChargeDe /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricChargeDensity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -409,7 +384,7 @@ public static ElectricChargeDensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -420,7 +395,7 @@ public static ElectricChargeDensityUnit ParseUnit(string str, IFormatProvider? p return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricChargeDensityUnit unit) { return TryParseUnit(str, null, out unit); @@ -435,7 +410,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricChar /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricChargeDensityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -454,35 +429,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricChargeDensity operator +(ElectricChargeDensity left, ElectricChargeDensity right) { - return new ElectricChargeDensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricChargeDensity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricChargeDensity operator -(ElectricChargeDensity left, ElectricChargeDensity right) { - return new ElectricChargeDensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricChargeDensity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -494,97 +469,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricChargeDensity left, ElectricChargeDensity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricChargeDensity left, ElectricChargeDensity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricChargeDensity left, ElectricChargeDensity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricChargeDensity left, ElectricChargeDensity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricChargeDensity other, ElectricChargeDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricChargeDensity left, ElectricChargeDensity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricChargeDensity other, ElectricChargeDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricChargeDensity left, ElectricChargeDensity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricChargeDensity other, ElectricChargeDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricChargeDensity otherQuantity)) + if (obj is not ElectricChargeDensity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricChargeDensity other, ElectricChargeDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricChargeDensity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricChargeDensity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricChargeDensity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricChargeDensity otherQuantity)) throw new ArgumentException("Expected type ElectricChargeDensity.", nameof(obj)); + if (obj is not ElectricChargeDensity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -596,146 +556,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricChargeDensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricChargeDensityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this ElectricChargeDensity to another ElectricChargeDensity with the unit representation . - /// - /// The unit to convert to. - /// A ElectricChargeDensity with the specified unit. - public ElectricChargeDensity ToUnit(ElectricChargeDensityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricChargeDensity with the specified unit. - public ElectricChargeDensity ToUnit(ElectricChargeDensityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricChargeDensity), Unit, typeof(ElectricChargeDensity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricChargeDensity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricChargeDensityUnit unit, [NotNullWhen(true)] out ElectricChargeDensity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricChargeDensity? convertedOrNull = (Unit, unit) switch - { - // ElectricChargeDensityUnit -> BaseUnit + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> ElectricChargeDensityUnit - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricChargeDensity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricChargeDensityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricChargeDensityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ElectricChargeDensityUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricChargeDensityUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricChargeDensityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(ElectricChargeDensityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -750,7 +588,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs index 908ee65ca4..b4dc318642 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductance.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electrical_resistance_and_conductance /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricConductance : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricConductanceUnit? _unit; /// @@ -104,7 +103,7 @@ public static ElectricConductanceInfo CreateDefault(Func - /// The for is [T^3][L^-2][M^-1][I^2]. + /// The for is T^3L^-2M^-1I^2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); @@ -119,30 +118,58 @@ public static ElectricConductanceInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricConductance. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricConductanceUnit.Gigamho, "Gigamho", "Gigamhos", BaseUnits.Undefined); - yield return new (ElectricConductanceUnit.Gigasiemens, "Gigasiemens", "Gigasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricConductanceUnit.Kilomho, "Kilomho", "Kilomhos", BaseUnits.Undefined); - yield return new (ElectricConductanceUnit.Kilosiemens, "Kilosiemens", "Kilosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricConductanceUnit.Megamho, "Megamho", "Megamhos", BaseUnits.Undefined); - yield return new (ElectricConductanceUnit.Megasiemens, "Megasiemens", "Megasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricConductanceUnit.Mho, "Mho", "Mhos", BaseUnits.Undefined); - yield return new (ElectricConductanceUnit.Micromho, "Micromho", "Micromhos", BaseUnits.Undefined); - yield return new (ElectricConductanceUnit.Microsiemens, "Microsiemens", "Microsiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere)); - yield return new (ElectricConductanceUnit.Millimho, "Millimho", "Millimhos", BaseUnits.Undefined); - yield return new (ElectricConductanceUnit.Millisiemens, "Millisiemens", "Millisiemens", BaseUnits.Undefined); - yield return new (ElectricConductanceUnit.Nanomho, "Nanomho", "Nanomhos", BaseUnits.Undefined); - yield return new (ElectricConductanceUnit.Nanosiemens, "Nanosiemens", "Nanosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricConductanceUnit.Gigamho, "Gigamho", "Gigamhos", BaseUnits.Undefined, + new QuantityValue(1, 1000000000) + ); + yield return new (ElectricConductanceUnit.Gigasiemens, "Gigasiemens", "Gigasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000000) + ); + yield return new (ElectricConductanceUnit.Kilomho, "Kilomho", "Kilomhos", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (ElectricConductanceUnit.Kilosiemens, "Kilosiemens", "Kilosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000) + ); + yield return new (ElectricConductanceUnit.Megamho, "Megamho", "Megamhos", BaseUnits.Undefined, + new QuantityValue(1, 1000000) + ); + yield return new (ElectricConductanceUnit.Megasiemens, "Megasiemens", "Megasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000) + ); + yield return new (ElectricConductanceUnit.Mho, "Mho", "Mhos", BaseUnits.Undefined, + 1 + ); + yield return new (ElectricConductanceUnit.Micromho, "Micromho", "Micromhos", BaseUnits.Undefined, + 1000000 + ); + yield return new (ElectricConductanceUnit.Microsiemens, "Microsiemens", "Microsiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), + 1000000 + ); + yield return new (ElectricConductanceUnit.Millimho, "Millimho", "Millimhos", BaseUnits.Undefined, + 1000 + ); + yield return new (ElectricConductanceUnit.Millisiemens, "Millisiemens", "Millisiemens", BaseUnits.Undefined, + 1000 + ); + yield return new (ElectricConductanceUnit.Nanomho, "Nanomho", "Nanomhos", BaseUnits.Undefined, + 1000000000 + ); + yield return new (ElectricConductanceUnit.Nanosiemens, "Nanosiemens", "Nanosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere), + 1000000000 + ); yield return new (ElectricConductanceUnit.Siemens, "Siemens", "Siemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricConductanceUnit.Teramho, "Teramho", "Teramhos", BaseUnits.Undefined); - yield return new (ElectricConductanceUnit.Terasiemens, "Terasiemens", "Terasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricConductanceUnit.Teramho, "Teramho", "Teramhos", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000) + ); + yield return new (ElectricConductanceUnit.Terasiemens, "Terasiemens", "Terasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000000000) + ); } } static ElectricConductance() { - Info = ElectricConductanceInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricConductanceInfo.CreateDefault); } /// @@ -150,7 +177,7 @@ static ElectricConductance() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricConductance(double value, ElectricConductanceUnit unit) + public ElectricConductance(QuantityValue value, ElectricConductanceUnit unit) { _value = value; _unit = unit; @@ -164,7 +191,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -175,7 +202,8 @@ public ElectricConductance(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -204,10 +232,8 @@ public ElectricConductance(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricConductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -246,133 +272,89 @@ public ElectricConductance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigamhos => As(ElectricConductanceUnit.Gigamho); + public QuantityValue Gigamhos => this.As(ElectricConductanceUnit.Gigamho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigasiemens => As(ElectricConductanceUnit.Gigasiemens); + public QuantityValue Gigasiemens => this.As(ElectricConductanceUnit.Gigasiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilomhos => As(ElectricConductanceUnit.Kilomho); + public QuantityValue Kilomhos => this.As(ElectricConductanceUnit.Kilomho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilosiemens => As(ElectricConductanceUnit.Kilosiemens); + public QuantityValue Kilosiemens => this.As(ElectricConductanceUnit.Kilosiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megamhos => As(ElectricConductanceUnit.Megamho); + public QuantityValue Megamhos => this.As(ElectricConductanceUnit.Megamho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megasiemens => As(ElectricConductanceUnit.Megasiemens); + public QuantityValue Megasiemens => this.As(ElectricConductanceUnit.Megasiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Mhos => As(ElectricConductanceUnit.Mho); + public QuantityValue Mhos => this.As(ElectricConductanceUnit.Mho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Micromhos => As(ElectricConductanceUnit.Micromho); + public QuantityValue Micromhos => this.As(ElectricConductanceUnit.Micromho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microsiemens => As(ElectricConductanceUnit.Microsiemens); + public QuantityValue Microsiemens => this.As(ElectricConductanceUnit.Microsiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millimhos => As(ElectricConductanceUnit.Millimho); + public QuantityValue Millimhos => this.As(ElectricConductanceUnit.Millimho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millisiemens => As(ElectricConductanceUnit.Millisiemens); + public QuantityValue Millisiemens => this.As(ElectricConductanceUnit.Millisiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanomhos => As(ElectricConductanceUnit.Nanomho); + public QuantityValue Nanomhos => this.As(ElectricConductanceUnit.Nanomho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanosiemens => As(ElectricConductanceUnit.Nanosiemens); + public QuantityValue Nanosiemens => this.As(ElectricConductanceUnit.Nanosiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Siemens => As(ElectricConductanceUnit.Siemens); + public QuantityValue Siemens => this.As(ElectricConductanceUnit.Siemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Teramhos => As(ElectricConductanceUnit.Teramho); + public QuantityValue Teramhos => this.As(ElectricConductanceUnit.Teramho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Terasiemens => As(ElectricConductanceUnit.Terasiemens); + public QuantityValue Terasiemens => this.As(ElectricConductanceUnit.Terasiemens); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricConductanceUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricConductanceUnit.Gigamho, ElectricConductanceUnit.Siemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Gigasiemens, ElectricConductanceUnit.Siemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Kilomho, ElectricConductanceUnit.Siemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Kilosiemens, ElectricConductanceUnit.Siemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Megamho, ElectricConductanceUnit.Siemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Megasiemens, ElectricConductanceUnit.Siemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Mho, ElectricConductanceUnit.Siemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Micromho, ElectricConductanceUnit.Siemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Microsiemens, ElectricConductanceUnit.Siemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Millimho, ElectricConductanceUnit.Siemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Millisiemens, ElectricConductanceUnit.Siemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Nanomho, ElectricConductanceUnit.Siemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Nanosiemens, ElectricConductanceUnit.Siemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Teramho, ElectricConductanceUnit.Siemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Terasiemens, ElectricConductanceUnit.Siemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Siemens)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Siemens, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricConductanceUnit - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Gigamho, quantity => quantity.ToUnit(ElectricConductanceUnit.Gigamho)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Gigasiemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Gigasiemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Kilomho, quantity => quantity.ToUnit(ElectricConductanceUnit.Kilomho)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Kilosiemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Kilosiemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Megamho, quantity => quantity.ToUnit(ElectricConductanceUnit.Megamho)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Megasiemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Megasiemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Mho, quantity => quantity.ToUnit(ElectricConductanceUnit.Mho)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Micromho, quantity => quantity.ToUnit(ElectricConductanceUnit.Micromho)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Microsiemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Microsiemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Millimho, quantity => quantity.ToUnit(ElectricConductanceUnit.Millimho)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Millisiemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Millisiemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Nanomho, quantity => quantity.ToUnit(ElectricConductanceUnit.Nanomho)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Nanosiemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Nanosiemens)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Teramho, quantity => quantity.ToUnit(ElectricConductanceUnit.Teramho)); - unitConverter.SetConversionFunction(ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Terasiemens, quantity => quantity.ToUnit(ElectricConductanceUnit.Terasiemens)); - } - /// /// Get unit abbreviation string. /// @@ -401,7 +383,7 @@ public static string GetAbbreviation(ElectricConductanceUnit unit, IFormatProvid /// /// Creates a from . /// - public static ElectricConductance FromGigamhos(double value) + public static ElectricConductance FromGigamhos(QuantityValue value) { return new ElectricConductance(value, ElectricConductanceUnit.Gigamho); } @@ -409,7 +391,7 @@ public static ElectricConductance FromGigamhos(double value) /// /// Creates a from . /// - public static ElectricConductance FromGigasiemens(double value) + public static ElectricConductance FromGigasiemens(QuantityValue value) { return new ElectricConductance(value, ElectricConductanceUnit.Gigasiemens); } @@ -417,7 +399,7 @@ public static ElectricConductance FromGigasiemens(double value) /// /// Creates a from . /// - public static ElectricConductance FromKilomhos(double value) + public static ElectricConductance FromKilomhos(QuantityValue value) { return new ElectricConductance(value, ElectricConductanceUnit.Kilomho); } @@ -425,7 +407,7 @@ public static ElectricConductance FromKilomhos(double value) /// /// Creates a from . /// - public static ElectricConductance FromKilosiemens(double value) + public static ElectricConductance FromKilosiemens(QuantityValue value) { return new ElectricConductance(value, ElectricConductanceUnit.Kilosiemens); } @@ -433,7 +415,7 @@ public static ElectricConductance FromKilosiemens(double value) /// /// Creates a from . /// - public static ElectricConductance FromMegamhos(double value) + public static ElectricConductance FromMegamhos(QuantityValue value) { return new ElectricConductance(value, ElectricConductanceUnit.Megamho); } @@ -441,7 +423,7 @@ public static ElectricConductance FromMegamhos(double value) /// /// Creates a from . /// - public static ElectricConductance FromMegasiemens(double value) + public static ElectricConductance FromMegasiemens(QuantityValue value) { return new ElectricConductance(value, ElectricConductanceUnit.Megasiemens); } @@ -449,7 +431,7 @@ public static ElectricConductance FromMegasiemens(double value) /// /// Creates a from . /// - public static ElectricConductance FromMhos(double value) + public static ElectricConductance FromMhos(QuantityValue value) { return new ElectricConductance(value, ElectricConductanceUnit.Mho); } @@ -457,7 +439,7 @@ public static ElectricConductance FromMhos(double value) /// /// Creates a from . /// - public static ElectricConductance FromMicromhos(double value) + public static ElectricConductance FromMicromhos(QuantityValue value) { return new ElectricConductance(value, ElectricConductanceUnit.Micromho); } @@ -465,7 +447,7 @@ public static ElectricConductance FromMicromhos(double value) /// /// Creates a from . /// - public static ElectricConductance FromMicrosiemens(double value) + public static ElectricConductance FromMicrosiemens(QuantityValue value) { return new ElectricConductance(value, ElectricConductanceUnit.Microsiemens); } @@ -473,7 +455,7 @@ public static ElectricConductance FromMicrosiemens(double value) /// /// Creates a from . /// - public static ElectricConductance FromMillimhos(double value) + public static ElectricConductance FromMillimhos(QuantityValue value) { return new ElectricConductance(value, ElectricConductanceUnit.Millimho); } @@ -481,7 +463,7 @@ public static ElectricConductance FromMillimhos(double value) /// /// Creates a from . /// - public static ElectricConductance FromMillisiemens(double value) + public static ElectricConductance FromMillisiemens(QuantityValue value) { return new ElectricConductance(value, ElectricConductanceUnit.Millisiemens); } @@ -489,7 +471,7 @@ public static ElectricConductance FromMillisiemens(double value) /// /// Creates a from . /// - public static ElectricConductance FromNanomhos(double value) + public static ElectricConductance FromNanomhos(QuantityValue value) { return new ElectricConductance(value, ElectricConductanceUnit.Nanomho); } @@ -497,7 +479,7 @@ public static ElectricConductance FromNanomhos(double value) /// /// Creates a from . /// - public static ElectricConductance FromNanosiemens(double value) + public static ElectricConductance FromNanosiemens(QuantityValue value) { return new ElectricConductance(value, ElectricConductanceUnit.Nanosiemens); } @@ -505,7 +487,7 @@ public static ElectricConductance FromNanosiemens(double value) /// /// Creates a from . /// - public static ElectricConductance FromSiemens(double value) + public static ElectricConductance FromSiemens(QuantityValue value) { return new ElectricConductance(value, ElectricConductanceUnit.Siemens); } @@ -513,7 +495,7 @@ public static ElectricConductance FromSiemens(double value) /// /// Creates a from . /// - public static ElectricConductance FromTeramhos(double value) + public static ElectricConductance FromTeramhos(QuantityValue value) { return new ElectricConductance(value, ElectricConductanceUnit.Teramho); } @@ -521,7 +503,7 @@ public static ElectricConductance FromTeramhos(double value) /// /// Creates a from . /// - public static ElectricConductance FromTerasiemens(double value) + public static ElectricConductance FromTerasiemens(QuantityValue value) { return new ElectricConductance(value, ElectricConductanceUnit.Terasiemens); } @@ -532,7 +514,7 @@ public static ElectricConductance FromTerasiemens(double value) /// Value to convert from. /// Unit to convert from. /// ElectricConductance unit value. - public static ElectricConductance From(double value, ElectricConductanceUnit fromUnit) + public static ElectricConductance From(QuantityValue value, ElectricConductanceUnit fromUnit) { return new ElectricConductance(value, fromUnit); } @@ -593,10 +575,7 @@ public static ElectricConductance Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricConductance Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -624,11 +603,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricConducta /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricConductance result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -649,7 +624,7 @@ public static ElectricConductanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -660,7 +635,7 @@ public static ElectricConductanceUnit ParseUnit(string str, IFormatProvider? pro return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricConductanceUnit unit) { return TryParseUnit(str, null, out unit); @@ -675,7 +650,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricCond /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricConductanceUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -694,35 +669,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricConductance operator +(ElectricConductance left, ElectricConductance right) { - return new ElectricConductance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricConductance(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricConductance operator -(ElectricConductance left, ElectricConductance right) { - return new ElectricConductance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricConductance(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -734,97 +709,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricConductance left, ElectricConductance right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricConductance left, ElectricConductance right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricConductance left, ElectricConductance right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricConductance left, ElectricConductance right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricConductance other, ElectricConductance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricConductance left, ElectricConductance right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricConductance other, ElectricConductance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricConductance left, ElectricConductance right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricConductance other, ElectricConductance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricConductance otherQuantity)) + if (obj is not ElectricConductance otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricConductance other, ElectricConductance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricConductance other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricConductance. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricConductance), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricConductance otherQuantity)) throw new ArgumentException("Expected type ElectricConductance.", nameof(obj)); + if (obj is not ElectricConductance otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -836,176 +796,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricConductance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricConductanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this ElectricConductance to another ElectricConductance with the unit representation . - /// - /// The unit to convert to. - /// A ElectricConductance with the specified unit. - public ElectricConductance ToUnit(ElectricConductanceUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricConductance with the specified unit. - public ElectricConductance ToUnit(ElectricConductanceUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricConductance), Unit, typeof(ElectricConductance), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricConductance)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricConductanceUnit unit, [NotNullWhen(true)] out ElectricConductance? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricConductance? convertedOrNull = (Unit, unit) switch - { - // ElectricConductanceUnit -> BaseUnit - (ElectricConductanceUnit.Gigamho, ElectricConductanceUnit.Siemens) => new ElectricConductance((_value) * 1e9d, ElectricConductanceUnit.Siemens), - (ElectricConductanceUnit.Gigasiemens, ElectricConductanceUnit.Siemens) => new ElectricConductance((_value) * 1e9d, ElectricConductanceUnit.Siemens), - (ElectricConductanceUnit.Kilomho, ElectricConductanceUnit.Siemens) => new ElectricConductance((_value) * 1e3d, ElectricConductanceUnit.Siemens), - (ElectricConductanceUnit.Kilosiemens, ElectricConductanceUnit.Siemens) => new ElectricConductance((_value) * 1e3d, ElectricConductanceUnit.Siemens), - (ElectricConductanceUnit.Megamho, ElectricConductanceUnit.Siemens) => new ElectricConductance((_value) * 1e6d, ElectricConductanceUnit.Siemens), - (ElectricConductanceUnit.Megasiemens, ElectricConductanceUnit.Siemens) => new ElectricConductance((_value) * 1e6d, ElectricConductanceUnit.Siemens), - (ElectricConductanceUnit.Mho, ElectricConductanceUnit.Siemens) => new ElectricConductance(_value, ElectricConductanceUnit.Siemens), - (ElectricConductanceUnit.Micromho, ElectricConductanceUnit.Siemens) => new ElectricConductance((_value) * 1e-6d, ElectricConductanceUnit.Siemens), - (ElectricConductanceUnit.Microsiemens, ElectricConductanceUnit.Siemens) => new ElectricConductance((_value) * 1e-6d, ElectricConductanceUnit.Siemens), - (ElectricConductanceUnit.Millimho, ElectricConductanceUnit.Siemens) => new ElectricConductance((_value) * 1e-3d, ElectricConductanceUnit.Siemens), - (ElectricConductanceUnit.Millisiemens, ElectricConductanceUnit.Siemens) => new ElectricConductance((_value) * 1e-3d, ElectricConductanceUnit.Siemens), - (ElectricConductanceUnit.Nanomho, ElectricConductanceUnit.Siemens) => new ElectricConductance((_value) * 1e-9d, ElectricConductanceUnit.Siemens), - (ElectricConductanceUnit.Nanosiemens, ElectricConductanceUnit.Siemens) => new ElectricConductance((_value) * 1e-9d, ElectricConductanceUnit.Siemens), - (ElectricConductanceUnit.Teramho, ElectricConductanceUnit.Siemens) => new ElectricConductance((_value) * 1e12d, ElectricConductanceUnit.Siemens), - (ElectricConductanceUnit.Terasiemens, ElectricConductanceUnit.Siemens) => new ElectricConductance((_value) * 1e12d, ElectricConductanceUnit.Siemens), - - // BaseUnit -> ElectricConductanceUnit - (ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Gigamho) => new ElectricConductance((_value) / 1e9d, ElectricConductanceUnit.Gigamho), - (ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Gigasiemens) => new ElectricConductance((_value) / 1e9d, ElectricConductanceUnit.Gigasiemens), - (ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Kilomho) => new ElectricConductance((_value) / 1e3d, ElectricConductanceUnit.Kilomho), - (ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Kilosiemens) => new ElectricConductance((_value) / 1e3d, ElectricConductanceUnit.Kilosiemens), - (ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Megamho) => new ElectricConductance((_value) / 1e6d, ElectricConductanceUnit.Megamho), - (ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Megasiemens) => new ElectricConductance((_value) / 1e6d, ElectricConductanceUnit.Megasiemens), - (ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Mho) => new ElectricConductance(_value, ElectricConductanceUnit.Mho), - (ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Micromho) => new ElectricConductance((_value) / 1e-6d, ElectricConductanceUnit.Micromho), - (ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Microsiemens) => new ElectricConductance((_value) / 1e-6d, ElectricConductanceUnit.Microsiemens), - (ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Millimho) => new ElectricConductance((_value) / 1e-3d, ElectricConductanceUnit.Millimho), - (ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Millisiemens) => new ElectricConductance((_value) / 1e-3d, ElectricConductanceUnit.Millisiemens), - (ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Nanomho) => new ElectricConductance((_value) / 1e-9d, ElectricConductanceUnit.Nanomho), - (ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Nanosiemens) => new ElectricConductance((_value) / 1e-9d, ElectricConductanceUnit.Nanosiemens), - (ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Teramho) => new ElectricConductance((_value) / 1e12d, ElectricConductanceUnit.Teramho), - (ElectricConductanceUnit.Siemens, ElectricConductanceUnit.Terasiemens) => new ElectricConductance((_value) / 1e12d, ElectricConductanceUnit.Terasiemens), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricConductance ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricConductanceUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricConductanceUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ElectricConductanceUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricConductanceUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1020,7 +828,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs index 92f96fd430..ccfedfd528 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricConductivity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricConductivity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricConductivityUnit? _unit; /// @@ -104,7 +103,7 @@ public static ElectricConductivityInfo CreateDefault(Func - /// The for is [T^3][L^-3][M^-1][I^2]. + /// The for is T^3L^-3M^-1I^2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-3, -1, 3, 2, 0, 0, 0); @@ -119,20 +118,28 @@ public static ElectricConductivityInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricConductivity. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricConductivityUnit.MicrosiemensPerCentimeter, "MicrosiemensPerCentimeter", "MicrosiemensPerCentimeter", BaseUnits.Undefined); - yield return new (ElectricConductivityUnit.MillisiemensPerCentimeter, "MillisiemensPerCentimeter", "MillisiemensPerCentimeter", BaseUnits.Undefined); - yield return new (ElectricConductivityUnit.SiemensPerCentimeter, "SiemensPerCentimeter", "SiemensPerCentimeter", BaseUnits.Undefined); - yield return new (ElectricConductivityUnit.SiemensPerFoot, "SiemensPerFoot", "SiemensPerFoot", BaseUnits.Undefined); - yield return new (ElectricConductivityUnit.SiemensPerInch, "SiemensPerInch", "SiemensPerInch", BaseUnits.Undefined); + yield return new (ElectricConductivityUnit.MicrosiemensPerCentimeter, "MicrosiemensPerCentimeter", "MicrosiemensPerCentimeter", BaseUnits.Undefined, + 10000 + ); + yield return new (ElectricConductivityUnit.MillisiemensPerCentimeter, "MillisiemensPerCentimeter", "MillisiemensPerCentimeter", BaseUnits.Undefined, + 10 + ); + yield return new (ElectricConductivityUnit.SiemensPerCentimeter, "SiemensPerCentimeter", "SiemensPerCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 100) + ); + yield return new (ElectricConductivityUnit.SiemensPerFoot, "SiemensPerFoot", "SiemensPerFoot", BaseUnits.Undefined, + new QuantityValue(381, 1250) + ); + yield return new (ElectricConductivityUnit.SiemensPerInch, "SiemensPerInch", "SiemensPerInch", BaseUnits.Undefined, + new QuantityValue(127, 5000) + ); yield return new (ElectricConductivityUnit.SiemensPerMeter, "SiemensPerMeter", "SiemensPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); } } static ElectricConductivity() { - Info = ElectricConductivityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricConductivityInfo.CreateDefault); } /// @@ -140,7 +147,7 @@ static ElectricConductivity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricConductivity(double value, ElectricConductivityUnit unit) + public ElectricConductivity(QuantityValue value, ElectricConductivityUnit unit) { _value = value; _unit = unit; @@ -154,7 +161,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -165,7 +172,8 @@ public ElectricConductivity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -194,10 +202,8 @@ public ElectricConductivity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -236,63 +242,39 @@ public ElectricConductivity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrosiemensPerCentimeter => As(ElectricConductivityUnit.MicrosiemensPerCentimeter); + public QuantityValue MicrosiemensPerCentimeter => this.As(ElectricConductivityUnit.MicrosiemensPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillisiemensPerCentimeter => As(ElectricConductivityUnit.MillisiemensPerCentimeter); + public QuantityValue MillisiemensPerCentimeter => this.As(ElectricConductivityUnit.MillisiemensPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SiemensPerCentimeter => As(ElectricConductivityUnit.SiemensPerCentimeter); + public QuantityValue SiemensPerCentimeter => this.As(ElectricConductivityUnit.SiemensPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SiemensPerFoot => As(ElectricConductivityUnit.SiemensPerFoot); + public QuantityValue SiemensPerFoot => this.As(ElectricConductivityUnit.SiemensPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SiemensPerInch => As(ElectricConductivityUnit.SiemensPerInch); + public QuantityValue SiemensPerInch => this.As(ElectricConductivityUnit.SiemensPerInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SiemensPerMeter => As(ElectricConductivityUnit.SiemensPerMeter); + public QuantityValue SiemensPerMeter => this.As(ElectricConductivityUnit.SiemensPerMeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricConductivityUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricConductivityUnit.MicrosiemensPerCentimeter, ElectricConductivityUnit.SiemensPerMeter, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerMeter)); - unitConverter.SetConversionFunction(ElectricConductivityUnit.MillisiemensPerCentimeter, ElectricConductivityUnit.SiemensPerMeter, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerMeter)); - unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerCentimeter, ElectricConductivityUnit.SiemensPerMeter, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerMeter)); - unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerFoot, ElectricConductivityUnit.SiemensPerMeter, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerMeter)); - unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerInch, ElectricConductivityUnit.SiemensPerMeter, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricConductivityUnit - unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.MicrosiemensPerCentimeter, quantity => quantity.ToUnit(ElectricConductivityUnit.MicrosiemensPerCentimeter)); - unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.MillisiemensPerCentimeter, quantity => quantity.ToUnit(ElectricConductivityUnit.MillisiemensPerCentimeter)); - unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerCentimeter, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerCentimeter)); - unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerFoot, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerFoot)); - unitConverter.SetConversionFunction(ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerInch, quantity => quantity.ToUnit(ElectricConductivityUnit.SiemensPerInch)); - } - /// /// Get unit abbreviation string. /// @@ -321,7 +303,7 @@ public static string GetAbbreviation(ElectricConductivityUnit unit, IFormatProvi /// /// Creates a from . /// - public static ElectricConductivity FromMicrosiemensPerCentimeter(double value) + public static ElectricConductivity FromMicrosiemensPerCentimeter(QuantityValue value) { return new ElectricConductivity(value, ElectricConductivityUnit.MicrosiemensPerCentimeter); } @@ -329,7 +311,7 @@ public static ElectricConductivity FromMicrosiemensPerCentimeter(double value) /// /// Creates a from . /// - public static ElectricConductivity FromMillisiemensPerCentimeter(double value) + public static ElectricConductivity FromMillisiemensPerCentimeter(QuantityValue value) { return new ElectricConductivity(value, ElectricConductivityUnit.MillisiemensPerCentimeter); } @@ -337,7 +319,7 @@ public static ElectricConductivity FromMillisiemensPerCentimeter(double value) /// /// Creates a from . /// - public static ElectricConductivity FromSiemensPerCentimeter(double value) + public static ElectricConductivity FromSiemensPerCentimeter(QuantityValue value) { return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerCentimeter); } @@ -345,7 +327,7 @@ public static ElectricConductivity FromSiemensPerCentimeter(double value) /// /// Creates a from . /// - public static ElectricConductivity FromSiemensPerFoot(double value) + public static ElectricConductivity FromSiemensPerFoot(QuantityValue value) { return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerFoot); } @@ -353,7 +335,7 @@ public static ElectricConductivity FromSiemensPerFoot(double value) /// /// Creates a from . /// - public static ElectricConductivity FromSiemensPerInch(double value) + public static ElectricConductivity FromSiemensPerInch(QuantityValue value) { return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerInch); } @@ -361,7 +343,7 @@ public static ElectricConductivity FromSiemensPerInch(double value) /// /// Creates a from . /// - public static ElectricConductivity FromSiemensPerMeter(double value) + public static ElectricConductivity FromSiemensPerMeter(QuantityValue value) { return new ElectricConductivity(value, ElectricConductivityUnit.SiemensPerMeter); } @@ -372,7 +354,7 @@ public static ElectricConductivity FromSiemensPerMeter(double value) /// Value to convert from. /// Unit to convert from. /// ElectricConductivity unit value. - public static ElectricConductivity From(double value, ElectricConductivityUnit fromUnit) + public static ElectricConductivity From(QuantityValue value, ElectricConductivityUnit fromUnit) { return new ElectricConductivity(value, fromUnit); } @@ -433,10 +415,7 @@ public static ElectricConductivity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricConductivity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -464,11 +443,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricConducti /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricConductivity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -489,7 +464,7 @@ public static ElectricConductivityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -500,7 +475,7 @@ public static ElectricConductivityUnit ParseUnit(string str, IFormatProvider? pr return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricConductivityUnit unit) { return TryParseUnit(str, null, out unit); @@ -515,7 +490,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricCond /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricConductivityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -534,35 +509,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricConductivity operator +(ElectricConductivity left, ElectricConductivity right) { - return new ElectricConductivity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricConductivity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricConductivity operator -(ElectricConductivity left, ElectricConductivity right) { - return new ElectricConductivity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricConductivity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -575,7 +550,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// The corresponding inverse quantity, . public ElectricResistivity Inverse() { - return ElectricResistivity.FromOhmMeters(1 / SiemensPerMeter); + return UnitConverter.Default.ConvertTo(Value, Unit, ElectricResistivity.Info); } #endregion @@ -585,97 +560,82 @@ public ElectricResistivity Inverse() /// Returns true if less or equal to. public static bool operator <=(ElectricConductivity left, ElectricConductivity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricConductivity left, ElectricConductivity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricConductivity left, ElectricConductivity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricConductivity left, ElectricConductivity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricConductivity other, ElectricConductivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricConductivity left, ElectricConductivity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricConductivity other, ElectricConductivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricConductivity left, ElectricConductivity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricConductivity other, ElectricConductivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricConductivity otherQuantity)) + if (obj is not ElectricConductivity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricConductivity other, ElectricConductivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricConductivity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricConductivity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricConductivity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricConductivity otherQuantity)) throw new ArgumentException("Expected type ElectricConductivity.", nameof(obj)); + if (obj is not ElectricConductivity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -687,156 +647,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricConductivity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricConductivityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this ElectricConductivity to another ElectricConductivity with the unit representation . - /// - /// The unit to convert to. - /// A ElectricConductivity with the specified unit. - public ElectricConductivity ToUnit(ElectricConductivityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricConductivity with the specified unit. - public ElectricConductivity ToUnit(ElectricConductivityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricConductivity), Unit, typeof(ElectricConductivity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricConductivity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricConductivityUnit unit, [NotNullWhen(true)] out ElectricConductivity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricConductivity? convertedOrNull = (Unit, unit) switch - { - // ElectricConductivityUnit -> BaseUnit - (ElectricConductivityUnit.MicrosiemensPerCentimeter, ElectricConductivityUnit.SiemensPerMeter) => new ElectricConductivity((_value * 1e2) * 1e-6d, ElectricConductivityUnit.SiemensPerMeter), - (ElectricConductivityUnit.MillisiemensPerCentimeter, ElectricConductivityUnit.SiemensPerMeter) => new ElectricConductivity((_value * 1e2) * 1e-3d, ElectricConductivityUnit.SiemensPerMeter), - (ElectricConductivityUnit.SiemensPerCentimeter, ElectricConductivityUnit.SiemensPerMeter) => new ElectricConductivity(_value * 1e2, ElectricConductivityUnit.SiemensPerMeter), - (ElectricConductivityUnit.SiemensPerFoot, ElectricConductivityUnit.SiemensPerMeter) => new ElectricConductivity(_value / 0.3048, ElectricConductivityUnit.SiemensPerMeter), - (ElectricConductivityUnit.SiemensPerInch, ElectricConductivityUnit.SiemensPerMeter) => new ElectricConductivity(_value / 2.54e-2, ElectricConductivityUnit.SiemensPerMeter), - - // BaseUnit -> ElectricConductivityUnit - (ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.MicrosiemensPerCentimeter) => new ElectricConductivity((_value / 1e2) / 1e-6d, ElectricConductivityUnit.MicrosiemensPerCentimeter), - (ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.MillisiemensPerCentimeter) => new ElectricConductivity((_value / 1e2) / 1e-3d, ElectricConductivityUnit.MillisiemensPerCentimeter), - (ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerCentimeter) => new ElectricConductivity(_value / 1e2, ElectricConductivityUnit.SiemensPerCentimeter), - (ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerFoot) => new ElectricConductivity(_value * 0.3048, ElectricConductivityUnit.SiemensPerFoot), - (ElectricConductivityUnit.SiemensPerMeter, ElectricConductivityUnit.SiemensPerInch) => new ElectricConductivity(_value * 2.54e-2, ElectricConductivityUnit.SiemensPerInch), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricConductivity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricConductivityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricConductivityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ElectricConductivityUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricConductivityUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -851,7 +679,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs index 8c80e4fa27..1cb770cb84 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrent.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// If you want to map more parameters into the ElectricCurrent class (amps RMS, phase angle, etc.), create your own wrapper type such as a record or named tuple. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricCurrent : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -60,13 +59,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricCurrentUnit? _unit; /// @@ -111,7 +110,7 @@ public static ElectricCurrentInfo CreateDefault(Func - /// The for is [I]. + /// The for is I. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 0, 1, 0, 0, 0); @@ -127,22 +126,36 @@ public static ElectricCurrentInfo CreateDefault(Func> GetDefaultMappings() { yield return new (ElectricCurrentUnit.Ampere, "Ampere", "Amperes", new BaseUnits(current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricCurrentUnit.Centiampere, "Centiampere", "Centiamperes", new BaseUnits(current: ElectricCurrentUnit.Centiampere)); - yield return new (ElectricCurrentUnit.Femtoampere, "Femtoampere", "Femtoamperes", new BaseUnits(current: ElectricCurrentUnit.Femtoampere)); - yield return new (ElectricCurrentUnit.Kiloampere, "Kiloampere", "Kiloamperes", new BaseUnits(current: ElectricCurrentUnit.Kiloampere)); - yield return new (ElectricCurrentUnit.Megaampere, "Megaampere", "Megaamperes", new BaseUnits(current: ElectricCurrentUnit.Megaampere)); - yield return new (ElectricCurrentUnit.Microampere, "Microampere", "Microamperes", new BaseUnits(current: ElectricCurrentUnit.Microampere)); - yield return new (ElectricCurrentUnit.Milliampere, "Milliampere", "Milliamperes", new BaseUnits(current: ElectricCurrentUnit.Milliampere)); - yield return new (ElectricCurrentUnit.Nanoampere, "Nanoampere", "Nanoamperes", new BaseUnits(current: ElectricCurrentUnit.Nanoampere)); - yield return new (ElectricCurrentUnit.Picoampere, "Picoampere", "Picoamperes", new BaseUnits(current: ElectricCurrentUnit.Picoampere)); + yield return new (ElectricCurrentUnit.Centiampere, "Centiampere", "Centiamperes", new BaseUnits(current: ElectricCurrentUnit.Centiampere), + 100 + ); + yield return new (ElectricCurrentUnit.Femtoampere, "Femtoampere", "Femtoamperes", new BaseUnits(current: ElectricCurrentUnit.Femtoampere), + 1000000000000000 + ); + yield return new (ElectricCurrentUnit.Kiloampere, "Kiloampere", "Kiloamperes", new BaseUnits(current: ElectricCurrentUnit.Kiloampere), + new QuantityValue(1, 1000) + ); + yield return new (ElectricCurrentUnit.Megaampere, "Megaampere", "Megaamperes", new BaseUnits(current: ElectricCurrentUnit.Megaampere), + new QuantityValue(1, 1000000) + ); + yield return new (ElectricCurrentUnit.Microampere, "Microampere", "Microamperes", new BaseUnits(current: ElectricCurrentUnit.Microampere), + 1000000 + ); + yield return new (ElectricCurrentUnit.Milliampere, "Milliampere", "Milliamperes", new BaseUnits(current: ElectricCurrentUnit.Milliampere), + 1000 + ); + yield return new (ElectricCurrentUnit.Nanoampere, "Nanoampere", "Nanoamperes", new BaseUnits(current: ElectricCurrentUnit.Nanoampere), + 1000000000 + ); + yield return new (ElectricCurrentUnit.Picoampere, "Picoampere", "Picoamperes", new BaseUnits(current: ElectricCurrentUnit.Picoampere), + 1000000000000 + ); } } static ElectricCurrent() { - Info = ElectricCurrentInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricCurrentInfo.CreateDefault); } /// @@ -150,7 +163,7 @@ static ElectricCurrent() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricCurrent(double value, ElectricCurrentUnit unit) + public ElectricCurrent(QuantityValue value, ElectricCurrentUnit unit) { _value = value; _unit = unit; @@ -164,7 +177,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -175,7 +188,8 @@ public ElectricCurrent(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -204,10 +218,8 @@ public ElectricCurrent(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricCurrentUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -246,84 +258,54 @@ public ElectricCurrent(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Amperes => As(ElectricCurrentUnit.Ampere); + public QuantityValue Amperes => this.As(ElectricCurrentUnit.Ampere); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Centiamperes => As(ElectricCurrentUnit.Centiampere); + public QuantityValue Centiamperes => this.As(ElectricCurrentUnit.Centiampere); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Femtoamperes => As(ElectricCurrentUnit.Femtoampere); + public QuantityValue Femtoamperes => this.As(ElectricCurrentUnit.Femtoampere); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kiloamperes => As(ElectricCurrentUnit.Kiloampere); + public QuantityValue Kiloamperes => this.As(ElectricCurrentUnit.Kiloampere); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megaamperes => As(ElectricCurrentUnit.Megaampere); + public QuantityValue Megaamperes => this.As(ElectricCurrentUnit.Megaampere); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microamperes => As(ElectricCurrentUnit.Microampere); + public QuantityValue Microamperes => this.As(ElectricCurrentUnit.Microampere); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Milliamperes => As(ElectricCurrentUnit.Milliampere); + public QuantityValue Milliamperes => this.As(ElectricCurrentUnit.Milliampere); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanoamperes => As(ElectricCurrentUnit.Nanoampere); + public QuantityValue Nanoamperes => this.As(ElectricCurrentUnit.Nanoampere); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Picoamperes => As(ElectricCurrentUnit.Picoampere); + public QuantityValue Picoamperes => this.As(ElectricCurrentUnit.Picoampere); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricCurrentUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricCurrentUnit.Centiampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Ampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Femtoampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Ampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Kiloampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Ampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Megaampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Ampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Microampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Ampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Milliampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Ampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Nanoampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Ampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Picoampere, ElectricCurrentUnit.Ampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Ampere)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Ampere, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricCurrentUnit - unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Centiampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Centiampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Femtoampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Femtoampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Kiloampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Kiloampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Megaampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Megaampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Microampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Microampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Milliampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Milliampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Nanoampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Nanoampere)); - unitConverter.SetConversionFunction(ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Picoampere, quantity => quantity.ToUnit(ElectricCurrentUnit.Picoampere)); - } - /// /// Get unit abbreviation string. /// @@ -352,7 +334,7 @@ public static string GetAbbreviation(ElectricCurrentUnit unit, IFormatProvider? /// /// Creates a from . /// - public static ElectricCurrent FromAmperes(double value) + public static ElectricCurrent FromAmperes(QuantityValue value) { return new ElectricCurrent(value, ElectricCurrentUnit.Ampere); } @@ -360,7 +342,7 @@ public static ElectricCurrent FromAmperes(double value) /// /// Creates a from . /// - public static ElectricCurrent FromCentiamperes(double value) + public static ElectricCurrent FromCentiamperes(QuantityValue value) { return new ElectricCurrent(value, ElectricCurrentUnit.Centiampere); } @@ -368,7 +350,7 @@ public static ElectricCurrent FromCentiamperes(double value) /// /// Creates a from . /// - public static ElectricCurrent FromFemtoamperes(double value) + public static ElectricCurrent FromFemtoamperes(QuantityValue value) { return new ElectricCurrent(value, ElectricCurrentUnit.Femtoampere); } @@ -376,7 +358,7 @@ public static ElectricCurrent FromFemtoamperes(double value) /// /// Creates a from . /// - public static ElectricCurrent FromKiloamperes(double value) + public static ElectricCurrent FromKiloamperes(QuantityValue value) { return new ElectricCurrent(value, ElectricCurrentUnit.Kiloampere); } @@ -384,7 +366,7 @@ public static ElectricCurrent FromKiloamperes(double value) /// /// Creates a from . /// - public static ElectricCurrent FromMegaamperes(double value) + public static ElectricCurrent FromMegaamperes(QuantityValue value) { return new ElectricCurrent(value, ElectricCurrentUnit.Megaampere); } @@ -392,7 +374,7 @@ public static ElectricCurrent FromMegaamperes(double value) /// /// Creates a from . /// - public static ElectricCurrent FromMicroamperes(double value) + public static ElectricCurrent FromMicroamperes(QuantityValue value) { return new ElectricCurrent(value, ElectricCurrentUnit.Microampere); } @@ -400,7 +382,7 @@ public static ElectricCurrent FromMicroamperes(double value) /// /// Creates a from . /// - public static ElectricCurrent FromMilliamperes(double value) + public static ElectricCurrent FromMilliamperes(QuantityValue value) { return new ElectricCurrent(value, ElectricCurrentUnit.Milliampere); } @@ -408,7 +390,7 @@ public static ElectricCurrent FromMilliamperes(double value) /// /// Creates a from . /// - public static ElectricCurrent FromNanoamperes(double value) + public static ElectricCurrent FromNanoamperes(QuantityValue value) { return new ElectricCurrent(value, ElectricCurrentUnit.Nanoampere); } @@ -416,7 +398,7 @@ public static ElectricCurrent FromNanoamperes(double value) /// /// Creates a from . /// - public static ElectricCurrent FromPicoamperes(double value) + public static ElectricCurrent FromPicoamperes(QuantityValue value) { return new ElectricCurrent(value, ElectricCurrentUnit.Picoampere); } @@ -427,7 +409,7 @@ public static ElectricCurrent FromPicoamperes(double value) /// Value to convert from. /// Unit to convert from. /// ElectricCurrent unit value. - public static ElectricCurrent From(double value, ElectricCurrentUnit fromUnit) + public static ElectricCurrent From(QuantityValue value, ElectricCurrentUnit fromUnit) { return new ElectricCurrent(value, fromUnit); } @@ -488,10 +470,7 @@ public static ElectricCurrent Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricCurrent Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -519,11 +498,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricCurrent /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricCurrent result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -544,7 +519,7 @@ public static ElectricCurrentUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -555,7 +530,7 @@ public static ElectricCurrentUnit ParseUnit(string str, IFormatProvider? provide return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricCurrentUnit unit) { return TryParseUnit(str, null, out unit); @@ -570,7 +545,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricCurr /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricCurrentUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -589,35 +564,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricCurrent operator +(ElectricCurrent left, ElectricCurrent right) { - return new ElectricCurrent(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricCurrent(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricCurrent operator -(ElectricCurrent left, ElectricCurrent right) { - return new ElectricCurrent(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricCurrent(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -663,97 +638,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricCurrent left, ElectricCurrent right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricCurrent left, ElectricCurrent right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricCurrent left, ElectricCurrent right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricCurrent left, ElectricCurrent right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricCurrent other, ElectricCurrent tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricCurrent left, ElectricCurrent right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricCurrent other, ElectricCurrent tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricCurrent left, ElectricCurrent right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricCurrent other, ElectricCurrent tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricCurrent otherQuantity)) + if (obj is not ElectricCurrent otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricCurrent other, ElectricCurrent tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricCurrent other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricCurrent. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricCurrent), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricCurrent otherQuantity)) throw new ArgumentException("Expected type ElectricCurrent.", nameof(obj)); + if (obj is not ElectricCurrent otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -765,162 +725,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricCurrent other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricCurrentUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this ElectricCurrent to another ElectricCurrent with the unit representation . - /// - /// The unit to convert to. - /// A ElectricCurrent with the specified unit. - public ElectricCurrent ToUnit(ElectricCurrentUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricCurrent with the specified unit. - public ElectricCurrent ToUnit(ElectricCurrentUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricCurrent), Unit, typeof(ElectricCurrent), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricCurrent)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricCurrentUnit unit, [NotNullWhen(true)] out ElectricCurrent? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricCurrent? convertedOrNull = (Unit, unit) switch - { - // ElectricCurrentUnit -> BaseUnit - (ElectricCurrentUnit.Centiampere, ElectricCurrentUnit.Ampere) => new ElectricCurrent((_value) * 1e-2d, ElectricCurrentUnit.Ampere), - (ElectricCurrentUnit.Femtoampere, ElectricCurrentUnit.Ampere) => new ElectricCurrent((_value) * 1e-15d, ElectricCurrentUnit.Ampere), - (ElectricCurrentUnit.Kiloampere, ElectricCurrentUnit.Ampere) => new ElectricCurrent((_value) * 1e3d, ElectricCurrentUnit.Ampere), - (ElectricCurrentUnit.Megaampere, ElectricCurrentUnit.Ampere) => new ElectricCurrent((_value) * 1e6d, ElectricCurrentUnit.Ampere), - (ElectricCurrentUnit.Microampere, ElectricCurrentUnit.Ampere) => new ElectricCurrent((_value) * 1e-6d, ElectricCurrentUnit.Ampere), - (ElectricCurrentUnit.Milliampere, ElectricCurrentUnit.Ampere) => new ElectricCurrent((_value) * 1e-3d, ElectricCurrentUnit.Ampere), - (ElectricCurrentUnit.Nanoampere, ElectricCurrentUnit.Ampere) => new ElectricCurrent((_value) * 1e-9d, ElectricCurrentUnit.Ampere), - (ElectricCurrentUnit.Picoampere, ElectricCurrentUnit.Ampere) => new ElectricCurrent((_value) * 1e-12d, ElectricCurrentUnit.Ampere), - - // BaseUnit -> ElectricCurrentUnit - (ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Centiampere) => new ElectricCurrent((_value) / 1e-2d, ElectricCurrentUnit.Centiampere), - (ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Femtoampere) => new ElectricCurrent((_value) / 1e-15d, ElectricCurrentUnit.Femtoampere), - (ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Kiloampere) => new ElectricCurrent((_value) / 1e3d, ElectricCurrentUnit.Kiloampere), - (ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Megaampere) => new ElectricCurrent((_value) / 1e6d, ElectricCurrentUnit.Megaampere), - (ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Microampere) => new ElectricCurrent((_value) / 1e-6d, ElectricCurrentUnit.Microampere), - (ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Milliampere) => new ElectricCurrent((_value) / 1e-3d, ElectricCurrentUnit.Milliampere), - (ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Nanoampere) => new ElectricCurrent((_value) / 1e-9d, ElectricCurrentUnit.Nanoampere), - (ElectricCurrentUnit.Ampere, ElectricCurrentUnit.Picoampere) => new ElectricCurrent((_value) / 1e-12d, ElectricCurrentUnit.Picoampere), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricCurrent ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricCurrentUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ElectricCurrentUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricCurrentUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -935,7 +757,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs index ed55047ef8..38219b40f7 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentDensity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Current_density /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricCurrentDensity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricCurrentDensityUnit? _unit; /// @@ -104,7 +103,7 @@ public static ElectricCurrentDensityInfo CreateDefault(Func - /// The for is [L^-2][I]. + /// The for is L^-2I. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 0, 0, 1, 0, 0, 0); @@ -119,17 +118,19 @@ public static ElectricCurrentDensityInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricCurrentDensity. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricCurrentDensityUnit.AmperePerSquareFoot, "AmperePerSquareFoot", "AmperesPerSquareFoot", new BaseUnits(length: LengthUnit.Foot, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricCurrentDensityUnit.AmperePerSquareInch, "AmperePerSquareInch", "AmperesPerSquareInch", new BaseUnits(length: LengthUnit.Inch, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricCurrentDensityUnit.AmperePerSquareFoot, "AmperePerSquareFoot", "AmperesPerSquareFoot", new BaseUnits(length: LengthUnit.Foot, current: ElectricCurrentUnit.Ampere), + new QuantityValue(145161, 1562500) + ); + yield return new (ElectricCurrentDensityUnit.AmperePerSquareInch, "AmperePerSquareInch", "AmperesPerSquareInch", new BaseUnits(length: LengthUnit.Inch, current: ElectricCurrentUnit.Ampere), + new QuantityValue(16129, 25000000) + ); yield return new (ElectricCurrentDensityUnit.AmperePerSquareMeter, "AmperePerSquareMeter", "AmperesPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, current: ElectricCurrentUnit.Ampere)); } } static ElectricCurrentDensity() { - Info = ElectricCurrentDensityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricCurrentDensityInfo.CreateDefault); } /// @@ -137,7 +138,7 @@ static ElectricCurrentDensity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricCurrentDensity(double value, ElectricCurrentDensityUnit unit) + public ElectricCurrentDensity(QuantityValue value, ElectricCurrentDensityUnit unit) { _value = value; _unit = unit; @@ -151,7 +152,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -162,7 +163,8 @@ public ElectricCurrentDensity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -191,10 +193,8 @@ public ElectricCurrentDensity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricCurrentDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -233,42 +233,24 @@ public ElectricCurrentDensity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AmperesPerSquareFoot => As(ElectricCurrentDensityUnit.AmperePerSquareFoot); + public QuantityValue AmperesPerSquareFoot => this.As(ElectricCurrentDensityUnit.AmperePerSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AmperesPerSquareInch => As(ElectricCurrentDensityUnit.AmperePerSquareInch); + public QuantityValue AmperesPerSquareInch => this.As(ElectricCurrentDensityUnit.AmperePerSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AmperesPerSquareMeter => As(ElectricCurrentDensityUnit.AmperePerSquareMeter); + public QuantityValue AmperesPerSquareMeter => this.As(ElectricCurrentDensityUnit.AmperePerSquareMeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricCurrentDensityUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricCurrentDensityUnit.AmperePerSquareFoot, ElectricCurrentDensityUnit.AmperePerSquareMeter, quantity => quantity.ToUnit(ElectricCurrentDensityUnit.AmperePerSquareMeter)); - unitConverter.SetConversionFunction(ElectricCurrentDensityUnit.AmperePerSquareInch, ElectricCurrentDensityUnit.AmperePerSquareMeter, quantity => quantity.ToUnit(ElectricCurrentDensityUnit.AmperePerSquareMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricCurrentDensityUnit.AmperePerSquareMeter, ElectricCurrentDensityUnit.AmperePerSquareMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricCurrentDensityUnit - unitConverter.SetConversionFunction(ElectricCurrentDensityUnit.AmperePerSquareMeter, ElectricCurrentDensityUnit.AmperePerSquareFoot, quantity => quantity.ToUnit(ElectricCurrentDensityUnit.AmperePerSquareFoot)); - unitConverter.SetConversionFunction(ElectricCurrentDensityUnit.AmperePerSquareMeter, ElectricCurrentDensityUnit.AmperePerSquareInch, quantity => quantity.ToUnit(ElectricCurrentDensityUnit.AmperePerSquareInch)); - } - /// /// Get unit abbreviation string. /// @@ -297,7 +279,7 @@ public static string GetAbbreviation(ElectricCurrentDensityUnit unit, IFormatPro /// /// Creates a from . /// - public static ElectricCurrentDensity FromAmperesPerSquareFoot(double value) + public static ElectricCurrentDensity FromAmperesPerSquareFoot(QuantityValue value) { return new ElectricCurrentDensity(value, ElectricCurrentDensityUnit.AmperePerSquareFoot); } @@ -305,7 +287,7 @@ public static ElectricCurrentDensity FromAmperesPerSquareFoot(double value) /// /// Creates a from . /// - public static ElectricCurrentDensity FromAmperesPerSquareInch(double value) + public static ElectricCurrentDensity FromAmperesPerSquareInch(QuantityValue value) { return new ElectricCurrentDensity(value, ElectricCurrentDensityUnit.AmperePerSquareInch); } @@ -313,7 +295,7 @@ public static ElectricCurrentDensity FromAmperesPerSquareInch(double value) /// /// Creates a from . /// - public static ElectricCurrentDensity FromAmperesPerSquareMeter(double value) + public static ElectricCurrentDensity FromAmperesPerSquareMeter(QuantityValue value) { return new ElectricCurrentDensity(value, ElectricCurrentDensityUnit.AmperePerSquareMeter); } @@ -324,7 +306,7 @@ public static ElectricCurrentDensity FromAmperesPerSquareMeter(double value) /// Value to convert from. /// Unit to convert from. /// ElectricCurrentDensity unit value. - public static ElectricCurrentDensity From(double value, ElectricCurrentDensityUnit fromUnit) + public static ElectricCurrentDensity From(QuantityValue value, ElectricCurrentDensityUnit fromUnit) { return new ElectricCurrentDensity(value, fromUnit); } @@ -385,10 +367,7 @@ public static ElectricCurrentDensity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricCurrentDensity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -416,11 +395,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricCurrentD /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricCurrentDensity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -441,7 +416,7 @@ public static ElectricCurrentDensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -452,7 +427,7 @@ public static ElectricCurrentDensityUnit ParseUnit(string str, IFormatProvider? return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricCurrentDensityUnit unit) { return TryParseUnit(str, null, out unit); @@ -467,7 +442,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricCurr /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricCurrentDensityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -486,35 +461,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricCurrentDensity operator +(ElectricCurrentDensity left, ElectricCurrentDensity right) { - return new ElectricCurrentDensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricCurrentDensity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricCurrentDensity operator -(ElectricCurrentDensity left, ElectricCurrentDensity right) { - return new ElectricCurrentDensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricCurrentDensity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -526,97 +501,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricCurrentDensity left, ElectricCurrentDensity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricCurrentDensity left, ElectricCurrentDensity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricCurrentDensity left, ElectricCurrentDensity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricCurrentDensity left, ElectricCurrentDensity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricCurrentDensity other, ElectricCurrentDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricCurrentDensity left, ElectricCurrentDensity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricCurrentDensity other, ElectricCurrentDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricCurrentDensity left, ElectricCurrentDensity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricCurrentDensity other, ElectricCurrentDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricCurrentDensity otherQuantity)) + if (obj is not ElectricCurrentDensity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricCurrentDensity other, ElectricCurrentDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricCurrentDensity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricCurrentDensity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricCurrentDensity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricCurrentDensity otherQuantity)) throw new ArgumentException("Expected type ElectricCurrentDensity.", nameof(obj)); + if (obj is not ElectricCurrentDensity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -628,150 +588,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricCurrentDensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricCurrentDensityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this ElectricCurrentDensity to another ElectricCurrentDensity with the unit representation . - /// - /// The unit to convert to. - /// A ElectricCurrentDensity with the specified unit. - public ElectricCurrentDensity ToUnit(ElectricCurrentDensityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricCurrentDensity with the specified unit. - public ElectricCurrentDensity ToUnit(ElectricCurrentDensityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricCurrentDensity), Unit, typeof(ElectricCurrentDensity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricCurrentDensity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricCurrentDensityUnit unit, [NotNullWhen(true)] out ElectricCurrentDensity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricCurrentDensity? convertedOrNull = (Unit, unit) switch - { - // ElectricCurrentDensityUnit -> BaseUnit - (ElectricCurrentDensityUnit.AmperePerSquareFoot, ElectricCurrentDensityUnit.AmperePerSquareMeter) => new ElectricCurrentDensity(_value / 9.290304e-2, ElectricCurrentDensityUnit.AmperePerSquareMeter), - (ElectricCurrentDensityUnit.AmperePerSquareInch, ElectricCurrentDensityUnit.AmperePerSquareMeter) => new ElectricCurrentDensity(_value / 0.00064516, ElectricCurrentDensityUnit.AmperePerSquareMeter), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> ElectricCurrentDensityUnit - (ElectricCurrentDensityUnit.AmperePerSquareMeter, ElectricCurrentDensityUnit.AmperePerSquareFoot) => new ElectricCurrentDensity(_value * 9.290304e-2, ElectricCurrentDensityUnit.AmperePerSquareFoot), - (ElectricCurrentDensityUnit.AmperePerSquareMeter, ElectricCurrentDensityUnit.AmperePerSquareInch) => new ElectricCurrentDensity(_value * 0.00064516, ElectricCurrentDensityUnit.AmperePerSquareInch), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricCurrentDensity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricCurrentDensityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentDensityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ElectricCurrentDensityUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentDensityUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricCurrentDensityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(ElectricCurrentDensityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -786,7 +620,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs index fa857f5d19..3e475d3c48 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricCurrentGradient.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// In electromagnetism, the current gradient describes how the current changes in time. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricCurrentGradient : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricCurrentGradientUnit? _unit; /// @@ -104,7 +103,7 @@ public static ElectricCurrentGradientInfo CreateDefault(Func - /// The for is [T^-1][I]. + /// The for is T^-1I. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -1, 1, 0, 0, 0); @@ -119,21 +118,31 @@ public static ElectricCurrentGradientInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricCurrentGradient. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricCurrentGradientUnit.AmperePerMicrosecond, "AmperePerMicrosecond", "AmperesPerMicrosecond", new BaseUnits(time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricCurrentGradientUnit.AmperePerMillisecond, "AmperePerMillisecond", "AmperesPerMillisecond", new BaseUnits(time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricCurrentGradientUnit.AmperePerMinute, "AmperePerMinute", "AmperesPerMinute", new BaseUnits(time: DurationUnit.Minute, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricCurrentGradientUnit.AmperePerNanosecond, "AmperePerNanosecond", "AmperesPerNanosecond", new BaseUnits(time: DurationUnit.Nanosecond, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricCurrentGradientUnit.AmperePerMicrosecond, "AmperePerMicrosecond", "AmperesPerMicrosecond", new BaseUnits(time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000) + ); + yield return new (ElectricCurrentGradientUnit.AmperePerMillisecond, "AmperePerMillisecond", "AmperesPerMillisecond", new BaseUnits(time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000) + ); + yield return new (ElectricCurrentGradientUnit.AmperePerMinute, "AmperePerMinute", "AmperesPerMinute", new BaseUnits(time: DurationUnit.Minute, current: ElectricCurrentUnit.Ampere), + 60 + ); + yield return new (ElectricCurrentGradientUnit.AmperePerNanosecond, "AmperePerNanosecond", "AmperesPerNanosecond", new BaseUnits(time: DurationUnit.Nanosecond, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000000) + ); yield return new (ElectricCurrentGradientUnit.AmperePerSecond, "AmperePerSecond", "AmperesPerSecond", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricCurrentGradientUnit.MilliamperePerMinute, "MilliamperePerMinute", "MilliamperesPerMinute", new BaseUnits(time: DurationUnit.Minute, current: ElectricCurrentUnit.Milliampere)); - yield return new (ElectricCurrentGradientUnit.MilliamperePerSecond, "MilliamperePerSecond", "MilliamperesPerSecond", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere)); + yield return new (ElectricCurrentGradientUnit.MilliamperePerMinute, "MilliamperePerMinute", "MilliamperesPerMinute", new BaseUnits(time: DurationUnit.Minute, current: ElectricCurrentUnit.Milliampere), + 60000 + ); + yield return new (ElectricCurrentGradientUnit.MilliamperePerSecond, "MilliamperePerSecond", "MilliamperesPerSecond", new BaseUnits(time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), + 1000 + ); } } static ElectricCurrentGradient() { - Info = ElectricCurrentGradientInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricCurrentGradientInfo.CreateDefault); } /// @@ -141,7 +150,7 @@ static ElectricCurrentGradient() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricCurrentGradient(double value, ElectricCurrentGradientUnit unit) + public ElectricCurrentGradient(QuantityValue value, ElectricCurrentGradientUnit unit) { _value = value; _unit = unit; @@ -155,7 +164,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -166,7 +175,8 @@ public ElectricCurrentGradient(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -195,10 +205,8 @@ public ElectricCurrentGradient(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricCurrentGradientUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -237,70 +245,44 @@ public ElectricCurrentGradient(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AmperesPerMicrosecond => As(ElectricCurrentGradientUnit.AmperePerMicrosecond); + public QuantityValue AmperesPerMicrosecond => this.As(ElectricCurrentGradientUnit.AmperePerMicrosecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AmperesPerMillisecond => As(ElectricCurrentGradientUnit.AmperePerMillisecond); + public QuantityValue AmperesPerMillisecond => this.As(ElectricCurrentGradientUnit.AmperePerMillisecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AmperesPerMinute => As(ElectricCurrentGradientUnit.AmperePerMinute); + public QuantityValue AmperesPerMinute => this.As(ElectricCurrentGradientUnit.AmperePerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AmperesPerNanosecond => As(ElectricCurrentGradientUnit.AmperePerNanosecond); + public QuantityValue AmperesPerNanosecond => this.As(ElectricCurrentGradientUnit.AmperePerNanosecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AmperesPerSecond => As(ElectricCurrentGradientUnit.AmperePerSecond); + public QuantityValue AmperesPerSecond => this.As(ElectricCurrentGradientUnit.AmperePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliamperesPerMinute => As(ElectricCurrentGradientUnit.MilliamperePerMinute); + public QuantityValue MilliamperesPerMinute => this.As(ElectricCurrentGradientUnit.MilliamperePerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliamperesPerSecond => As(ElectricCurrentGradientUnit.MilliamperePerSecond); + public QuantityValue MilliamperesPerSecond => this.As(ElectricCurrentGradientUnit.MilliamperePerSecond); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricCurrentGradientUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerMicrosecond, ElectricCurrentGradientUnit.AmperePerSecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerSecond)); - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerMillisecond, ElectricCurrentGradientUnit.AmperePerSecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerSecond)); - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerMinute, ElectricCurrentGradientUnit.AmperePerSecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerSecond)); - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerNanosecond, ElectricCurrentGradientUnit.AmperePerSecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerSecond)); - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.MilliamperePerMinute, ElectricCurrentGradientUnit.AmperePerSecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerSecond)); - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.MilliamperePerSecond, ElectricCurrentGradientUnit.AmperePerSecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricCurrentGradientUnit - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerMicrosecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerMicrosecond)); - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerMillisecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerMillisecond)); - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerMinute, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerMinute)); - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerNanosecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.AmperePerNanosecond)); - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.MilliamperePerMinute, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.MilliamperePerMinute)); - unitConverter.SetConversionFunction(ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.MilliamperePerSecond, quantity => quantity.ToUnit(ElectricCurrentGradientUnit.MilliamperePerSecond)); - } - /// /// Get unit abbreviation string. /// @@ -329,7 +311,7 @@ public static string GetAbbreviation(ElectricCurrentGradientUnit unit, IFormatPr /// /// Creates a from . /// - public static ElectricCurrentGradient FromAmperesPerMicrosecond(double value) + public static ElectricCurrentGradient FromAmperesPerMicrosecond(QuantityValue value) { return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerMicrosecond); } @@ -337,7 +319,7 @@ public static ElectricCurrentGradient FromAmperesPerMicrosecond(double value) /// /// Creates a from . /// - public static ElectricCurrentGradient FromAmperesPerMillisecond(double value) + public static ElectricCurrentGradient FromAmperesPerMillisecond(QuantityValue value) { return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerMillisecond); } @@ -345,7 +327,7 @@ public static ElectricCurrentGradient FromAmperesPerMillisecond(double value) /// /// Creates a from . /// - public static ElectricCurrentGradient FromAmperesPerMinute(double value) + public static ElectricCurrentGradient FromAmperesPerMinute(QuantityValue value) { return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerMinute); } @@ -353,7 +335,7 @@ public static ElectricCurrentGradient FromAmperesPerMinute(double value) /// /// Creates a from . /// - public static ElectricCurrentGradient FromAmperesPerNanosecond(double value) + public static ElectricCurrentGradient FromAmperesPerNanosecond(QuantityValue value) { return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerNanosecond); } @@ -361,7 +343,7 @@ public static ElectricCurrentGradient FromAmperesPerNanosecond(double value) /// /// Creates a from . /// - public static ElectricCurrentGradient FromAmperesPerSecond(double value) + public static ElectricCurrentGradient FromAmperesPerSecond(QuantityValue value) { return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.AmperePerSecond); } @@ -369,7 +351,7 @@ public static ElectricCurrentGradient FromAmperesPerSecond(double value) /// /// Creates a from . /// - public static ElectricCurrentGradient FromMilliamperesPerMinute(double value) + public static ElectricCurrentGradient FromMilliamperesPerMinute(QuantityValue value) { return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.MilliamperePerMinute); } @@ -377,7 +359,7 @@ public static ElectricCurrentGradient FromMilliamperesPerMinute(double value) /// /// Creates a from . /// - public static ElectricCurrentGradient FromMilliamperesPerSecond(double value) + public static ElectricCurrentGradient FromMilliamperesPerSecond(QuantityValue value) { return new ElectricCurrentGradient(value, ElectricCurrentGradientUnit.MilliamperePerSecond); } @@ -388,7 +370,7 @@ public static ElectricCurrentGradient FromMilliamperesPerSecond(double value) /// Value to convert from. /// Unit to convert from. /// ElectricCurrentGradient unit value. - public static ElectricCurrentGradient From(double value, ElectricCurrentGradientUnit fromUnit) + public static ElectricCurrentGradient From(QuantityValue value, ElectricCurrentGradientUnit fromUnit) { return new ElectricCurrentGradient(value, fromUnit); } @@ -449,10 +431,7 @@ public static ElectricCurrentGradient Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricCurrentGradient Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -480,11 +459,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricCurrentG /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricCurrentGradient result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -505,7 +480,7 @@ public static ElectricCurrentGradientUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -516,7 +491,7 @@ public static ElectricCurrentGradientUnit ParseUnit(string str, IFormatProvider? return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricCurrentGradientUnit unit) { return TryParseUnit(str, null, out unit); @@ -531,7 +506,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricCurr /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricCurrentGradientUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -550,35 +525,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricCurrentGradient operator +(ElectricCurrentGradient left, ElectricCurrentGradient right) { - return new ElectricCurrentGradient(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricCurrentGradient(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricCurrentGradient operator -(ElectricCurrentGradient left, ElectricCurrentGradient right) { - return new ElectricCurrentGradient(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricCurrentGradient(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -600,97 +575,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricCurrentGradient left, ElectricCurrentGradient right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricCurrentGradient left, ElectricCurrentGradient right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricCurrentGradient left, ElectricCurrentGradient right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricCurrentGradient left, ElectricCurrentGradient right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricCurrentGradient other, ElectricCurrentGradient tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricCurrentGradient left, ElectricCurrentGradient right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricCurrentGradient other, ElectricCurrentGradient tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricCurrentGradient left, ElectricCurrentGradient right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricCurrentGradient other, ElectricCurrentGradient tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricCurrentGradient otherQuantity)) + if (obj is not ElectricCurrentGradient otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricCurrentGradient other, ElectricCurrentGradient tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricCurrentGradient other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricCurrentGradient. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricCurrentGradient), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricCurrentGradient otherQuantity)) throw new ArgumentException("Expected type ElectricCurrentGradient.", nameof(obj)); + if (obj is not ElectricCurrentGradient otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -702,158 +662,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricCurrentGradient other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricCurrentGradientUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this ElectricCurrentGradient to another ElectricCurrentGradient with the unit representation . - /// - /// The unit to convert to. - /// A ElectricCurrentGradient with the specified unit. - public ElectricCurrentGradient ToUnit(ElectricCurrentGradientUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricCurrentGradient with the specified unit. - public ElectricCurrentGradient ToUnit(ElectricCurrentGradientUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricCurrentGradient), Unit, typeof(ElectricCurrentGradient), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricCurrentGradient)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricCurrentGradientUnit unit, [NotNullWhen(true)] out ElectricCurrentGradient? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricCurrentGradient? convertedOrNull = (Unit, unit) switch - { - // ElectricCurrentGradientUnit -> BaseUnit - (ElectricCurrentGradientUnit.AmperePerMicrosecond, ElectricCurrentGradientUnit.AmperePerSecond) => new ElectricCurrentGradient(_value * 1E6, ElectricCurrentGradientUnit.AmperePerSecond), - (ElectricCurrentGradientUnit.AmperePerMillisecond, ElectricCurrentGradientUnit.AmperePerSecond) => new ElectricCurrentGradient(_value * 1E3, ElectricCurrentGradientUnit.AmperePerSecond), - (ElectricCurrentGradientUnit.AmperePerMinute, ElectricCurrentGradientUnit.AmperePerSecond) => new ElectricCurrentGradient(_value / 60, ElectricCurrentGradientUnit.AmperePerSecond), - (ElectricCurrentGradientUnit.AmperePerNanosecond, ElectricCurrentGradientUnit.AmperePerSecond) => new ElectricCurrentGradient(_value * 1E9, ElectricCurrentGradientUnit.AmperePerSecond), - (ElectricCurrentGradientUnit.MilliamperePerMinute, ElectricCurrentGradientUnit.AmperePerSecond) => new ElectricCurrentGradient((_value / 60) * 1e-3d, ElectricCurrentGradientUnit.AmperePerSecond), - (ElectricCurrentGradientUnit.MilliamperePerSecond, ElectricCurrentGradientUnit.AmperePerSecond) => new ElectricCurrentGradient((_value) * 1e-3d, ElectricCurrentGradientUnit.AmperePerSecond), - - // BaseUnit -> ElectricCurrentGradientUnit - (ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerMicrosecond) => new ElectricCurrentGradient(_value / 1E6, ElectricCurrentGradientUnit.AmperePerMicrosecond), - (ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerMillisecond) => new ElectricCurrentGradient(_value / 1E3, ElectricCurrentGradientUnit.AmperePerMillisecond), - (ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerMinute) => new ElectricCurrentGradient(_value * 60, ElectricCurrentGradientUnit.AmperePerMinute), - (ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.AmperePerNanosecond) => new ElectricCurrentGradient(_value / 1E9, ElectricCurrentGradientUnit.AmperePerNanosecond), - (ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.MilliamperePerMinute) => new ElectricCurrentGradient((_value * 60) / 1e-3d, ElectricCurrentGradientUnit.MilliamperePerMinute), - (ElectricCurrentGradientUnit.AmperePerSecond, ElectricCurrentGradientUnit.MilliamperePerSecond) => new ElectricCurrentGradient((_value) / 1e-3d, ElectricCurrentGradientUnit.MilliamperePerSecond), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricCurrentGradient ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricCurrentGradientUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricCurrentGradientUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ElectricCurrentGradientUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricCurrentGradientUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -868,7 +694,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs index 2eeb140dad..67e3207f81 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricField.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electric_field /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricField : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricFieldUnit? _unit; /// @@ -104,7 +103,7 @@ public static ElectricFieldInfo CreateDefault(Func - /// The for is [T^-3][L][M][I^-1]. + /// The for is T^-3LMI^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 1, -3, -1, 0, 0, 0); @@ -125,9 +124,7 @@ public static IEnumerable> GetDefaultMappings( static ElectricField() { - Info = ElectricFieldInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricFieldInfo.CreateDefault); } /// @@ -135,7 +132,7 @@ static ElectricField() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricField(double value, ElectricFieldUnit unit) + public ElectricField(QuantityValue value, ElectricFieldUnit unit) { _value = value; _unit = unit; @@ -149,7 +146,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -160,7 +157,8 @@ public ElectricField(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -189,10 +187,8 @@ public ElectricField(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -231,28 +227,14 @@ public ElectricField(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double VoltsPerMeter => As(ElectricFieldUnit.VoltPerMeter); + public QuantityValue VoltsPerMeter => this.As(ElectricFieldUnit.VoltPerMeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricFieldUnit -> BaseUnit - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricFieldUnit.VoltPerMeter, ElectricFieldUnit.VoltPerMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricFieldUnit - } - /// /// Get unit abbreviation string. /// @@ -281,7 +263,7 @@ public static string GetAbbreviation(ElectricFieldUnit unit, IFormatProvider? pr /// /// Creates a from . /// - public static ElectricField FromVoltsPerMeter(double value) + public static ElectricField FromVoltsPerMeter(QuantityValue value) { return new ElectricField(value, ElectricFieldUnit.VoltPerMeter); } @@ -292,7 +274,7 @@ public static ElectricField FromVoltsPerMeter(double value) /// Value to convert from. /// Unit to convert from. /// ElectricField unit value. - public static ElectricField From(double value, ElectricFieldUnit fromUnit) + public static ElectricField From(QuantityValue value, ElectricFieldUnit fromUnit) { return new ElectricField(value, fromUnit); } @@ -353,10 +335,7 @@ public static ElectricField Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricField Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -384,11 +363,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricField re /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricField result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -409,7 +384,7 @@ public static ElectricFieldUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -420,7 +395,7 @@ public static ElectricFieldUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricFieldUnit unit) { return TryParseUnit(str, null, out unit); @@ -435,7 +410,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricFiel /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricFieldUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -454,35 +429,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricField operator +(ElectricField left, ElectricField right) { - return new ElectricField(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricField(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricField operator -(ElectricField left, ElectricField right) { - return new ElectricField(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricField(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -494,97 +469,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricField left, ElectricField right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricField left, ElectricField right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricField left, ElectricField right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricField left, ElectricField right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricField other, ElectricField tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricField left, ElectricField right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricField other, ElectricField tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricField left, ElectricField right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricField other, ElectricField tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricField otherQuantity)) + if (obj is not ElectricField otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricField other, ElectricField tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricField other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricField. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricField), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricField otherQuantity)) throw new ArgumentException("Expected type ElectricField.", nameof(obj)); + if (obj is not ElectricField otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -596,146 +556,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricField other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricFieldUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this ElectricField to another ElectricField with the unit representation . - /// - /// The unit to convert to. - /// A ElectricField with the specified unit. - public ElectricField ToUnit(ElectricFieldUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricField with the specified unit. - public ElectricField ToUnit(ElectricFieldUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricField), Unit, typeof(ElectricField), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricField)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricFieldUnit unit, [NotNullWhen(true)] out ElectricField? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricField? convertedOrNull = (Unit, unit) switch - { - // ElectricFieldUnit -> BaseUnit + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> ElectricFieldUnit - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricField ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricFieldUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricFieldUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ElectricFieldUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricFieldUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricFieldUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(ElectricFieldUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -750,7 +588,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricImpedance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricImpedance.g.cs index ea8007ea55..9dff2c8f52 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricImpedance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricImpedance.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -39,7 +37,8 @@ namespace UnitsNet /// [Obsolete("Impedance is a complex number, which is not currently supported by UnitsNet. Please use either ElectricResistance or ElectricReactance instead.")] [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricImpedance : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -54,13 +53,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricImpedanceUnit? _unit; /// @@ -105,7 +104,7 @@ public static ElectricImpedanceInfo CreateDefault(Func - /// The for is [T^-3][L^2][M][I^-2]. + /// The for is T^-3L^2MI^-2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, -2, 0, 0, 0); @@ -120,22 +119,34 @@ public static ElectricImpedanceInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricImpedance. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricImpedanceUnit.Gigaohm, "Gigaohm", "Gigaohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricImpedanceUnit.Kiloohm, "Kiloohm", "Kiloohms", BaseUnits.Undefined); - yield return new (ElectricImpedanceUnit.Megaohm, "Megaohm", "Megaohms", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricImpedanceUnit.Microohm, "Microohm", "Microohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricImpedanceUnit.Milliohm, "Milliohm", "Milliohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricImpedanceUnit.Nanoohm, "Nanoohm", "Nanoohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricImpedanceUnit.Gigaohm, "Gigaohm", "Gigaohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000000) + ); + yield return new (ElectricImpedanceUnit.Kiloohm, "Kiloohm", "Kiloohms", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (ElectricImpedanceUnit.Megaohm, "Megaohm", "Megaohms", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000) + ); + yield return new (ElectricImpedanceUnit.Microohm, "Microohm", "Microohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000000 + ); + yield return new (ElectricImpedanceUnit.Milliohm, "Milliohm", "Milliohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000 + ); + yield return new (ElectricImpedanceUnit.Nanoohm, "Nanoohm", "Nanoohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000000000 + ); yield return new (ElectricImpedanceUnit.Ohm, "Ohm", "Ohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricImpedanceUnit.Teraohm, "Teraohm", "Teraohms", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricImpedanceUnit.Teraohm, "Teraohm", "Teraohms", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000000000) + ); } } static ElectricImpedance() { - Info = ElectricImpedanceInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricImpedanceInfo.CreateDefault); } /// @@ -143,7 +154,7 @@ static ElectricImpedance() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricImpedance(double value, ElectricImpedanceUnit unit) + public ElectricImpedance(QuantityValue value, ElectricImpedanceUnit unit) { _value = value; _unit = unit; @@ -157,7 +168,7 @@ public ElectricImpedance(double value, ElectricImpedanceUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricImpedance(double value, UnitSystem unitSystem) + public ElectricImpedance(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -168,7 +179,8 @@ public ElectricImpedance(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -197,10 +209,8 @@ public ElectricImpedance(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricImpedanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -239,77 +249,49 @@ public ElectricImpedance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigaohms => As(ElectricImpedanceUnit.Gigaohm); + public QuantityValue Gigaohms => this.As(ElectricImpedanceUnit.Gigaohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kiloohms => As(ElectricImpedanceUnit.Kiloohm); + public QuantityValue Kiloohms => this.As(ElectricImpedanceUnit.Kiloohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megaohms => As(ElectricImpedanceUnit.Megaohm); + public QuantityValue Megaohms => this.As(ElectricImpedanceUnit.Megaohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microohms => As(ElectricImpedanceUnit.Microohm); + public QuantityValue Microohms => this.As(ElectricImpedanceUnit.Microohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Milliohms => As(ElectricImpedanceUnit.Milliohm); + public QuantityValue Milliohms => this.As(ElectricImpedanceUnit.Milliohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanoohms => As(ElectricImpedanceUnit.Nanoohm); + public QuantityValue Nanoohms => this.As(ElectricImpedanceUnit.Nanoohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Ohms => As(ElectricImpedanceUnit.Ohm); + public QuantityValue Ohms => this.As(ElectricImpedanceUnit.Ohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Teraohms => As(ElectricImpedanceUnit.Teraohm); + public QuantityValue Teraohms => this.As(ElectricImpedanceUnit.Teraohm); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricImpedanceUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricImpedanceUnit.Gigaohm, ElectricImpedanceUnit.Ohm, quantity => quantity.ToUnit(ElectricImpedanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricImpedanceUnit.Kiloohm, ElectricImpedanceUnit.Ohm, quantity => quantity.ToUnit(ElectricImpedanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricImpedanceUnit.Megaohm, ElectricImpedanceUnit.Ohm, quantity => quantity.ToUnit(ElectricImpedanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricImpedanceUnit.Microohm, ElectricImpedanceUnit.Ohm, quantity => quantity.ToUnit(ElectricImpedanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricImpedanceUnit.Milliohm, ElectricImpedanceUnit.Ohm, quantity => quantity.ToUnit(ElectricImpedanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricImpedanceUnit.Nanoohm, ElectricImpedanceUnit.Ohm, quantity => quantity.ToUnit(ElectricImpedanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricImpedanceUnit.Teraohm, ElectricImpedanceUnit.Ohm, quantity => quantity.ToUnit(ElectricImpedanceUnit.Ohm)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricImpedanceUnit.Ohm, ElectricImpedanceUnit.Ohm, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricImpedanceUnit - unitConverter.SetConversionFunction(ElectricImpedanceUnit.Ohm, ElectricImpedanceUnit.Gigaohm, quantity => quantity.ToUnit(ElectricImpedanceUnit.Gigaohm)); - unitConverter.SetConversionFunction(ElectricImpedanceUnit.Ohm, ElectricImpedanceUnit.Kiloohm, quantity => quantity.ToUnit(ElectricImpedanceUnit.Kiloohm)); - unitConverter.SetConversionFunction(ElectricImpedanceUnit.Ohm, ElectricImpedanceUnit.Megaohm, quantity => quantity.ToUnit(ElectricImpedanceUnit.Megaohm)); - unitConverter.SetConversionFunction(ElectricImpedanceUnit.Ohm, ElectricImpedanceUnit.Microohm, quantity => quantity.ToUnit(ElectricImpedanceUnit.Microohm)); - unitConverter.SetConversionFunction(ElectricImpedanceUnit.Ohm, ElectricImpedanceUnit.Milliohm, quantity => quantity.ToUnit(ElectricImpedanceUnit.Milliohm)); - unitConverter.SetConversionFunction(ElectricImpedanceUnit.Ohm, ElectricImpedanceUnit.Nanoohm, quantity => quantity.ToUnit(ElectricImpedanceUnit.Nanoohm)); - unitConverter.SetConversionFunction(ElectricImpedanceUnit.Ohm, ElectricImpedanceUnit.Teraohm, quantity => quantity.ToUnit(ElectricImpedanceUnit.Teraohm)); - } - /// /// Get unit abbreviation string. /// @@ -338,7 +320,7 @@ public static string GetAbbreviation(ElectricImpedanceUnit unit, IFormatProvider /// /// Creates a from . /// - public static ElectricImpedance FromGigaohms(double value) + public static ElectricImpedance FromGigaohms(QuantityValue value) { return new ElectricImpedance(value, ElectricImpedanceUnit.Gigaohm); } @@ -346,7 +328,7 @@ public static ElectricImpedance FromGigaohms(double value) /// /// Creates a from . /// - public static ElectricImpedance FromKiloohms(double value) + public static ElectricImpedance FromKiloohms(QuantityValue value) { return new ElectricImpedance(value, ElectricImpedanceUnit.Kiloohm); } @@ -354,7 +336,7 @@ public static ElectricImpedance FromKiloohms(double value) /// /// Creates a from . /// - public static ElectricImpedance FromMegaohms(double value) + public static ElectricImpedance FromMegaohms(QuantityValue value) { return new ElectricImpedance(value, ElectricImpedanceUnit.Megaohm); } @@ -362,7 +344,7 @@ public static ElectricImpedance FromMegaohms(double value) /// /// Creates a from . /// - public static ElectricImpedance FromMicroohms(double value) + public static ElectricImpedance FromMicroohms(QuantityValue value) { return new ElectricImpedance(value, ElectricImpedanceUnit.Microohm); } @@ -370,7 +352,7 @@ public static ElectricImpedance FromMicroohms(double value) /// /// Creates a from . /// - public static ElectricImpedance FromMilliohms(double value) + public static ElectricImpedance FromMilliohms(QuantityValue value) { return new ElectricImpedance(value, ElectricImpedanceUnit.Milliohm); } @@ -378,7 +360,7 @@ public static ElectricImpedance FromMilliohms(double value) /// /// Creates a from . /// - public static ElectricImpedance FromNanoohms(double value) + public static ElectricImpedance FromNanoohms(QuantityValue value) { return new ElectricImpedance(value, ElectricImpedanceUnit.Nanoohm); } @@ -386,7 +368,7 @@ public static ElectricImpedance FromNanoohms(double value) /// /// Creates a from . /// - public static ElectricImpedance FromOhms(double value) + public static ElectricImpedance FromOhms(QuantityValue value) { return new ElectricImpedance(value, ElectricImpedanceUnit.Ohm); } @@ -394,7 +376,7 @@ public static ElectricImpedance FromOhms(double value) /// /// Creates a from . /// - public static ElectricImpedance FromTeraohms(double value) + public static ElectricImpedance FromTeraohms(QuantityValue value) { return new ElectricImpedance(value, ElectricImpedanceUnit.Teraohm); } @@ -405,7 +387,7 @@ public static ElectricImpedance FromTeraohms(double value) /// Value to convert from. /// Unit to convert from. /// ElectricImpedance unit value. - public static ElectricImpedance From(double value, ElectricImpedanceUnit fromUnit) + public static ElectricImpedance From(QuantityValue value, ElectricImpedanceUnit fromUnit) { return new ElectricImpedance(value, fromUnit); } @@ -466,10 +448,7 @@ public static ElectricImpedance Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricImpedance Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -497,11 +476,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricImpedanc /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricImpedance result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -522,7 +497,7 @@ public static ElectricImpedanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -533,7 +508,7 @@ public static ElectricImpedanceUnit ParseUnit(string str, IFormatProvider? provi return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricImpedanceUnit unit) { return TryParseUnit(str, null, out unit); @@ -548,7 +523,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricImpe /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricImpedanceUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -567,35 +542,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricImpedance operator +(ElectricImpedance left, ElectricImpedance right) { - return new ElectricImpedance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricImpedance(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricImpedance operator -(ElectricImpedance left, ElectricImpedance right) { - return new ElectricImpedance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricImpedance(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static ElectricImpedance operator *(double left, ElectricImpedance right) + public static ElectricImpedance operator *(QuantityValue left, ElectricImpedance right) { return new ElectricImpedance(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricImpedance operator *(ElectricImpedance left, double right) + public static ElectricImpedance operator *(ElectricImpedance left, QuantityValue right) { return new ElectricImpedance(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricImpedance operator /(ElectricImpedance left, double right) + public static ElectricImpedance operator /(ElectricImpedance left, QuantityValue right) { return new ElectricImpedance(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricImpedance left, ElectricImpedance right) + public static QuantityValue operator /(ElectricImpedance left, ElectricImpedance right) { return left.Ohms / right.Ohms; } @@ -607,97 +582,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricImpedance left, ElectricImpedance right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricImpedance left, ElectricImpedance right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricImpedance left, ElectricImpedance right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricImpedance left, ElectricImpedance right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricImpedance other, ElectricImpedance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricImpedance left, ElectricImpedance right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricImpedance other, ElectricImpedance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricImpedance left, ElectricImpedance right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricImpedance other, ElectricImpedance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricImpedance otherQuantity)) + if (obj is not ElectricImpedance otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricImpedance other, ElectricImpedance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricImpedance other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricImpedance. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricImpedance), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricImpedance otherQuantity)) throw new ArgumentException("Expected type ElectricImpedance.", nameof(obj)); + if (obj is not ElectricImpedance otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -709,160 +669,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricImpedance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricImpedanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this ElectricImpedance to another ElectricImpedance with the unit representation . - /// - /// The unit to convert to. - /// A ElectricImpedance with the specified unit. - public ElectricImpedance ToUnit(ElectricImpedanceUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricImpedance with the specified unit. - public ElectricImpedance ToUnit(ElectricImpedanceUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricImpedance), Unit, typeof(ElectricImpedance), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricImpedance)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricImpedanceUnit unit, [NotNullWhen(true)] out ElectricImpedance? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricImpedance? convertedOrNull = (Unit, unit) switch - { - // ElectricImpedanceUnit -> BaseUnit - (ElectricImpedanceUnit.Gigaohm, ElectricImpedanceUnit.Ohm) => new ElectricImpedance((_value) * 1e9d, ElectricImpedanceUnit.Ohm), - (ElectricImpedanceUnit.Kiloohm, ElectricImpedanceUnit.Ohm) => new ElectricImpedance((_value) * 1e3d, ElectricImpedanceUnit.Ohm), - (ElectricImpedanceUnit.Megaohm, ElectricImpedanceUnit.Ohm) => new ElectricImpedance((_value) * 1e6d, ElectricImpedanceUnit.Ohm), - (ElectricImpedanceUnit.Microohm, ElectricImpedanceUnit.Ohm) => new ElectricImpedance((_value) * 1e-6d, ElectricImpedanceUnit.Ohm), - (ElectricImpedanceUnit.Milliohm, ElectricImpedanceUnit.Ohm) => new ElectricImpedance((_value) * 1e-3d, ElectricImpedanceUnit.Ohm), - (ElectricImpedanceUnit.Nanoohm, ElectricImpedanceUnit.Ohm) => new ElectricImpedance((_value) * 1e-9d, ElectricImpedanceUnit.Ohm), - (ElectricImpedanceUnit.Teraohm, ElectricImpedanceUnit.Ohm) => new ElectricImpedance((_value) * 1e12d, ElectricImpedanceUnit.Ohm), - - // BaseUnit -> ElectricImpedanceUnit - (ElectricImpedanceUnit.Ohm, ElectricImpedanceUnit.Gigaohm) => new ElectricImpedance((_value) / 1e9d, ElectricImpedanceUnit.Gigaohm), - (ElectricImpedanceUnit.Ohm, ElectricImpedanceUnit.Kiloohm) => new ElectricImpedance((_value) / 1e3d, ElectricImpedanceUnit.Kiloohm), - (ElectricImpedanceUnit.Ohm, ElectricImpedanceUnit.Megaohm) => new ElectricImpedance((_value) / 1e6d, ElectricImpedanceUnit.Megaohm), - (ElectricImpedanceUnit.Ohm, ElectricImpedanceUnit.Microohm) => new ElectricImpedance((_value) / 1e-6d, ElectricImpedanceUnit.Microohm), - (ElectricImpedanceUnit.Ohm, ElectricImpedanceUnit.Milliohm) => new ElectricImpedance((_value) / 1e-3d, ElectricImpedanceUnit.Milliohm), - (ElectricImpedanceUnit.Ohm, ElectricImpedanceUnit.Nanoohm) => new ElectricImpedance((_value) / 1e-9d, ElectricImpedanceUnit.Nanoohm), - (ElectricImpedanceUnit.Ohm, ElectricImpedanceUnit.Teraohm) => new ElectricImpedance((_value) / 1e12d, ElectricImpedanceUnit.Teraohm), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricImpedance ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricImpedanceUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricImpedanceUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ElectricImpedanceUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricImpedanceUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ElectricImpedanceUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricImpedanceUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -877,7 +701,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs index 23b73bf158..fbbc6e8388 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricInductance.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Inductance /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricInductance : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricInductanceUnit? _unit; /// @@ -104,7 +103,7 @@ public static ElectricInductanceInfo CreateDefault(Func - /// The for is [T^-2][L^2][M][I^-2]. + /// The for is T^-2L^2MI^-2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, -2, 0, 0, 0); @@ -120,18 +119,24 @@ public static ElectricInductanceInfo CreateDefault(Func> GetDefaultMappings() { yield return new (ElectricInductanceUnit.Henry, "Henry", "Henries", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricInductanceUnit.Microhenry, "Microhenry", "Microhenries", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricInductanceUnit.Millihenry, "Millihenry", "Millihenries", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricInductanceUnit.Nanohenry, "Nanohenry", "Nanohenries", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricInductanceUnit.Picohenry, "Picohenry", "Picohenries", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricInductanceUnit.Microhenry, "Microhenry", "Microhenries", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000000 + ); + yield return new (ElectricInductanceUnit.Millihenry, "Millihenry", "Millihenries", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000 + ); + yield return new (ElectricInductanceUnit.Nanohenry, "Nanohenry", "Nanohenries", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000000000 + ); + yield return new (ElectricInductanceUnit.Picohenry, "Picohenry", "Picohenries", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000000000000 + ); } } static ElectricInductance() { - Info = ElectricInductanceInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricInductanceInfo.CreateDefault); } /// @@ -139,7 +144,7 @@ static ElectricInductance() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricInductance(double value, ElectricInductanceUnit unit) + public ElectricInductance(QuantityValue value, ElectricInductanceUnit unit) { _value = value; _unit = unit; @@ -153,7 +158,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -164,7 +169,8 @@ public ElectricInductance(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -193,10 +199,8 @@ public ElectricInductance(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricInductanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -235,56 +239,34 @@ public ElectricInductance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Henries => As(ElectricInductanceUnit.Henry); + public QuantityValue Henries => this.As(ElectricInductanceUnit.Henry); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microhenries => As(ElectricInductanceUnit.Microhenry); + public QuantityValue Microhenries => this.As(ElectricInductanceUnit.Microhenry); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millihenries => As(ElectricInductanceUnit.Millihenry); + public QuantityValue Millihenries => this.As(ElectricInductanceUnit.Millihenry); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanohenries => As(ElectricInductanceUnit.Nanohenry); + public QuantityValue Nanohenries => this.As(ElectricInductanceUnit.Nanohenry); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Picohenries => As(ElectricInductanceUnit.Picohenry); + public QuantityValue Picohenries => this.As(ElectricInductanceUnit.Picohenry); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricInductanceUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricInductanceUnit.Microhenry, ElectricInductanceUnit.Henry, quantity => quantity.ToUnit(ElectricInductanceUnit.Henry)); - unitConverter.SetConversionFunction(ElectricInductanceUnit.Millihenry, ElectricInductanceUnit.Henry, quantity => quantity.ToUnit(ElectricInductanceUnit.Henry)); - unitConverter.SetConversionFunction(ElectricInductanceUnit.Nanohenry, ElectricInductanceUnit.Henry, quantity => quantity.ToUnit(ElectricInductanceUnit.Henry)); - unitConverter.SetConversionFunction(ElectricInductanceUnit.Picohenry, ElectricInductanceUnit.Henry, quantity => quantity.ToUnit(ElectricInductanceUnit.Henry)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricInductanceUnit.Henry, ElectricInductanceUnit.Henry, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricInductanceUnit - unitConverter.SetConversionFunction(ElectricInductanceUnit.Henry, ElectricInductanceUnit.Microhenry, quantity => quantity.ToUnit(ElectricInductanceUnit.Microhenry)); - unitConverter.SetConversionFunction(ElectricInductanceUnit.Henry, ElectricInductanceUnit.Millihenry, quantity => quantity.ToUnit(ElectricInductanceUnit.Millihenry)); - unitConverter.SetConversionFunction(ElectricInductanceUnit.Henry, ElectricInductanceUnit.Nanohenry, quantity => quantity.ToUnit(ElectricInductanceUnit.Nanohenry)); - unitConverter.SetConversionFunction(ElectricInductanceUnit.Henry, ElectricInductanceUnit.Picohenry, quantity => quantity.ToUnit(ElectricInductanceUnit.Picohenry)); - } - /// /// Get unit abbreviation string. /// @@ -313,7 +295,7 @@ public static string GetAbbreviation(ElectricInductanceUnit unit, IFormatProvide /// /// Creates a from . /// - public static ElectricInductance FromHenries(double value) + public static ElectricInductance FromHenries(QuantityValue value) { return new ElectricInductance(value, ElectricInductanceUnit.Henry); } @@ -321,7 +303,7 @@ public static ElectricInductance FromHenries(double value) /// /// Creates a from . /// - public static ElectricInductance FromMicrohenries(double value) + public static ElectricInductance FromMicrohenries(QuantityValue value) { return new ElectricInductance(value, ElectricInductanceUnit.Microhenry); } @@ -329,7 +311,7 @@ public static ElectricInductance FromMicrohenries(double value) /// /// Creates a from . /// - public static ElectricInductance FromMillihenries(double value) + public static ElectricInductance FromMillihenries(QuantityValue value) { return new ElectricInductance(value, ElectricInductanceUnit.Millihenry); } @@ -337,7 +319,7 @@ public static ElectricInductance FromMillihenries(double value) /// /// Creates a from . /// - public static ElectricInductance FromNanohenries(double value) + public static ElectricInductance FromNanohenries(QuantityValue value) { return new ElectricInductance(value, ElectricInductanceUnit.Nanohenry); } @@ -345,7 +327,7 @@ public static ElectricInductance FromNanohenries(double value) /// /// Creates a from . /// - public static ElectricInductance FromPicohenries(double value) + public static ElectricInductance FromPicohenries(QuantityValue value) { return new ElectricInductance(value, ElectricInductanceUnit.Picohenry); } @@ -356,7 +338,7 @@ public static ElectricInductance FromPicohenries(double value) /// Value to convert from. /// Unit to convert from. /// ElectricInductance unit value. - public static ElectricInductance From(double value, ElectricInductanceUnit fromUnit) + public static ElectricInductance From(QuantityValue value, ElectricInductanceUnit fromUnit) { return new ElectricInductance(value, fromUnit); } @@ -417,10 +399,7 @@ public static ElectricInductance Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricInductance Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -448,11 +427,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricInductan /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricInductance result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -473,7 +448,7 @@ public static ElectricInductanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -484,7 +459,7 @@ public static ElectricInductanceUnit ParseUnit(string str, IFormatProvider? prov return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricInductanceUnit unit) { return TryParseUnit(str, null, out unit); @@ -499,7 +474,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricIndu /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricInductanceUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -518,35 +493,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricInductance operator +(ElectricInductance left, ElectricInductance right) { - return new ElectricInductance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricInductance(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricInductance operator -(ElectricInductance left, ElectricInductance right) { - return new ElectricInductance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricInductance(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -558,97 +533,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricInductance left, ElectricInductance right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricInductance left, ElectricInductance right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricInductance left, ElectricInductance right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricInductance left, ElectricInductance right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricInductance other, ElectricInductance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricInductance left, ElectricInductance right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricInductance other, ElectricInductance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricInductance left, ElectricInductance right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricInductance other, ElectricInductance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricInductance otherQuantity)) + if (obj is not ElectricInductance otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricInductance other, ElectricInductance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricInductance other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricInductance. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricInductance), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricInductance otherQuantity)) throw new ArgumentException("Expected type ElectricInductance.", nameof(obj)); + if (obj is not ElectricInductance otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -660,154 +620,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricInductance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricInductanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this ElectricInductance to another ElectricInductance with the unit representation . - /// - /// The unit to convert to. - /// A ElectricInductance with the specified unit. - public ElectricInductance ToUnit(ElectricInductanceUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricInductance with the specified unit. - public ElectricInductance ToUnit(ElectricInductanceUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricInductance), Unit, typeof(ElectricInductance), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricInductance)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricInductanceUnit unit, [NotNullWhen(true)] out ElectricInductance? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricInductance? convertedOrNull = (Unit, unit) switch - { - // ElectricInductanceUnit -> BaseUnit - (ElectricInductanceUnit.Microhenry, ElectricInductanceUnit.Henry) => new ElectricInductance((_value) * 1e-6d, ElectricInductanceUnit.Henry), - (ElectricInductanceUnit.Millihenry, ElectricInductanceUnit.Henry) => new ElectricInductance((_value) * 1e-3d, ElectricInductanceUnit.Henry), - (ElectricInductanceUnit.Nanohenry, ElectricInductanceUnit.Henry) => new ElectricInductance((_value) * 1e-9d, ElectricInductanceUnit.Henry), - (ElectricInductanceUnit.Picohenry, ElectricInductanceUnit.Henry) => new ElectricInductance((_value) * 1e-12d, ElectricInductanceUnit.Henry), - - // BaseUnit -> ElectricInductanceUnit - (ElectricInductanceUnit.Henry, ElectricInductanceUnit.Microhenry) => new ElectricInductance((_value) / 1e-6d, ElectricInductanceUnit.Microhenry), - (ElectricInductanceUnit.Henry, ElectricInductanceUnit.Millihenry) => new ElectricInductance((_value) / 1e-3d, ElectricInductanceUnit.Millihenry), - (ElectricInductanceUnit.Henry, ElectricInductanceUnit.Nanohenry) => new ElectricInductance((_value) / 1e-9d, ElectricInductanceUnit.Nanohenry), - (ElectricInductanceUnit.Henry, ElectricInductanceUnit.Picohenry) => new ElectricInductance((_value) / 1e-12d, ElectricInductanceUnit.Picohenry), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricInductance ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricInductanceUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricInductanceUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ElectricInductanceUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricInductanceUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -822,7 +652,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs index 5b34019916..e6e61249ee 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotential.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// If you want to map more parameters into the ElectricPotential class (volts RMS, phase angle, etc.), create your own wrapper type such as a record or named tuple. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricPotential : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -59,13 +58,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricPotentialUnit? _unit; /// @@ -110,7 +109,7 @@ public static ElectricPotentialInfo CreateDefault(Func - /// The for is [T^-3][L^2][M][I^-1]. + /// The for is T^-3L^2MI^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, -1, 0, 0, 0); @@ -125,20 +124,28 @@ public static ElectricPotentialInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricPotential. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricPotentialUnit.Kilovolt, "Kilovolt", "Kilovolts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere)); - yield return new (ElectricPotentialUnit.Megavolt, "Megavolt", "Megavolts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere)); - yield return new (ElectricPotentialUnit.Microvolt, "Microvolt", "Microvolts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricPotentialUnit.Millivolt, "Millivolt", "Millivolts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricPotentialUnit.Nanovolt, "Nanovolt", "Nanovolts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricPotentialUnit.Kilovolt, "Kilovolt", "Kilovolts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), + new QuantityValue(1, 1000) + ); + yield return new (ElectricPotentialUnit.Megavolt, "Megavolt", "Megavolts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere), + new QuantityValue(1, 1000000) + ); + yield return new (ElectricPotentialUnit.Microvolt, "Microvolt", "Microvolts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000000 + ); + yield return new (ElectricPotentialUnit.Millivolt, "Millivolt", "Millivolts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000 + ); + yield return new (ElectricPotentialUnit.Nanovolt, "Nanovolt", "Nanovolts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000000000 + ); yield return new (ElectricPotentialUnit.Volt, "Volt", "Volts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); } } static ElectricPotential() { - Info = ElectricPotentialInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricPotentialInfo.CreateDefault); } /// @@ -146,7 +153,7 @@ static ElectricPotential() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricPotential(double value, ElectricPotentialUnit unit) + public ElectricPotential(QuantityValue value, ElectricPotentialUnit unit) { _value = value; _unit = unit; @@ -160,7 +167,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -171,7 +178,8 @@ public ElectricPotential(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -200,10 +208,8 @@ public ElectricPotential(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricPotentialUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -242,63 +248,39 @@ public ElectricPotential(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilovolts => As(ElectricPotentialUnit.Kilovolt); + public QuantityValue Kilovolts => this.As(ElectricPotentialUnit.Kilovolt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megavolts => As(ElectricPotentialUnit.Megavolt); + public QuantityValue Megavolts => this.As(ElectricPotentialUnit.Megavolt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microvolts => As(ElectricPotentialUnit.Microvolt); + public QuantityValue Microvolts => this.As(ElectricPotentialUnit.Microvolt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millivolts => As(ElectricPotentialUnit.Millivolt); + public QuantityValue Millivolts => this.As(ElectricPotentialUnit.Millivolt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanovolts => As(ElectricPotentialUnit.Nanovolt); + public QuantityValue Nanovolts => this.As(ElectricPotentialUnit.Nanovolt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Volts => As(ElectricPotentialUnit.Volt); + public QuantityValue Volts => this.As(ElectricPotentialUnit.Volt); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricPotentialUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricPotentialUnit.Kilovolt, ElectricPotentialUnit.Volt, quantity => quantity.ToUnit(ElectricPotentialUnit.Volt)); - unitConverter.SetConversionFunction(ElectricPotentialUnit.Megavolt, ElectricPotentialUnit.Volt, quantity => quantity.ToUnit(ElectricPotentialUnit.Volt)); - unitConverter.SetConversionFunction(ElectricPotentialUnit.Microvolt, ElectricPotentialUnit.Volt, quantity => quantity.ToUnit(ElectricPotentialUnit.Volt)); - unitConverter.SetConversionFunction(ElectricPotentialUnit.Millivolt, ElectricPotentialUnit.Volt, quantity => quantity.ToUnit(ElectricPotentialUnit.Volt)); - unitConverter.SetConversionFunction(ElectricPotentialUnit.Nanovolt, ElectricPotentialUnit.Volt, quantity => quantity.ToUnit(ElectricPotentialUnit.Volt)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Volt, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricPotentialUnit - unitConverter.SetConversionFunction(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Kilovolt, quantity => quantity.ToUnit(ElectricPotentialUnit.Kilovolt)); - unitConverter.SetConversionFunction(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Megavolt, quantity => quantity.ToUnit(ElectricPotentialUnit.Megavolt)); - unitConverter.SetConversionFunction(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Microvolt, quantity => quantity.ToUnit(ElectricPotentialUnit.Microvolt)); - unitConverter.SetConversionFunction(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Millivolt, quantity => quantity.ToUnit(ElectricPotentialUnit.Millivolt)); - unitConverter.SetConversionFunction(ElectricPotentialUnit.Volt, ElectricPotentialUnit.Nanovolt, quantity => quantity.ToUnit(ElectricPotentialUnit.Nanovolt)); - } - /// /// Get unit abbreviation string. /// @@ -327,7 +309,7 @@ public static string GetAbbreviation(ElectricPotentialUnit unit, IFormatProvider /// /// Creates a from . /// - public static ElectricPotential FromKilovolts(double value) + public static ElectricPotential FromKilovolts(QuantityValue value) { return new ElectricPotential(value, ElectricPotentialUnit.Kilovolt); } @@ -335,7 +317,7 @@ public static ElectricPotential FromKilovolts(double value) /// /// Creates a from . /// - public static ElectricPotential FromMegavolts(double value) + public static ElectricPotential FromMegavolts(QuantityValue value) { return new ElectricPotential(value, ElectricPotentialUnit.Megavolt); } @@ -343,7 +325,7 @@ public static ElectricPotential FromMegavolts(double value) /// /// Creates a from . /// - public static ElectricPotential FromMicrovolts(double value) + public static ElectricPotential FromMicrovolts(QuantityValue value) { return new ElectricPotential(value, ElectricPotentialUnit.Microvolt); } @@ -351,7 +333,7 @@ public static ElectricPotential FromMicrovolts(double value) /// /// Creates a from . /// - public static ElectricPotential FromMillivolts(double value) + public static ElectricPotential FromMillivolts(QuantityValue value) { return new ElectricPotential(value, ElectricPotentialUnit.Millivolt); } @@ -359,7 +341,7 @@ public static ElectricPotential FromMillivolts(double value) /// /// Creates a from . /// - public static ElectricPotential FromNanovolts(double value) + public static ElectricPotential FromNanovolts(QuantityValue value) { return new ElectricPotential(value, ElectricPotentialUnit.Nanovolt); } @@ -367,7 +349,7 @@ public static ElectricPotential FromNanovolts(double value) /// /// Creates a from . /// - public static ElectricPotential FromVolts(double value) + public static ElectricPotential FromVolts(QuantityValue value) { return new ElectricPotential(value, ElectricPotentialUnit.Volt); } @@ -378,7 +360,7 @@ public static ElectricPotential FromVolts(double value) /// Value to convert from. /// Unit to convert from. /// ElectricPotential unit value. - public static ElectricPotential From(double value, ElectricPotentialUnit fromUnit) + public static ElectricPotential From(QuantityValue value, ElectricPotentialUnit fromUnit) { return new ElectricPotential(value, fromUnit); } @@ -439,10 +421,7 @@ public static ElectricPotential Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricPotential Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -470,11 +449,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricPotentia /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricPotential result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -495,7 +470,7 @@ public static ElectricPotentialUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -506,7 +481,7 @@ public static ElectricPotentialUnit ParseUnit(string str, IFormatProvider? provi return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricPotentialUnit unit) { return TryParseUnit(str, null, out unit); @@ -521,7 +496,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricPote /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricPotentialUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -540,35 +515,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricPotential operator +(ElectricPotential left, ElectricPotential right) { - return new ElectricPotential(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricPotential(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricPotential operator -(ElectricPotential left, ElectricPotential right) { - return new ElectricPotential(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricPotential(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -608,97 +583,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricPotential left, ElectricPotential right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricPotential left, ElectricPotential right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricPotential left, ElectricPotential right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricPotential left, ElectricPotential right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricPotential other, ElectricPotential tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricPotential left, ElectricPotential right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricPotential other, ElectricPotential tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricPotential left, ElectricPotential right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricPotential other, ElectricPotential tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricPotential otherQuantity)) + if (obj is not ElectricPotential otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricPotential other, ElectricPotential tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricPotential other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricPotential. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricPotential), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricPotential otherQuantity)) throw new ArgumentException("Expected type ElectricPotential.", nameof(obj)); + if (obj is not ElectricPotential otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -710,156 +670,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricPotential other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricPotentialUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this ElectricPotential to another ElectricPotential with the unit representation . - /// - /// The unit to convert to. - /// A ElectricPotential with the specified unit. - public ElectricPotential ToUnit(ElectricPotentialUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricPotential with the specified unit. - public ElectricPotential ToUnit(ElectricPotentialUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricPotential), Unit, typeof(ElectricPotential), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricPotential)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricPotentialUnit unit, [NotNullWhen(true)] out ElectricPotential? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricPotential? convertedOrNull = (Unit, unit) switch - { - // ElectricPotentialUnit -> BaseUnit - (ElectricPotentialUnit.Kilovolt, ElectricPotentialUnit.Volt) => new ElectricPotential((_value) * 1e3d, ElectricPotentialUnit.Volt), - (ElectricPotentialUnit.Megavolt, ElectricPotentialUnit.Volt) => new ElectricPotential((_value) * 1e6d, ElectricPotentialUnit.Volt), - (ElectricPotentialUnit.Microvolt, ElectricPotentialUnit.Volt) => new ElectricPotential((_value) * 1e-6d, ElectricPotentialUnit.Volt), - (ElectricPotentialUnit.Millivolt, ElectricPotentialUnit.Volt) => new ElectricPotential((_value) * 1e-3d, ElectricPotentialUnit.Volt), - (ElectricPotentialUnit.Nanovolt, ElectricPotentialUnit.Volt) => new ElectricPotential((_value) * 1e-9d, ElectricPotentialUnit.Volt), - - // BaseUnit -> ElectricPotentialUnit - (ElectricPotentialUnit.Volt, ElectricPotentialUnit.Kilovolt) => new ElectricPotential((_value) / 1e3d, ElectricPotentialUnit.Kilovolt), - (ElectricPotentialUnit.Volt, ElectricPotentialUnit.Megavolt) => new ElectricPotential((_value) / 1e6d, ElectricPotentialUnit.Megavolt), - (ElectricPotentialUnit.Volt, ElectricPotentialUnit.Microvolt) => new ElectricPotential((_value) / 1e-6d, ElectricPotentialUnit.Microvolt), - (ElectricPotentialUnit.Volt, ElectricPotentialUnit.Millivolt) => new ElectricPotential((_value) / 1e-3d, ElectricPotentialUnit.Millivolt), - (ElectricPotentialUnit.Volt, ElectricPotentialUnit.Nanovolt) => new ElectricPotential((_value) / 1e-9d, ElectricPotentialUnit.Nanovolt), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricPotential ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricPotentialUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ElectricPotentialUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricPotentialUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -874,7 +702,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs index 981f293340..cd97a64336 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricPotentialChangeRate.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricPotentialChangeRate : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricPotentialChangeRateUnit? _unit; /// @@ -101,7 +100,7 @@ public static ElectricPotentialChangeRateInfo CreateDefault(Func - /// The for is [T^-4][L^2][M][I^-1]. + /// The for is T^-4L^2MI^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -4, -1, 0, 0, 0); @@ -116,34 +115,70 @@ public static ElectricPotentialChangeRateInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricPotentialChangeRate. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricPotentialChangeRateUnit.KilovoltPerHour, "KilovoltPerHour", "KilovoltsPerHour", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Hour, current: ElectricCurrentUnit.Milliampere)); - yield return new (ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, "KilovoltPerMicrosecond", "KilovoltsPerMicrosecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Milliampere)); - yield return new (ElectricPotentialChangeRateUnit.KilovoltPerMinute, "KilovoltPerMinute", "KilovoltsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute, current: ElectricCurrentUnit.Milliampere)); - yield return new (ElectricPotentialChangeRateUnit.KilovoltPerSecond, "KilovoltPerSecond", "KilovoltsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere)); - yield return new (ElectricPotentialChangeRateUnit.MegavoltPerHour, "MegavoltPerHour", "MegavoltsPerHour", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Hour, current: ElectricCurrentUnit.Microampere)); - yield return new (ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, "MegavoltPerMicrosecond", "MegavoltsPerMicrosecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Microampere)); - yield return new (ElectricPotentialChangeRateUnit.MegavoltPerMinute, "MegavoltPerMinute", "MegavoltsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute, current: ElectricCurrentUnit.Microampere)); - yield return new (ElectricPotentialChangeRateUnit.MegavoltPerSecond, "MegavoltPerSecond", "MegavoltsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere)); - yield return new (ElectricPotentialChangeRateUnit.MicrovoltPerHour, "MicrovoltPerHour", "MicrovoltsPerHour", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Hour, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, "MicrovoltPerMicrosecond", "MicrovoltsPerMicrosecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricPotentialChangeRateUnit.MicrovoltPerMinute, "MicrovoltPerMinute", "MicrovoltsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Minute, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricPotentialChangeRateUnit.MicrovoltPerSecond, "MicrovoltPerSecond", "MicrovoltsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricPotentialChangeRateUnit.MillivoltPerHour, "MillivoltPerHour", "MillivoltsPerHour", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Hour, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, "MillivoltPerMicrosecond", "MillivoltsPerMicrosecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricPotentialChangeRateUnit.MillivoltPerMinute, "MillivoltPerMinute", "MillivoltsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Minute, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricPotentialChangeRateUnit.MillivoltPerSecond, "MillivoltPerSecond", "MillivoltsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricPotentialChangeRateUnit.VoltPerHour, "VoltPerHour", "VoltsPerHour", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Hour, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricPotentialChangeRateUnit.VoltPerMicrosecond, "VoltPerMicrosecond", "VoltsPerMicrosecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricPotentialChangeRateUnit.VoltPerMinute, "VoltPerMinute", "VoltsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricPotentialChangeRateUnit.KilovoltPerHour, "KilovoltPerHour", "KilovoltsPerHour", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Hour, current: ElectricCurrentUnit.Milliampere), + new QuantityValue(18, 5) + ); + yield return new (ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, "KilovoltPerMicrosecond", "KilovoltsPerMicrosecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Milliampere), + new QuantityValue(1, 1000000000) + ); + yield return new (ElectricPotentialChangeRateUnit.KilovoltPerMinute, "KilovoltPerMinute", "KilovoltsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute, current: ElectricCurrentUnit.Milliampere), + new QuantityValue(3, 50) + ); + yield return new (ElectricPotentialChangeRateUnit.KilovoltPerSecond, "KilovoltPerSecond", "KilovoltsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), + new QuantityValue(1, 1000) + ); + yield return new (ElectricPotentialChangeRateUnit.MegavoltPerHour, "MegavoltPerHour", "MegavoltsPerHour", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Hour, current: ElectricCurrentUnit.Microampere), + new QuantityValue(9, 2500) + ); + yield return new (ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, "MegavoltPerMicrosecond", "MegavoltsPerMicrosecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Microampere), + new QuantityValue(1, 1000000000000) + ); + yield return new (ElectricPotentialChangeRateUnit.MegavoltPerMinute, "MegavoltPerMinute", "MegavoltsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute, current: ElectricCurrentUnit.Microampere), + new QuantityValue(3, 50000) + ); + yield return new (ElectricPotentialChangeRateUnit.MegavoltPerSecond, "MegavoltPerSecond", "MegavoltsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere), + new QuantityValue(1, 1000000) + ); + yield return new (ElectricPotentialChangeRateUnit.MicrovoltPerHour, "MicrovoltPerHour", "MicrovoltsPerHour", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Hour, current: ElectricCurrentUnit.Ampere), + 3600000000 + ); + yield return new (ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, "MicrovoltPerMicrosecond", "MicrovoltsPerMicrosecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Ampere), + 1 + ); + yield return new (ElectricPotentialChangeRateUnit.MicrovoltPerMinute, "MicrovoltPerMinute", "MicrovoltsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Minute, current: ElectricCurrentUnit.Ampere), + 60000000 + ); + yield return new (ElectricPotentialChangeRateUnit.MicrovoltPerSecond, "MicrovoltPerSecond", "MicrovoltsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000000 + ); + yield return new (ElectricPotentialChangeRateUnit.MillivoltPerHour, "MillivoltPerHour", "MillivoltsPerHour", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Hour, current: ElectricCurrentUnit.Ampere), + 3600000 + ); + yield return new (ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, "MillivoltPerMicrosecond", "MillivoltsPerMicrosecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000) + ); + yield return new (ElectricPotentialChangeRateUnit.MillivoltPerMinute, "MillivoltPerMinute", "MillivoltsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Minute, current: ElectricCurrentUnit.Ampere), + 60000 + ); + yield return new (ElectricPotentialChangeRateUnit.MillivoltPerSecond, "MillivoltPerSecond", "MillivoltsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000 + ); + yield return new (ElectricPotentialChangeRateUnit.VoltPerHour, "VoltPerHour", "VoltsPerHour", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Hour, current: ElectricCurrentUnit.Ampere), + 3600 + ); + yield return new (ElectricPotentialChangeRateUnit.VoltPerMicrosecond, "VoltPerMicrosecond", "VoltsPerMicrosecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Microsecond, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000) + ); + yield return new (ElectricPotentialChangeRateUnit.VoltPerMinute, "VoltPerMinute", "VoltsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute, current: ElectricCurrentUnit.Ampere), + 60 + ); yield return new (ElectricPotentialChangeRateUnit.VoltPerSecond, "VoltPerSecond", "VoltsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); } } static ElectricPotentialChangeRate() { - Info = ElectricPotentialChangeRateInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricPotentialChangeRateInfo.CreateDefault); } /// @@ -151,7 +186,7 @@ static ElectricPotentialChangeRate() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricPotentialChangeRate(double value, ElectricPotentialChangeRateUnit unit) + public ElectricPotentialChangeRate(QuantityValue value, ElectricPotentialChangeRateUnit unit) { _value = value; _unit = unit; @@ -165,7 +200,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -176,7 +211,8 @@ public ElectricPotentialChangeRate(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -205,10 +241,8 @@ public ElectricPotentialChangeRate(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricPotentialChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -247,161 +281,109 @@ public ElectricPotentialChangeRate(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilovoltsPerHour => As(ElectricPotentialChangeRateUnit.KilovoltPerHour); + public QuantityValue KilovoltsPerHour => this.As(ElectricPotentialChangeRateUnit.KilovoltPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilovoltsPerMicrosecond => As(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond); + public QuantityValue KilovoltsPerMicrosecond => this.As(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilovoltsPerMinute => As(ElectricPotentialChangeRateUnit.KilovoltPerMinute); + public QuantityValue KilovoltsPerMinute => this.As(ElectricPotentialChangeRateUnit.KilovoltPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilovoltsPerSecond => As(ElectricPotentialChangeRateUnit.KilovoltPerSecond); + public QuantityValue KilovoltsPerSecond => this.As(ElectricPotentialChangeRateUnit.KilovoltPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegavoltsPerHour => As(ElectricPotentialChangeRateUnit.MegavoltPerHour); + public QuantityValue MegavoltsPerHour => this.As(ElectricPotentialChangeRateUnit.MegavoltPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegavoltsPerMicrosecond => As(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond); + public QuantityValue MegavoltsPerMicrosecond => this.As(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegavoltsPerMinute => As(ElectricPotentialChangeRateUnit.MegavoltPerMinute); + public QuantityValue MegavoltsPerMinute => this.As(ElectricPotentialChangeRateUnit.MegavoltPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegavoltsPerSecond => As(ElectricPotentialChangeRateUnit.MegavoltPerSecond); + public QuantityValue MegavoltsPerSecond => this.As(ElectricPotentialChangeRateUnit.MegavoltPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrovoltsPerHour => As(ElectricPotentialChangeRateUnit.MicrovoltPerHour); + public QuantityValue MicrovoltsPerHour => this.As(ElectricPotentialChangeRateUnit.MicrovoltPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrovoltsPerMicrosecond => As(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond); + public QuantityValue MicrovoltsPerMicrosecond => this.As(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrovoltsPerMinute => As(ElectricPotentialChangeRateUnit.MicrovoltPerMinute); + public QuantityValue MicrovoltsPerMinute => this.As(ElectricPotentialChangeRateUnit.MicrovoltPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrovoltsPerSecond => As(ElectricPotentialChangeRateUnit.MicrovoltPerSecond); + public QuantityValue MicrovoltsPerSecond => this.As(ElectricPotentialChangeRateUnit.MicrovoltPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillivoltsPerHour => As(ElectricPotentialChangeRateUnit.MillivoltPerHour); + public QuantityValue MillivoltsPerHour => this.As(ElectricPotentialChangeRateUnit.MillivoltPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillivoltsPerMicrosecond => As(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond); + public QuantityValue MillivoltsPerMicrosecond => this.As(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillivoltsPerMinute => As(ElectricPotentialChangeRateUnit.MillivoltPerMinute); + public QuantityValue MillivoltsPerMinute => this.As(ElectricPotentialChangeRateUnit.MillivoltPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillivoltsPerSecond => As(ElectricPotentialChangeRateUnit.MillivoltPerSecond); + public QuantityValue MillivoltsPerSecond => this.As(ElectricPotentialChangeRateUnit.MillivoltPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double VoltsPerHour => As(ElectricPotentialChangeRateUnit.VoltPerHour); + public QuantityValue VoltsPerHour => this.As(ElectricPotentialChangeRateUnit.VoltPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double VoltsPerMicrosecond => As(ElectricPotentialChangeRateUnit.VoltPerMicrosecond); + public QuantityValue VoltsPerMicrosecond => this.As(ElectricPotentialChangeRateUnit.VoltPerMicrosecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double VoltsPerMinute => As(ElectricPotentialChangeRateUnit.VoltPerMinute); + public QuantityValue VoltsPerMinute => this.As(ElectricPotentialChangeRateUnit.VoltPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double VoltsPerSecond => As(ElectricPotentialChangeRateUnit.VoltPerSecond); + public QuantityValue VoltsPerSecond => this.As(ElectricPotentialChangeRateUnit.VoltPerSecond); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricPotentialChangeRateUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.KilovoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.KilovoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.KilovoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MegavoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MegavoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MegavoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MicrovoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MicrovoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MicrovoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MillivoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MillivoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.MillivoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricPotentialChangeRateUnit - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerHour, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.KilovoltPerHour)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerMinute, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.KilovoltPerMinute)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.KilovoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerHour, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MegavoltPerHour)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerMinute, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MegavoltPerMinute)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MegavoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerHour, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MicrovoltPerHour)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerMinute, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MicrovoltPerMinute)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MicrovoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerHour, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MillivoltPerHour)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerMinute, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MillivoltPerMinute)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerSecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.MillivoltPerSecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerHour, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerHour)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerMicrosecond, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerMicrosecond)); - unitConverter.SetConversionFunction(ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerMinute, quantity => quantity.ToUnit(ElectricPotentialChangeRateUnit.VoltPerMinute)); - } - /// /// Get unit abbreviation string. /// @@ -430,7 +412,7 @@ public static string GetAbbreviation(ElectricPotentialChangeRateUnit unit, IForm /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromKilovoltsPerHour(double value) + public static ElectricPotentialChangeRate FromKilovoltsPerHour(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.KilovoltPerHour); } @@ -438,7 +420,7 @@ public static ElectricPotentialChangeRate FromKilovoltsPerHour(double value) /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromKilovoltsPerMicrosecond(double value) + public static ElectricPotentialChangeRate FromKilovoltsPerMicrosecond(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond); } @@ -446,7 +428,7 @@ public static ElectricPotentialChangeRate FromKilovoltsPerMicrosecond(double val /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromKilovoltsPerMinute(double value) + public static ElectricPotentialChangeRate FromKilovoltsPerMinute(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.KilovoltPerMinute); } @@ -454,7 +436,7 @@ public static ElectricPotentialChangeRate FromKilovoltsPerMinute(double value) /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromKilovoltsPerSecond(double value) + public static ElectricPotentialChangeRate FromKilovoltsPerSecond(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.KilovoltPerSecond); } @@ -462,7 +444,7 @@ public static ElectricPotentialChangeRate FromKilovoltsPerSecond(double value) /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromMegavoltsPerHour(double value) + public static ElectricPotentialChangeRate FromMegavoltsPerHour(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MegavoltPerHour); } @@ -470,7 +452,7 @@ public static ElectricPotentialChangeRate FromMegavoltsPerHour(double value) /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromMegavoltsPerMicrosecond(double value) + public static ElectricPotentialChangeRate FromMegavoltsPerMicrosecond(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond); } @@ -478,7 +460,7 @@ public static ElectricPotentialChangeRate FromMegavoltsPerMicrosecond(double val /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromMegavoltsPerMinute(double value) + public static ElectricPotentialChangeRate FromMegavoltsPerMinute(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MegavoltPerMinute); } @@ -486,7 +468,7 @@ public static ElectricPotentialChangeRate FromMegavoltsPerMinute(double value) /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromMegavoltsPerSecond(double value) + public static ElectricPotentialChangeRate FromMegavoltsPerSecond(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MegavoltPerSecond); } @@ -494,7 +476,7 @@ public static ElectricPotentialChangeRate FromMegavoltsPerSecond(double value) /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromMicrovoltsPerHour(double value) + public static ElectricPotentialChangeRate FromMicrovoltsPerHour(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MicrovoltPerHour); } @@ -502,7 +484,7 @@ public static ElectricPotentialChangeRate FromMicrovoltsPerHour(double value) /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromMicrovoltsPerMicrosecond(double value) + public static ElectricPotentialChangeRate FromMicrovoltsPerMicrosecond(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond); } @@ -510,7 +492,7 @@ public static ElectricPotentialChangeRate FromMicrovoltsPerMicrosecond(double va /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromMicrovoltsPerMinute(double value) + public static ElectricPotentialChangeRate FromMicrovoltsPerMinute(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MicrovoltPerMinute); } @@ -518,7 +500,7 @@ public static ElectricPotentialChangeRate FromMicrovoltsPerMinute(double value) /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromMicrovoltsPerSecond(double value) + public static ElectricPotentialChangeRate FromMicrovoltsPerSecond(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MicrovoltPerSecond); } @@ -526,7 +508,7 @@ public static ElectricPotentialChangeRate FromMicrovoltsPerSecond(double value) /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromMillivoltsPerHour(double value) + public static ElectricPotentialChangeRate FromMillivoltsPerHour(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MillivoltPerHour); } @@ -534,7 +516,7 @@ public static ElectricPotentialChangeRate FromMillivoltsPerHour(double value) /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromMillivoltsPerMicrosecond(double value) + public static ElectricPotentialChangeRate FromMillivoltsPerMicrosecond(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond); } @@ -542,7 +524,7 @@ public static ElectricPotentialChangeRate FromMillivoltsPerMicrosecond(double va /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromMillivoltsPerMinute(double value) + public static ElectricPotentialChangeRate FromMillivoltsPerMinute(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MillivoltPerMinute); } @@ -550,7 +532,7 @@ public static ElectricPotentialChangeRate FromMillivoltsPerMinute(double value) /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromMillivoltsPerSecond(double value) + public static ElectricPotentialChangeRate FromMillivoltsPerSecond(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.MillivoltPerSecond); } @@ -558,7 +540,7 @@ public static ElectricPotentialChangeRate FromMillivoltsPerSecond(double value) /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromVoltsPerHour(double value) + public static ElectricPotentialChangeRate FromVoltsPerHour(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.VoltPerHour); } @@ -566,7 +548,7 @@ public static ElectricPotentialChangeRate FromVoltsPerHour(double value) /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromVoltsPerMicrosecond(double value) + public static ElectricPotentialChangeRate FromVoltsPerMicrosecond(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.VoltPerMicrosecond); } @@ -574,7 +556,7 @@ public static ElectricPotentialChangeRate FromVoltsPerMicrosecond(double value) /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromVoltsPerMinute(double value) + public static ElectricPotentialChangeRate FromVoltsPerMinute(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.VoltPerMinute); } @@ -582,7 +564,7 @@ public static ElectricPotentialChangeRate FromVoltsPerMinute(double value) /// /// Creates a from . /// - public static ElectricPotentialChangeRate FromVoltsPerSecond(double value) + public static ElectricPotentialChangeRate FromVoltsPerSecond(QuantityValue value) { return new ElectricPotentialChangeRate(value, ElectricPotentialChangeRateUnit.VoltPerSecond); } @@ -593,7 +575,7 @@ public static ElectricPotentialChangeRate FromVoltsPerSecond(double value) /// Value to convert from. /// Unit to convert from. /// ElectricPotentialChangeRate unit value. - public static ElectricPotentialChangeRate From(double value, ElectricPotentialChangeRateUnit fromUnit) + public static ElectricPotentialChangeRate From(QuantityValue value, ElectricPotentialChangeRateUnit fromUnit) { return new ElectricPotentialChangeRate(value, fromUnit); } @@ -654,10 +636,7 @@ public static ElectricPotentialChangeRate Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricPotentialChangeRate Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -685,11 +664,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricPotentia /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricPotentialChangeRate result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -710,7 +685,7 @@ public static ElectricPotentialChangeRateUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -721,7 +696,7 @@ public static ElectricPotentialChangeRateUnit ParseUnit(string str, IFormatProvi return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricPotentialChangeRateUnit unit) { return TryParseUnit(str, null, out unit); @@ -736,7 +711,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricPote /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricPotentialChangeRateUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -755,35 +730,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricPotentialChangeRate operator +(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) { - return new ElectricPotentialChangeRate(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricPotentialChangeRate(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricPotentialChangeRate operator -(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) { - return new ElectricPotentialChangeRate(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricPotentialChangeRate(left.Value - right.As(left.Unit), left.Unit); } /// 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.VoltsPerSecond / right.VoltsPerSecond; } @@ -795,97 +770,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricPotentialChangeRate other, ElectricPotentialChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricPotentialChangeRate other, ElectricPotentialChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricPotentialChangeRate left, ElectricPotentialChangeRate right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricPotentialChangeRate other, ElectricPotentialChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricPotentialChangeRate otherQuantity)) + if (obj is not ElectricPotentialChangeRate otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricPotentialChangeRate other, ElectricPotentialChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricPotentialChangeRate other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricPotentialChangeRate. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricPotentialChangeRate), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricPotentialChangeRate otherQuantity)) throw new ArgumentException("Expected type ElectricPotentialChangeRate.", nameof(obj)); + if (obj is not ElectricPotentialChangeRate otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -897,184 +857,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricPotentialChangeRate other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricPotentialChangeRateUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this ElectricPotentialChangeRate to another ElectricPotentialChangeRate with the unit representation . - /// - /// The unit to convert to. - /// A ElectricPotentialChangeRate with the specified unit. - public ElectricPotentialChangeRate ToUnit(ElectricPotentialChangeRateUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricPotentialChangeRate with the specified unit. - public ElectricPotentialChangeRate ToUnit(ElectricPotentialChangeRateUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricPotentialChangeRate), Unit, typeof(ElectricPotentialChangeRate), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricPotentialChangeRate)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricPotentialChangeRateUnit unit, [NotNullWhen(true)] out ElectricPotentialChangeRate? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricPotentialChangeRate? convertedOrNull = (Unit, unit) switch - { - // ElectricPotentialChangeRateUnit -> BaseUnit - (ElectricPotentialChangeRateUnit.KilovoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value / 3600) * 1e3d, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value * 1E6) * 1e3d, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.KilovoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value / 60) * 1e3d, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.KilovoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value) * 1e3d, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.MegavoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value / 3600) * 1e6d, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value * 1E6) * 1e6d, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.MegavoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value / 60) * 1e6d, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.MegavoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value) * 1e6d, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.MicrovoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value / 3600) * 1e-6d, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value * 1E6) * 1e-6d, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.MicrovoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value / 60) * 1e-6d, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.MicrovoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value) * 1e-6d, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.MillivoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value / 3600) * 1e-3d, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value * 1E6) * 1e-3d, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.MillivoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value / 60) * 1e-3d, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.MillivoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate((_value) * 1e-3d, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.VoltPerHour, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate(_value / 3600, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.VoltPerMicrosecond, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate(_value * 1E6, ElectricPotentialChangeRateUnit.VoltPerSecond), - (ElectricPotentialChangeRateUnit.VoltPerMinute, ElectricPotentialChangeRateUnit.VoltPerSecond) => new ElectricPotentialChangeRate(_value / 60, ElectricPotentialChangeRateUnit.VoltPerSecond), - - // BaseUnit -> ElectricPotentialChangeRateUnit - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerHour) => new ElectricPotentialChangeRate((_value * 3600) / 1e3d, ElectricPotentialChangeRateUnit.KilovoltPerHour), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond) => new ElectricPotentialChangeRate((_value / 1E6) / 1e3d, ElectricPotentialChangeRateUnit.KilovoltPerMicrosecond), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerMinute) => new ElectricPotentialChangeRate((_value * 60) / 1e3d, ElectricPotentialChangeRateUnit.KilovoltPerMinute), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.KilovoltPerSecond) => new ElectricPotentialChangeRate((_value) / 1e3d, ElectricPotentialChangeRateUnit.KilovoltPerSecond), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerHour) => new ElectricPotentialChangeRate((_value * 3600) / 1e6d, ElectricPotentialChangeRateUnit.MegavoltPerHour), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond) => new ElectricPotentialChangeRate((_value / 1E6) / 1e6d, ElectricPotentialChangeRateUnit.MegavoltPerMicrosecond), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerMinute) => new ElectricPotentialChangeRate((_value * 60) / 1e6d, ElectricPotentialChangeRateUnit.MegavoltPerMinute), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MegavoltPerSecond) => new ElectricPotentialChangeRate((_value) / 1e6d, ElectricPotentialChangeRateUnit.MegavoltPerSecond), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerHour) => new ElectricPotentialChangeRate((_value * 3600) / 1e-6d, ElectricPotentialChangeRateUnit.MicrovoltPerHour), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond) => new ElectricPotentialChangeRate((_value / 1E6) / 1e-6d, ElectricPotentialChangeRateUnit.MicrovoltPerMicrosecond), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerMinute) => new ElectricPotentialChangeRate((_value * 60) / 1e-6d, ElectricPotentialChangeRateUnit.MicrovoltPerMinute), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MicrovoltPerSecond) => new ElectricPotentialChangeRate((_value) / 1e-6d, ElectricPotentialChangeRateUnit.MicrovoltPerSecond), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerHour) => new ElectricPotentialChangeRate((_value * 3600) / 1e-3d, ElectricPotentialChangeRateUnit.MillivoltPerHour), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond) => new ElectricPotentialChangeRate((_value / 1E6) / 1e-3d, ElectricPotentialChangeRateUnit.MillivoltPerMicrosecond), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerMinute) => new ElectricPotentialChangeRate((_value * 60) / 1e-3d, ElectricPotentialChangeRateUnit.MillivoltPerMinute), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.MillivoltPerSecond) => new ElectricPotentialChangeRate((_value) / 1e-3d, ElectricPotentialChangeRateUnit.MillivoltPerSecond), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerHour) => new ElectricPotentialChangeRate(_value * 3600, ElectricPotentialChangeRateUnit.VoltPerHour), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerMicrosecond) => new ElectricPotentialChangeRate(_value / 1E6, ElectricPotentialChangeRateUnit.VoltPerMicrosecond), - (ElectricPotentialChangeRateUnit.VoltPerSecond, ElectricPotentialChangeRateUnit.VoltPerMinute) => new ElectricPotentialChangeRate(_value * 60, ElectricPotentialChangeRateUnit.VoltPerMinute), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricPotentialChangeRate ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricPotentialChangeRateUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricPotentialChangeRateUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ElectricPotentialChangeRateUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricPotentialChangeRateUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1089,7 +889,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricReactance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricReactance.g.cs index a51174dc90..a0c1e593ca 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricReactance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricReactance.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electrical_reactance /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricReactance : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricReactanceUnit? _unit; /// @@ -104,7 +103,7 @@ public static ElectricReactanceInfo CreateDefault(Func - /// The for is [T^-3][L^2][M][I^-2]. + /// The for is T^-3L^2MI^-2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, -2, 0, 0, 0); @@ -119,22 +118,34 @@ public static ElectricReactanceInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricReactance. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricReactanceUnit.Gigaohm, "Gigaohm", "Gigaohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricReactanceUnit.Kiloohm, "Kiloohm", "Kiloohms", BaseUnits.Undefined); - yield return new (ElectricReactanceUnit.Megaohm, "Megaohm", "Megaohms", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricReactanceUnit.Microohm, "Microohm", "Microohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricReactanceUnit.Milliohm, "Milliohm", "Milliohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricReactanceUnit.Nanoohm, "Nanoohm", "Nanoohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricReactanceUnit.Gigaohm, "Gigaohm", "Gigaohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000000) + ); + yield return new (ElectricReactanceUnit.Kiloohm, "Kiloohm", "Kiloohms", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (ElectricReactanceUnit.Megaohm, "Megaohm", "Megaohms", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000) + ); + yield return new (ElectricReactanceUnit.Microohm, "Microohm", "Microohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000000 + ); + yield return new (ElectricReactanceUnit.Milliohm, "Milliohm", "Milliohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000 + ); + yield return new (ElectricReactanceUnit.Nanoohm, "Nanoohm", "Nanoohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000000000 + ); yield return new (ElectricReactanceUnit.Ohm, "Ohm", "Ohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricReactanceUnit.Teraohm, "Teraohm", "Teraohms", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricReactanceUnit.Teraohm, "Teraohm", "Teraohms", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000000000) + ); } } static ElectricReactance() { - Info = ElectricReactanceInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricReactanceInfo.CreateDefault); } /// @@ -142,7 +153,7 @@ static ElectricReactance() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricReactance(double value, ElectricReactanceUnit unit) + public ElectricReactance(QuantityValue value, ElectricReactanceUnit unit) { _value = value; _unit = unit; @@ -156,7 +167,7 @@ public ElectricReactance(double value, ElectricReactanceUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricReactance(double value, UnitSystem unitSystem) + public ElectricReactance(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -167,7 +178,8 @@ public ElectricReactance(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -196,10 +208,8 @@ public ElectricReactance(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricReactanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -238,77 +248,49 @@ public ElectricReactance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigaohms => As(ElectricReactanceUnit.Gigaohm); + public QuantityValue Gigaohms => this.As(ElectricReactanceUnit.Gigaohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kiloohms => As(ElectricReactanceUnit.Kiloohm); + public QuantityValue Kiloohms => this.As(ElectricReactanceUnit.Kiloohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megaohms => As(ElectricReactanceUnit.Megaohm); + public QuantityValue Megaohms => this.As(ElectricReactanceUnit.Megaohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microohms => As(ElectricReactanceUnit.Microohm); + public QuantityValue Microohms => this.As(ElectricReactanceUnit.Microohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Milliohms => As(ElectricReactanceUnit.Milliohm); + public QuantityValue Milliohms => this.As(ElectricReactanceUnit.Milliohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanoohms => As(ElectricReactanceUnit.Nanoohm); + public QuantityValue Nanoohms => this.As(ElectricReactanceUnit.Nanoohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Ohms => As(ElectricReactanceUnit.Ohm); + public QuantityValue Ohms => this.As(ElectricReactanceUnit.Ohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Teraohms => As(ElectricReactanceUnit.Teraohm); + public QuantityValue Teraohms => this.As(ElectricReactanceUnit.Teraohm); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricReactanceUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricReactanceUnit.Gigaohm, ElectricReactanceUnit.Ohm, quantity => quantity.ToUnit(ElectricReactanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricReactanceUnit.Kiloohm, ElectricReactanceUnit.Ohm, quantity => quantity.ToUnit(ElectricReactanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricReactanceUnit.Megaohm, ElectricReactanceUnit.Ohm, quantity => quantity.ToUnit(ElectricReactanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricReactanceUnit.Microohm, ElectricReactanceUnit.Ohm, quantity => quantity.ToUnit(ElectricReactanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricReactanceUnit.Milliohm, ElectricReactanceUnit.Ohm, quantity => quantity.ToUnit(ElectricReactanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricReactanceUnit.Nanoohm, ElectricReactanceUnit.Ohm, quantity => quantity.ToUnit(ElectricReactanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricReactanceUnit.Teraohm, ElectricReactanceUnit.Ohm, quantity => quantity.ToUnit(ElectricReactanceUnit.Ohm)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricReactanceUnit.Ohm, ElectricReactanceUnit.Ohm, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricReactanceUnit - unitConverter.SetConversionFunction(ElectricReactanceUnit.Ohm, ElectricReactanceUnit.Gigaohm, quantity => quantity.ToUnit(ElectricReactanceUnit.Gigaohm)); - unitConverter.SetConversionFunction(ElectricReactanceUnit.Ohm, ElectricReactanceUnit.Kiloohm, quantity => quantity.ToUnit(ElectricReactanceUnit.Kiloohm)); - unitConverter.SetConversionFunction(ElectricReactanceUnit.Ohm, ElectricReactanceUnit.Megaohm, quantity => quantity.ToUnit(ElectricReactanceUnit.Megaohm)); - unitConverter.SetConversionFunction(ElectricReactanceUnit.Ohm, ElectricReactanceUnit.Microohm, quantity => quantity.ToUnit(ElectricReactanceUnit.Microohm)); - unitConverter.SetConversionFunction(ElectricReactanceUnit.Ohm, ElectricReactanceUnit.Milliohm, quantity => quantity.ToUnit(ElectricReactanceUnit.Milliohm)); - unitConverter.SetConversionFunction(ElectricReactanceUnit.Ohm, ElectricReactanceUnit.Nanoohm, quantity => quantity.ToUnit(ElectricReactanceUnit.Nanoohm)); - unitConverter.SetConversionFunction(ElectricReactanceUnit.Ohm, ElectricReactanceUnit.Teraohm, quantity => quantity.ToUnit(ElectricReactanceUnit.Teraohm)); - } - /// /// Get unit abbreviation string. /// @@ -337,7 +319,7 @@ public static string GetAbbreviation(ElectricReactanceUnit unit, IFormatProvider /// /// Creates a from . /// - public static ElectricReactance FromGigaohms(double value) + public static ElectricReactance FromGigaohms(QuantityValue value) { return new ElectricReactance(value, ElectricReactanceUnit.Gigaohm); } @@ -345,7 +327,7 @@ public static ElectricReactance FromGigaohms(double value) /// /// Creates a from . /// - public static ElectricReactance FromKiloohms(double value) + public static ElectricReactance FromKiloohms(QuantityValue value) { return new ElectricReactance(value, ElectricReactanceUnit.Kiloohm); } @@ -353,7 +335,7 @@ public static ElectricReactance FromKiloohms(double value) /// /// Creates a from . /// - public static ElectricReactance FromMegaohms(double value) + public static ElectricReactance FromMegaohms(QuantityValue value) { return new ElectricReactance(value, ElectricReactanceUnit.Megaohm); } @@ -361,7 +343,7 @@ public static ElectricReactance FromMegaohms(double value) /// /// Creates a from . /// - public static ElectricReactance FromMicroohms(double value) + public static ElectricReactance FromMicroohms(QuantityValue value) { return new ElectricReactance(value, ElectricReactanceUnit.Microohm); } @@ -369,7 +351,7 @@ public static ElectricReactance FromMicroohms(double value) /// /// Creates a from . /// - public static ElectricReactance FromMilliohms(double value) + public static ElectricReactance FromMilliohms(QuantityValue value) { return new ElectricReactance(value, ElectricReactanceUnit.Milliohm); } @@ -377,7 +359,7 @@ public static ElectricReactance FromMilliohms(double value) /// /// Creates a from . /// - public static ElectricReactance FromNanoohms(double value) + public static ElectricReactance FromNanoohms(QuantityValue value) { return new ElectricReactance(value, ElectricReactanceUnit.Nanoohm); } @@ -385,7 +367,7 @@ public static ElectricReactance FromNanoohms(double value) /// /// Creates a from . /// - public static ElectricReactance FromOhms(double value) + public static ElectricReactance FromOhms(QuantityValue value) { return new ElectricReactance(value, ElectricReactanceUnit.Ohm); } @@ -393,7 +375,7 @@ public static ElectricReactance FromOhms(double value) /// /// Creates a from . /// - public static ElectricReactance FromTeraohms(double value) + public static ElectricReactance FromTeraohms(QuantityValue value) { return new ElectricReactance(value, ElectricReactanceUnit.Teraohm); } @@ -404,7 +386,7 @@ public static ElectricReactance FromTeraohms(double value) /// Value to convert from. /// Unit to convert from. /// ElectricReactance unit value. - public static ElectricReactance From(double value, ElectricReactanceUnit fromUnit) + public static ElectricReactance From(QuantityValue value, ElectricReactanceUnit fromUnit) { return new ElectricReactance(value, fromUnit); } @@ -465,10 +447,7 @@ public static ElectricReactance Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricReactance Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -496,11 +475,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricReactanc /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricReactance result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -521,7 +496,7 @@ public static ElectricReactanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -532,7 +507,7 @@ public static ElectricReactanceUnit ParseUnit(string str, IFormatProvider? provi return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricReactanceUnit unit) { return TryParseUnit(str, null, out unit); @@ -547,7 +522,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricReac /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricReactanceUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -566,35 +541,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricReactance operator +(ElectricReactance left, ElectricReactance right) { - return new ElectricReactance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricReactance(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricReactance operator -(ElectricReactance left, ElectricReactance right) { - return new ElectricReactance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricReactance(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static ElectricReactance operator *(double left, ElectricReactance right) + public static ElectricReactance operator *(QuantityValue left, ElectricReactance right) { return new ElectricReactance(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricReactance operator *(ElectricReactance left, double right) + public static ElectricReactance operator *(ElectricReactance left, QuantityValue right) { return new ElectricReactance(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricReactance operator /(ElectricReactance left, double right) + public static ElectricReactance operator /(ElectricReactance left, QuantityValue right) { return new ElectricReactance(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricReactance left, ElectricReactance right) + public static QuantityValue operator /(ElectricReactance left, ElectricReactance right) { return left.Ohms / right.Ohms; } @@ -606,97 +581,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricReactance left, ElectricReactance right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricReactance left, ElectricReactance right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricReactance left, ElectricReactance right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricReactance left, ElectricReactance right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricReactance other, ElectricReactance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricReactance left, ElectricReactance right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricReactance other, ElectricReactance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricReactance left, ElectricReactance right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricReactance other, ElectricReactance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricReactance otherQuantity)) + if (obj is not ElectricReactance otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricReactance other, ElectricReactance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricReactance other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricReactance. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricReactance), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricReactance otherQuantity)) throw new ArgumentException("Expected type ElectricReactance.", nameof(obj)); + if (obj is not ElectricReactance otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -708,160 +668,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricReactance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricReactanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this ElectricReactance to another ElectricReactance with the unit representation . - /// - /// The unit to convert to. - /// A ElectricReactance with the specified unit. - public ElectricReactance ToUnit(ElectricReactanceUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricReactance with the specified unit. - public ElectricReactance ToUnit(ElectricReactanceUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricReactance), Unit, typeof(ElectricReactance), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricReactance)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricReactanceUnit unit, [NotNullWhen(true)] out ElectricReactance? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricReactance? convertedOrNull = (Unit, unit) switch - { - // ElectricReactanceUnit -> BaseUnit - (ElectricReactanceUnit.Gigaohm, ElectricReactanceUnit.Ohm) => new ElectricReactance((_value) * 1e9d, ElectricReactanceUnit.Ohm), - (ElectricReactanceUnit.Kiloohm, ElectricReactanceUnit.Ohm) => new ElectricReactance((_value) * 1e3d, ElectricReactanceUnit.Ohm), - (ElectricReactanceUnit.Megaohm, ElectricReactanceUnit.Ohm) => new ElectricReactance((_value) * 1e6d, ElectricReactanceUnit.Ohm), - (ElectricReactanceUnit.Microohm, ElectricReactanceUnit.Ohm) => new ElectricReactance((_value) * 1e-6d, ElectricReactanceUnit.Ohm), - (ElectricReactanceUnit.Milliohm, ElectricReactanceUnit.Ohm) => new ElectricReactance((_value) * 1e-3d, ElectricReactanceUnit.Ohm), - (ElectricReactanceUnit.Nanoohm, ElectricReactanceUnit.Ohm) => new ElectricReactance((_value) * 1e-9d, ElectricReactanceUnit.Ohm), - (ElectricReactanceUnit.Teraohm, ElectricReactanceUnit.Ohm) => new ElectricReactance((_value) * 1e12d, ElectricReactanceUnit.Ohm), - - // BaseUnit -> ElectricReactanceUnit - (ElectricReactanceUnit.Ohm, ElectricReactanceUnit.Gigaohm) => new ElectricReactance((_value) / 1e9d, ElectricReactanceUnit.Gigaohm), - (ElectricReactanceUnit.Ohm, ElectricReactanceUnit.Kiloohm) => new ElectricReactance((_value) / 1e3d, ElectricReactanceUnit.Kiloohm), - (ElectricReactanceUnit.Ohm, ElectricReactanceUnit.Megaohm) => new ElectricReactance((_value) / 1e6d, ElectricReactanceUnit.Megaohm), - (ElectricReactanceUnit.Ohm, ElectricReactanceUnit.Microohm) => new ElectricReactance((_value) / 1e-6d, ElectricReactanceUnit.Microohm), - (ElectricReactanceUnit.Ohm, ElectricReactanceUnit.Milliohm) => new ElectricReactance((_value) / 1e-3d, ElectricReactanceUnit.Milliohm), - (ElectricReactanceUnit.Ohm, ElectricReactanceUnit.Nanoohm) => new ElectricReactance((_value) / 1e-9d, ElectricReactanceUnit.Nanoohm), - (ElectricReactanceUnit.Ohm, ElectricReactanceUnit.Teraohm) => new ElectricReactance((_value) / 1e12d, ElectricReactanceUnit.Teraohm), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricReactance ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricReactanceUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricReactanceUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ElectricReactanceUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricReactanceUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ElectricReactanceUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricReactanceUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -876,7 +700,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricReactiveEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricReactiveEnergy.g.cs index 0cd9922292..6e73dea0f7 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricReactiveEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricReactiveEnergy.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// The volt-ampere reactive hour (expressed as varh) is the reactive power of one Volt-ampere reactive produced in one hour. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricReactiveEnergy : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricReactiveEnergyUnit? _unit; /// @@ -101,7 +100,7 @@ public static ElectricReactiveEnergyInfo CreateDefault(Func - /// The for is [T^-2][L^2][M]. + /// The for is T^-2L^2M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); @@ -116,17 +115,19 @@ public static ElectricReactiveEnergyInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricReactiveEnergy. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricReactiveEnergyUnit.KilovoltampereReactiveHour, "KilovoltampereReactiveHour", "KilovoltampereReactiveHours", BaseUnits.Undefined); - yield return new (ElectricReactiveEnergyUnit.MegavoltampereReactiveHour, "MegavoltampereReactiveHour", "MegavoltampereReactiveHours", BaseUnits.Undefined); + yield return new (ElectricReactiveEnergyUnit.KilovoltampereReactiveHour, "KilovoltampereReactiveHour", "KilovoltampereReactiveHours", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (ElectricReactiveEnergyUnit.MegavoltampereReactiveHour, "MegavoltampereReactiveHour", "MegavoltampereReactiveHours", BaseUnits.Undefined, + new QuantityValue(1, 1000000) + ); yield return new (ElectricReactiveEnergyUnit.VoltampereReactiveHour, "VoltampereReactiveHour", "VoltampereReactiveHours", BaseUnits.Undefined); } } static ElectricReactiveEnergy() { - Info = ElectricReactiveEnergyInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricReactiveEnergyInfo.CreateDefault); } /// @@ -134,7 +135,7 @@ static ElectricReactiveEnergy() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricReactiveEnergy(double value, ElectricReactiveEnergyUnit unit) + public ElectricReactiveEnergy(QuantityValue value, ElectricReactiveEnergyUnit unit) { _value = value; _unit = unit; @@ -148,7 +149,7 @@ public ElectricReactiveEnergy(double value, ElectricReactiveEnergyUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricReactiveEnergy(double value, UnitSystem unitSystem) + public ElectricReactiveEnergy(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -159,7 +160,8 @@ public ElectricReactiveEnergy(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -188,10 +190,8 @@ public ElectricReactiveEnergy(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricReactiveEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -230,42 +230,24 @@ public ElectricReactiveEnergy(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilovoltampereReactiveHours => As(ElectricReactiveEnergyUnit.KilovoltampereReactiveHour); + public QuantityValue KilovoltampereReactiveHours => this.As(ElectricReactiveEnergyUnit.KilovoltampereReactiveHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegavoltampereReactiveHours => As(ElectricReactiveEnergyUnit.MegavoltampereReactiveHour); + public QuantityValue MegavoltampereReactiveHours => this.As(ElectricReactiveEnergyUnit.MegavoltampereReactiveHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double VoltampereReactiveHours => As(ElectricReactiveEnergyUnit.VoltampereReactiveHour); + public QuantityValue VoltampereReactiveHours => this.As(ElectricReactiveEnergyUnit.VoltampereReactiveHour); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricReactiveEnergyUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricReactiveEnergyUnit.KilovoltampereReactiveHour, ElectricReactiveEnergyUnit.VoltampereReactiveHour, quantity => quantity.ToUnit(ElectricReactiveEnergyUnit.VoltampereReactiveHour)); - unitConverter.SetConversionFunction(ElectricReactiveEnergyUnit.MegavoltampereReactiveHour, ElectricReactiveEnergyUnit.VoltampereReactiveHour, quantity => quantity.ToUnit(ElectricReactiveEnergyUnit.VoltampereReactiveHour)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricReactiveEnergyUnit.VoltampereReactiveHour, ElectricReactiveEnergyUnit.VoltampereReactiveHour, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricReactiveEnergyUnit - unitConverter.SetConversionFunction(ElectricReactiveEnergyUnit.VoltampereReactiveHour, ElectricReactiveEnergyUnit.KilovoltampereReactiveHour, quantity => quantity.ToUnit(ElectricReactiveEnergyUnit.KilovoltampereReactiveHour)); - unitConverter.SetConversionFunction(ElectricReactiveEnergyUnit.VoltampereReactiveHour, ElectricReactiveEnergyUnit.MegavoltampereReactiveHour, quantity => quantity.ToUnit(ElectricReactiveEnergyUnit.MegavoltampereReactiveHour)); - } - /// /// Get unit abbreviation string. /// @@ -294,7 +276,7 @@ public static string GetAbbreviation(ElectricReactiveEnergyUnit unit, IFormatPro /// /// Creates a from . /// - public static ElectricReactiveEnergy FromKilovoltampereReactiveHours(double value) + public static ElectricReactiveEnergy FromKilovoltampereReactiveHours(QuantityValue value) { return new ElectricReactiveEnergy(value, ElectricReactiveEnergyUnit.KilovoltampereReactiveHour); } @@ -302,7 +284,7 @@ public static ElectricReactiveEnergy FromKilovoltampereReactiveHours(double valu /// /// Creates a from . /// - public static ElectricReactiveEnergy FromMegavoltampereReactiveHours(double value) + public static ElectricReactiveEnergy FromMegavoltampereReactiveHours(QuantityValue value) { return new ElectricReactiveEnergy(value, ElectricReactiveEnergyUnit.MegavoltampereReactiveHour); } @@ -310,7 +292,7 @@ public static ElectricReactiveEnergy FromMegavoltampereReactiveHours(double valu /// /// Creates a from . /// - public static ElectricReactiveEnergy FromVoltampereReactiveHours(double value) + public static ElectricReactiveEnergy FromVoltampereReactiveHours(QuantityValue value) { return new ElectricReactiveEnergy(value, ElectricReactiveEnergyUnit.VoltampereReactiveHour); } @@ -321,7 +303,7 @@ public static ElectricReactiveEnergy FromVoltampereReactiveHours(double value) /// Value to convert from. /// Unit to convert from. /// ElectricReactiveEnergy unit value. - public static ElectricReactiveEnergy From(double value, ElectricReactiveEnergyUnit fromUnit) + public static ElectricReactiveEnergy From(QuantityValue value, ElectricReactiveEnergyUnit fromUnit) { return new ElectricReactiveEnergy(value, fromUnit); } @@ -382,10 +364,7 @@ public static ElectricReactiveEnergy Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricReactiveEnergy Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -413,11 +392,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricReactive /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricReactiveEnergy result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -438,7 +413,7 @@ public static ElectricReactiveEnergyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -449,7 +424,7 @@ public static ElectricReactiveEnergyUnit ParseUnit(string str, IFormatProvider? return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricReactiveEnergyUnit unit) { return TryParseUnit(str, null, out unit); @@ -464,7 +439,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricReac /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricReactiveEnergyUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -483,35 +458,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricReactiveEnergy operator +(ElectricReactiveEnergy left, ElectricReactiveEnergy right) { - return new ElectricReactiveEnergy(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricReactiveEnergy(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricReactiveEnergy operator -(ElectricReactiveEnergy left, ElectricReactiveEnergy right) { - return new ElectricReactiveEnergy(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricReactiveEnergy(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static ElectricReactiveEnergy operator *(double left, ElectricReactiveEnergy right) + public static ElectricReactiveEnergy operator *(QuantityValue left, ElectricReactiveEnergy right) { return new ElectricReactiveEnergy(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricReactiveEnergy operator *(ElectricReactiveEnergy left, double right) + public static ElectricReactiveEnergy operator *(ElectricReactiveEnergy left, QuantityValue right) { return new ElectricReactiveEnergy(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricReactiveEnergy operator /(ElectricReactiveEnergy left, double right) + public static ElectricReactiveEnergy operator /(ElectricReactiveEnergy left, QuantityValue right) { return new ElectricReactiveEnergy(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricReactiveEnergy left, ElectricReactiveEnergy right) + public static QuantityValue operator /(ElectricReactiveEnergy left, ElectricReactiveEnergy right) { return left.VoltampereReactiveHours / right.VoltampereReactiveHours; } @@ -523,97 +498,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricReactiveEnergy left, ElectricReactiveEnergy right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricReactiveEnergy left, ElectricReactiveEnergy right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricReactiveEnergy left, ElectricReactiveEnergy right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricReactiveEnergy left, ElectricReactiveEnergy right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricReactiveEnergy other, ElectricReactiveEnergy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricReactiveEnergy left, ElectricReactiveEnergy right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricReactiveEnergy other, ElectricReactiveEnergy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricReactiveEnergy left, ElectricReactiveEnergy right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricReactiveEnergy other, ElectricReactiveEnergy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricReactiveEnergy otherQuantity)) + if (obj is not ElectricReactiveEnergy otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricReactiveEnergy other, ElectricReactiveEnergy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricReactiveEnergy other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricReactiveEnergy. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricReactiveEnergy), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricReactiveEnergy otherQuantity)) throw new ArgumentException("Expected type ElectricReactiveEnergy.", nameof(obj)); + if (obj is not ElectricReactiveEnergy otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -625,150 +585,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricReactiveEnergy other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricReactiveEnergyUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this ElectricReactiveEnergy to another ElectricReactiveEnergy with the unit representation . - /// - /// The unit to convert to. - /// A ElectricReactiveEnergy with the specified unit. - public ElectricReactiveEnergy ToUnit(ElectricReactiveEnergyUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricReactiveEnergy with the specified unit. - public ElectricReactiveEnergy ToUnit(ElectricReactiveEnergyUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricReactiveEnergy), Unit, typeof(ElectricReactiveEnergy), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricReactiveEnergy)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricReactiveEnergyUnit unit, [NotNullWhen(true)] out ElectricReactiveEnergy? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricReactiveEnergy? convertedOrNull = (Unit, unit) switch - { - // ElectricReactiveEnergyUnit -> BaseUnit - (ElectricReactiveEnergyUnit.KilovoltampereReactiveHour, ElectricReactiveEnergyUnit.VoltampereReactiveHour) => new ElectricReactiveEnergy((_value) * 1e3d, ElectricReactiveEnergyUnit.VoltampereReactiveHour), - (ElectricReactiveEnergyUnit.MegavoltampereReactiveHour, ElectricReactiveEnergyUnit.VoltampereReactiveHour) => new ElectricReactiveEnergy((_value) * 1e6d, ElectricReactiveEnergyUnit.VoltampereReactiveHour), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> ElectricReactiveEnergyUnit - (ElectricReactiveEnergyUnit.VoltampereReactiveHour, ElectricReactiveEnergyUnit.KilovoltampereReactiveHour) => new ElectricReactiveEnergy((_value) / 1e3d, ElectricReactiveEnergyUnit.KilovoltampereReactiveHour), - (ElectricReactiveEnergyUnit.VoltampereReactiveHour, ElectricReactiveEnergyUnit.MegavoltampereReactiveHour) => new ElectricReactiveEnergy((_value) / 1e6d, ElectricReactiveEnergyUnit.MegavoltampereReactiveHour), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricReactiveEnergy ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricReactiveEnergyUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricReactiveEnergyUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ElectricReactiveEnergyUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricReactiveEnergyUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricReactiveEnergyUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(ElectricReactiveEnergyUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -783,7 +617,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricReactivePower.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricReactivePower.g.cs index 79a161038a..a247d6f20d 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricReactivePower.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricReactivePower.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/AC_power#Active,_reactive,_apparent,_and_complex_power_in_sinusoidal_steady-state /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricReactivePower : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricReactivePowerUnit? _unit; /// @@ -104,7 +103,7 @@ public static ElectricReactivePowerInfo CreateDefault(Func - /// The for is [T^-3][L^2][M]. + /// The for is T^-3L^2M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); @@ -119,18 +118,22 @@ public static ElectricReactivePowerInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricReactivePower. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricReactivePowerUnit.GigavoltampereReactive, "GigavoltampereReactive", "GigavoltamperesReactive", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond)); - yield return new (ElectricReactivePowerUnit.KilovoltampereReactive, "KilovoltampereReactive", "KilovoltamperesReactive", BaseUnits.Undefined); - yield return new (ElectricReactivePowerUnit.MegavoltampereReactive, "MegavoltampereReactive", "MegavoltamperesReactive", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); + yield return new (ElectricReactivePowerUnit.GigavoltampereReactive, "GigavoltampereReactive", "GigavoltamperesReactive", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond), + new QuantityValue(1, 1000000000) + ); + yield return new (ElectricReactivePowerUnit.KilovoltampereReactive, "KilovoltampereReactive", "KilovoltamperesReactive", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (ElectricReactivePowerUnit.MegavoltampereReactive, "MegavoltampereReactive", "MegavoltamperesReactive", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); yield return new (ElectricReactivePowerUnit.VoltampereReactive, "VoltampereReactive", "VoltamperesReactive", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); } } static ElectricReactivePower() { - Info = ElectricReactivePowerInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricReactivePowerInfo.CreateDefault); } /// @@ -138,7 +141,7 @@ static ElectricReactivePower() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricReactivePower(double value, ElectricReactivePowerUnit unit) + public ElectricReactivePower(QuantityValue value, ElectricReactivePowerUnit unit) { _value = value; _unit = unit; @@ -152,7 +155,7 @@ public ElectricReactivePower(double value, ElectricReactivePowerUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricReactivePower(double value, UnitSystem unitSystem) + public ElectricReactivePower(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -163,7 +166,8 @@ public ElectricReactivePower(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -192,10 +196,8 @@ public ElectricReactivePower(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricReactivePowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -234,49 +236,29 @@ public ElectricReactivePower(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigavoltamperesReactive => As(ElectricReactivePowerUnit.GigavoltampereReactive); + public QuantityValue GigavoltamperesReactive => this.As(ElectricReactivePowerUnit.GigavoltampereReactive); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilovoltamperesReactive => As(ElectricReactivePowerUnit.KilovoltampereReactive); + public QuantityValue KilovoltamperesReactive => this.As(ElectricReactivePowerUnit.KilovoltampereReactive); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegavoltamperesReactive => As(ElectricReactivePowerUnit.MegavoltampereReactive); + public QuantityValue MegavoltamperesReactive => this.As(ElectricReactivePowerUnit.MegavoltampereReactive); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double VoltamperesReactive => As(ElectricReactivePowerUnit.VoltampereReactive); + public QuantityValue VoltamperesReactive => this.As(ElectricReactivePowerUnit.VoltampereReactive); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricReactivePowerUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricReactivePowerUnit.GigavoltampereReactive, ElectricReactivePowerUnit.VoltampereReactive, quantity => quantity.ToUnit(ElectricReactivePowerUnit.VoltampereReactive)); - unitConverter.SetConversionFunction(ElectricReactivePowerUnit.KilovoltampereReactive, ElectricReactivePowerUnit.VoltampereReactive, quantity => quantity.ToUnit(ElectricReactivePowerUnit.VoltampereReactive)); - unitConverter.SetConversionFunction(ElectricReactivePowerUnit.MegavoltampereReactive, ElectricReactivePowerUnit.VoltampereReactive, quantity => quantity.ToUnit(ElectricReactivePowerUnit.VoltampereReactive)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricReactivePowerUnit.VoltampereReactive, ElectricReactivePowerUnit.VoltampereReactive, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricReactivePowerUnit - unitConverter.SetConversionFunction(ElectricReactivePowerUnit.VoltampereReactive, ElectricReactivePowerUnit.GigavoltampereReactive, quantity => quantity.ToUnit(ElectricReactivePowerUnit.GigavoltampereReactive)); - unitConverter.SetConversionFunction(ElectricReactivePowerUnit.VoltampereReactive, ElectricReactivePowerUnit.KilovoltampereReactive, quantity => quantity.ToUnit(ElectricReactivePowerUnit.KilovoltampereReactive)); - unitConverter.SetConversionFunction(ElectricReactivePowerUnit.VoltampereReactive, ElectricReactivePowerUnit.MegavoltampereReactive, quantity => quantity.ToUnit(ElectricReactivePowerUnit.MegavoltampereReactive)); - } - /// /// Get unit abbreviation string. /// @@ -305,7 +287,7 @@ public static string GetAbbreviation(ElectricReactivePowerUnit unit, IFormatProv /// /// Creates a from . /// - public static ElectricReactivePower FromGigavoltamperesReactive(double value) + public static ElectricReactivePower FromGigavoltamperesReactive(QuantityValue value) { return new ElectricReactivePower(value, ElectricReactivePowerUnit.GigavoltampereReactive); } @@ -313,7 +295,7 @@ public static ElectricReactivePower FromGigavoltamperesReactive(double value) /// /// Creates a from . /// - public static ElectricReactivePower FromKilovoltamperesReactive(double value) + public static ElectricReactivePower FromKilovoltamperesReactive(QuantityValue value) { return new ElectricReactivePower(value, ElectricReactivePowerUnit.KilovoltampereReactive); } @@ -321,7 +303,7 @@ public static ElectricReactivePower FromKilovoltamperesReactive(double value) /// /// Creates a from . /// - public static ElectricReactivePower FromMegavoltamperesReactive(double value) + public static ElectricReactivePower FromMegavoltamperesReactive(QuantityValue value) { return new ElectricReactivePower(value, ElectricReactivePowerUnit.MegavoltampereReactive); } @@ -329,7 +311,7 @@ public static ElectricReactivePower FromMegavoltamperesReactive(double value) /// /// Creates a from . /// - public static ElectricReactivePower FromVoltamperesReactive(double value) + public static ElectricReactivePower FromVoltamperesReactive(QuantityValue value) { return new ElectricReactivePower(value, ElectricReactivePowerUnit.VoltampereReactive); } @@ -340,7 +322,7 @@ public static ElectricReactivePower FromVoltamperesReactive(double value) /// Value to convert from. /// Unit to convert from. /// ElectricReactivePower unit value. - public static ElectricReactivePower From(double value, ElectricReactivePowerUnit fromUnit) + public static ElectricReactivePower From(QuantityValue value, ElectricReactivePowerUnit fromUnit) { return new ElectricReactivePower(value, fromUnit); } @@ -401,10 +383,7 @@ public static ElectricReactivePower Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricReactivePower Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -432,11 +411,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricReactive /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricReactivePower result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -457,7 +432,7 @@ public static ElectricReactivePowerUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -468,7 +443,7 @@ public static ElectricReactivePowerUnit ParseUnit(string str, IFormatProvider? p return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricReactivePowerUnit unit) { return TryParseUnit(str, null, out unit); @@ -483,7 +458,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricReac /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricReactivePowerUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -502,35 +477,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricReactivePower operator +(ElectricReactivePower left, ElectricReactivePower right) { - return new ElectricReactivePower(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricReactivePower(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricReactivePower operator -(ElectricReactivePower left, ElectricReactivePower right) { - return new ElectricReactivePower(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricReactivePower(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static ElectricReactivePower operator *(double left, ElectricReactivePower right) + public static ElectricReactivePower operator *(QuantityValue left, ElectricReactivePower right) { return new ElectricReactivePower(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricReactivePower operator *(ElectricReactivePower left, double right) + public static ElectricReactivePower operator *(ElectricReactivePower left, QuantityValue right) { return new ElectricReactivePower(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricReactivePower operator /(ElectricReactivePower left, double right) + public static ElectricReactivePower operator /(ElectricReactivePower left, QuantityValue right) { return new ElectricReactivePower(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricReactivePower left, ElectricReactivePower right) + public static QuantityValue operator /(ElectricReactivePower left, ElectricReactivePower right) { return left.VoltamperesReactive / right.VoltamperesReactive; } @@ -542,97 +517,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricReactivePower left, ElectricReactivePower right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricReactivePower left, ElectricReactivePower right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricReactivePower left, ElectricReactivePower right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricReactivePower left, ElectricReactivePower right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricReactivePower other, ElectricReactivePower tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricReactivePower left, ElectricReactivePower right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricReactivePower other, ElectricReactivePower tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricReactivePower left, ElectricReactivePower right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricReactivePower other, ElectricReactivePower tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricReactivePower otherQuantity)) + if (obj is not ElectricReactivePower otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricReactivePower other, ElectricReactivePower tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricReactivePower other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricReactivePower. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricReactivePower), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricReactivePower otherQuantity)) throw new ArgumentException("Expected type ElectricReactivePower.", nameof(obj)); + if (obj is not ElectricReactivePower otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -644,152 +604,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricReactivePower other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricReactivePowerUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this ElectricReactivePower to another ElectricReactivePower with the unit representation . - /// - /// The unit to convert to. - /// A ElectricReactivePower with the specified unit. - public ElectricReactivePower ToUnit(ElectricReactivePowerUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricReactivePower with the specified unit. - public ElectricReactivePower ToUnit(ElectricReactivePowerUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricReactivePower), Unit, typeof(ElectricReactivePower), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricReactivePower)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricReactivePowerUnit unit, [NotNullWhen(true)] out ElectricReactivePower? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricReactivePower? convertedOrNull = (Unit, unit) switch - { - // ElectricReactivePowerUnit -> BaseUnit - (ElectricReactivePowerUnit.GigavoltampereReactive, ElectricReactivePowerUnit.VoltampereReactive) => new ElectricReactivePower((_value) * 1e9d, ElectricReactivePowerUnit.VoltampereReactive), - (ElectricReactivePowerUnit.KilovoltampereReactive, ElectricReactivePowerUnit.VoltampereReactive) => new ElectricReactivePower((_value) * 1e3d, ElectricReactivePowerUnit.VoltampereReactive), - (ElectricReactivePowerUnit.MegavoltampereReactive, ElectricReactivePowerUnit.VoltampereReactive) => new ElectricReactivePower((_value) * 1e6d, ElectricReactivePowerUnit.VoltampereReactive), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> ElectricReactivePowerUnit - (ElectricReactivePowerUnit.VoltampereReactive, ElectricReactivePowerUnit.GigavoltampereReactive) => new ElectricReactivePower((_value) / 1e9d, ElectricReactivePowerUnit.GigavoltampereReactive), - (ElectricReactivePowerUnit.VoltampereReactive, ElectricReactivePowerUnit.KilovoltampereReactive) => new ElectricReactivePower((_value) / 1e3d, ElectricReactivePowerUnit.KilovoltampereReactive), - (ElectricReactivePowerUnit.VoltampereReactive, ElectricReactivePowerUnit.MegavoltampereReactive) => new ElectricReactivePower((_value) / 1e6d, ElectricReactivePowerUnit.MegavoltampereReactive), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricReactivePower ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricReactivePowerUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricReactivePowerUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ElectricReactivePowerUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricReactivePowerUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricReactivePowerUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(ElectricReactivePowerUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -804,7 +636,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs index 63394c6b68..1f000959c0 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistance.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electrical_resistance_and_conductance /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricResistance : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -56,13 +55,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricResistanceUnit? _unit; /// @@ -107,7 +106,7 @@ public static ElectricResistanceInfo CreateDefault(Func - /// The for is [T^-3][L^2][M][I^-2]. + /// The for is T^-3L^2MI^-2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, -2, 0, 0, 0); @@ -122,22 +121,34 @@ public static ElectricResistanceInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricResistance. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricResistanceUnit.Gigaohm, "Gigaohm", "Gigaohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricResistanceUnit.Kiloohm, "Kiloohm", "Kiloohms", BaseUnits.Undefined); - yield return new (ElectricResistanceUnit.Megaohm, "Megaohm", "Megaohms", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricResistanceUnit.Microohm, "Microohm", "Microohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricResistanceUnit.Milliohm, "Milliohm", "Milliohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricResistanceUnit.Nanoohm, "Nanoohm", "Nanoohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricResistanceUnit.Gigaohm, "Gigaohm", "Gigaohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000000) + ); + yield return new (ElectricResistanceUnit.Kiloohm, "Kiloohm", "Kiloohms", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (ElectricResistanceUnit.Megaohm, "Megaohm", "Megaohms", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000) + ); + yield return new (ElectricResistanceUnit.Microohm, "Microohm", "Microohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000000 + ); + yield return new (ElectricResistanceUnit.Milliohm, "Milliohm", "Milliohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000 + ); + yield return new (ElectricResistanceUnit.Nanoohm, "Nanoohm", "Nanoohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000000000 + ); yield return new (ElectricResistanceUnit.Ohm, "Ohm", "Ohms", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricResistanceUnit.Teraohm, "Teraohm", "Teraohms", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricResistanceUnit.Teraohm, "Teraohm", "Teraohms", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000000000) + ); } } static ElectricResistance() { - Info = ElectricResistanceInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricResistanceInfo.CreateDefault); } /// @@ -145,7 +156,7 @@ static ElectricResistance() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricResistance(double value, ElectricResistanceUnit unit) + public ElectricResistance(QuantityValue value, ElectricResistanceUnit unit) { _value = value; _unit = unit; @@ -159,7 +170,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -170,7 +181,8 @@ public ElectricResistance(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -199,10 +211,8 @@ public ElectricResistance(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -241,77 +251,49 @@ public ElectricResistance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigaohms => As(ElectricResistanceUnit.Gigaohm); + public QuantityValue Gigaohms => this.As(ElectricResistanceUnit.Gigaohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kiloohms => As(ElectricResistanceUnit.Kiloohm); + public QuantityValue Kiloohms => this.As(ElectricResistanceUnit.Kiloohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megaohms => As(ElectricResistanceUnit.Megaohm); + public QuantityValue Megaohms => this.As(ElectricResistanceUnit.Megaohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microohms => As(ElectricResistanceUnit.Microohm); + public QuantityValue Microohms => this.As(ElectricResistanceUnit.Microohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Milliohms => As(ElectricResistanceUnit.Milliohm); + public QuantityValue Milliohms => this.As(ElectricResistanceUnit.Milliohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanoohms => As(ElectricResistanceUnit.Nanoohm); + public QuantityValue Nanoohms => this.As(ElectricResistanceUnit.Nanoohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Ohms => As(ElectricResistanceUnit.Ohm); + public QuantityValue Ohms => this.As(ElectricResistanceUnit.Ohm); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Teraohms => As(ElectricResistanceUnit.Teraohm); + public QuantityValue Teraohms => this.As(ElectricResistanceUnit.Teraohm); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricResistanceUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricResistanceUnit.Gigaohm, ElectricResistanceUnit.Ohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Kiloohm, ElectricResistanceUnit.Ohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Megaohm, ElectricResistanceUnit.Ohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Microohm, ElectricResistanceUnit.Ohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Milliohm, ElectricResistanceUnit.Ohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Nanoohm, ElectricResistanceUnit.Ohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Ohm)); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Teraohm, ElectricResistanceUnit.Ohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Ohm)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Ohm, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricResistanceUnit - unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Gigaohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Gigaohm)); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Kiloohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Kiloohm)); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Megaohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Megaohm)); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Microohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Microohm)); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Milliohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Milliohm)); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Nanoohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Nanoohm)); - unitConverter.SetConversionFunction(ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Teraohm, quantity => quantity.ToUnit(ElectricResistanceUnit.Teraohm)); - } - /// /// Get unit abbreviation string. /// @@ -340,7 +322,7 @@ public static string GetAbbreviation(ElectricResistanceUnit unit, IFormatProvide /// /// Creates a from . /// - public static ElectricResistance FromGigaohms(double value) + public static ElectricResistance FromGigaohms(QuantityValue value) { return new ElectricResistance(value, ElectricResistanceUnit.Gigaohm); } @@ -348,7 +330,7 @@ public static ElectricResistance FromGigaohms(double value) /// /// Creates a from . /// - public static ElectricResistance FromKiloohms(double value) + public static ElectricResistance FromKiloohms(QuantityValue value) { return new ElectricResistance(value, ElectricResistanceUnit.Kiloohm); } @@ -356,7 +338,7 @@ public static ElectricResistance FromKiloohms(double value) /// /// Creates a from . /// - public static ElectricResistance FromMegaohms(double value) + public static ElectricResistance FromMegaohms(QuantityValue value) { return new ElectricResistance(value, ElectricResistanceUnit.Megaohm); } @@ -364,7 +346,7 @@ public static ElectricResistance FromMegaohms(double value) /// /// Creates a from . /// - public static ElectricResistance FromMicroohms(double value) + public static ElectricResistance FromMicroohms(QuantityValue value) { return new ElectricResistance(value, ElectricResistanceUnit.Microohm); } @@ -372,7 +354,7 @@ public static ElectricResistance FromMicroohms(double value) /// /// Creates a from . /// - public static ElectricResistance FromMilliohms(double value) + public static ElectricResistance FromMilliohms(QuantityValue value) { return new ElectricResistance(value, ElectricResistanceUnit.Milliohm); } @@ -380,7 +362,7 @@ public static ElectricResistance FromMilliohms(double value) /// /// Creates a from . /// - public static ElectricResistance FromNanoohms(double value) + public static ElectricResistance FromNanoohms(QuantityValue value) { return new ElectricResistance(value, ElectricResistanceUnit.Nanoohm); } @@ -388,7 +370,7 @@ public static ElectricResistance FromNanoohms(double value) /// /// Creates a from . /// - public static ElectricResistance FromOhms(double value) + public static ElectricResistance FromOhms(QuantityValue value) { return new ElectricResistance(value, ElectricResistanceUnit.Ohm); } @@ -396,7 +378,7 @@ public static ElectricResistance FromOhms(double value) /// /// Creates a from . /// - public static ElectricResistance FromTeraohms(double value) + public static ElectricResistance FromTeraohms(QuantityValue value) { return new ElectricResistance(value, ElectricResistanceUnit.Teraohm); } @@ -407,7 +389,7 @@ public static ElectricResistance FromTeraohms(double value) /// Value to convert from. /// Unit to convert from. /// ElectricResistance unit value. - public static ElectricResistance From(double value, ElectricResistanceUnit fromUnit) + public static ElectricResistance From(QuantityValue value, ElectricResistanceUnit fromUnit) { return new ElectricResistance(value, fromUnit); } @@ -468,10 +450,7 @@ public static ElectricResistance Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricResistance Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -499,11 +478,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricResistan /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricResistance result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -524,7 +499,7 @@ public static ElectricResistanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -535,7 +510,7 @@ public static ElectricResistanceUnit ParseUnit(string str, IFormatProvider? prov return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricResistanceUnit unit) { return TryParseUnit(str, null, out unit); @@ -550,7 +525,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricResi /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricResistanceUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -569,35 +544,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricResistance operator +(ElectricResistance left, ElectricResistance right) { - return new ElectricResistance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricResistance(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricResistance operator -(ElectricResistance left, ElectricResistance right) { - return new ElectricResistance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricResistance(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -619,97 +594,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricResistance left, ElectricResistance right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricResistance left, ElectricResistance right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricResistance left, ElectricResistance right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricResistance left, ElectricResistance right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricResistance other, ElectricResistance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricResistance left, ElectricResistance right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricResistance other, ElectricResistance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricResistance left, ElectricResistance right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricResistance other, ElectricResistance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricResistance otherQuantity)) + if (obj is not ElectricResistance otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricResistance other, ElectricResistance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricResistance other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricResistance. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricResistance), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricResistance otherQuantity)) throw new ArgumentException("Expected type ElectricResistance.", nameof(obj)); + if (obj is not ElectricResistance otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -721,160 +681,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricResistance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricResistanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this ElectricResistance to another ElectricResistance with the unit representation . - /// - /// The unit to convert to. - /// A ElectricResistance with the specified unit. - public ElectricResistance ToUnit(ElectricResistanceUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricResistance with the specified unit. - public ElectricResistance ToUnit(ElectricResistanceUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricResistance), Unit, typeof(ElectricResistance), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricResistance)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricResistanceUnit unit, [NotNullWhen(true)] out ElectricResistance? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricResistance? convertedOrNull = (Unit, unit) switch - { - // ElectricResistanceUnit -> BaseUnit - (ElectricResistanceUnit.Gigaohm, ElectricResistanceUnit.Ohm) => new ElectricResistance((_value) * 1e9d, ElectricResistanceUnit.Ohm), - (ElectricResistanceUnit.Kiloohm, ElectricResistanceUnit.Ohm) => new ElectricResistance((_value) * 1e3d, ElectricResistanceUnit.Ohm), - (ElectricResistanceUnit.Megaohm, ElectricResistanceUnit.Ohm) => new ElectricResistance((_value) * 1e6d, ElectricResistanceUnit.Ohm), - (ElectricResistanceUnit.Microohm, ElectricResistanceUnit.Ohm) => new ElectricResistance((_value) * 1e-6d, ElectricResistanceUnit.Ohm), - (ElectricResistanceUnit.Milliohm, ElectricResistanceUnit.Ohm) => new ElectricResistance((_value) * 1e-3d, ElectricResistanceUnit.Ohm), - (ElectricResistanceUnit.Nanoohm, ElectricResistanceUnit.Ohm) => new ElectricResistance((_value) * 1e-9d, ElectricResistanceUnit.Ohm), - (ElectricResistanceUnit.Teraohm, ElectricResistanceUnit.Ohm) => new ElectricResistance((_value) * 1e12d, ElectricResistanceUnit.Ohm), - - // BaseUnit -> ElectricResistanceUnit - (ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Gigaohm) => new ElectricResistance((_value) / 1e9d, ElectricResistanceUnit.Gigaohm), - (ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Kiloohm) => new ElectricResistance((_value) / 1e3d, ElectricResistanceUnit.Kiloohm), - (ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Megaohm) => new ElectricResistance((_value) / 1e6d, ElectricResistanceUnit.Megaohm), - (ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Microohm) => new ElectricResistance((_value) / 1e-6d, ElectricResistanceUnit.Microohm), - (ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Milliohm) => new ElectricResistance((_value) / 1e-3d, ElectricResistanceUnit.Milliohm), - (ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Nanoohm) => new ElectricResistance((_value) / 1e-9d, ElectricResistanceUnit.Nanoohm), - (ElectricResistanceUnit.Ohm, ElectricResistanceUnit.Teraohm) => new ElectricResistance((_value) / 1e12d, ElectricResistanceUnit.Teraohm), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricResistance ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricResistanceUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistanceUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ElectricResistanceUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricResistanceUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -889,7 +713,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs index e36ec8fe98..50fa195f02 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricResistivity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electrical_resistivity_and_conductivity /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricResistivity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricResistivityUnit? _unit; /// @@ -104,7 +103,7 @@ public static ElectricResistivityInfo CreateDefault(Func - /// The for is [T^-3][L^3][M][I^-2]. + /// The for is T^-3L^3MI^-2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(3, 1, -3, -2, 0, 0, 0); @@ -119,28 +118,52 @@ public static ElectricResistivityInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricResistivity. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricResistivityUnit.KiloohmCentimeter, "KiloohmCentimeter", "KiloohmsCentimeter", BaseUnits.Undefined); - yield return new (ElectricResistivityUnit.KiloohmMeter, "KiloohmMeter", "KiloohmMeters", new BaseUnits(length: LengthUnit.Decameter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricResistivityUnit.MegaohmCentimeter, "MegaohmCentimeter", "MegaohmsCentimeter", BaseUnits.Undefined); - yield return new (ElectricResistivityUnit.MegaohmMeter, "MegaohmMeter", "MegaohmMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere)); - yield return new (ElectricResistivityUnit.MicroohmCentimeter, "MicroohmCentimeter", "MicroohmsCentimeter", BaseUnits.Undefined); - yield return new (ElectricResistivityUnit.MicroohmMeter, "MicroohmMeter", "MicroohmMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricResistivityUnit.MilliohmCentimeter, "MilliohmCentimeter", "MilliohmsCentimeter", BaseUnits.Undefined); - yield return new (ElectricResistivityUnit.MilliohmMeter, "MilliohmMeter", "MilliohmMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricResistivityUnit.NanoohmCentimeter, "NanoohmCentimeter", "NanoohmsCentimeter", BaseUnits.Undefined); - yield return new (ElectricResistivityUnit.NanoohmMeter, "NanoohmMeter", "NanoohmMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricResistivityUnit.OhmCentimeter, "OhmCentimeter", "OhmsCentimeter", BaseUnits.Undefined); + yield return new (ElectricResistivityUnit.KiloohmCentimeter, "KiloohmCentimeter", "KiloohmsCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 10) + ); + yield return new (ElectricResistivityUnit.KiloohmMeter, "KiloohmMeter", "KiloohmMeters", new BaseUnits(length: LengthUnit.Decameter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000) + ); + yield return new (ElectricResistivityUnit.MegaohmCentimeter, "MegaohmCentimeter", "MegaohmsCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 10000) + ); + yield return new (ElectricResistivityUnit.MegaohmMeter, "MegaohmMeter", "MegaohmMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), + new QuantityValue(1, 1000000) + ); + yield return new (ElectricResistivityUnit.MicroohmCentimeter, "MicroohmCentimeter", "MicroohmsCentimeter", BaseUnits.Undefined, + 100000000 + ); + yield return new (ElectricResistivityUnit.MicroohmMeter, "MicroohmMeter", "MicroohmMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000000 + ); + yield return new (ElectricResistivityUnit.MilliohmCentimeter, "MilliohmCentimeter", "MilliohmsCentimeter", BaseUnits.Undefined, + 100000 + ); + yield return new (ElectricResistivityUnit.MilliohmMeter, "MilliohmMeter", "MilliohmMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000 + ); + yield return new (ElectricResistivityUnit.NanoohmCentimeter, "NanoohmCentimeter", "NanoohmsCentimeter", BaseUnits.Undefined, + 100000000000 + ); + yield return new (ElectricResistivityUnit.NanoohmMeter, "NanoohmMeter", "NanoohmMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000000000 + ); + yield return new (ElectricResistivityUnit.OhmCentimeter, "OhmCentimeter", "OhmsCentimeter", BaseUnits.Undefined, + 100 + ); yield return new (ElectricResistivityUnit.OhmMeter, "OhmMeter", "OhmMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricResistivityUnit.PicoohmCentimeter, "PicoohmCentimeter", "PicoohmsCentimeter", BaseUnits.Undefined); - yield return new (ElectricResistivityUnit.PicoohmMeter, "PicoohmMeter", "PicoohmMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricResistivityUnit.PicoohmCentimeter, "PicoohmCentimeter", "PicoohmsCentimeter", BaseUnits.Undefined, + 100000000000000 + ); + yield return new (ElectricResistivityUnit.PicoohmMeter, "PicoohmMeter", "PicoohmMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + 1000000000000 + ); } } static ElectricResistivity() { - Info = ElectricResistivityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricResistivityInfo.CreateDefault); } /// @@ -148,7 +171,7 @@ static ElectricResistivity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricResistivity(double value, ElectricResistivityUnit unit) + public ElectricResistivity(QuantityValue value, ElectricResistivityUnit unit) { _value = value; _unit = unit; @@ -162,7 +185,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -173,7 +196,8 @@ public ElectricResistivity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -202,10 +226,8 @@ public ElectricResistivity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricResistivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -244,119 +266,79 @@ public ElectricResistivity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KiloohmsCentimeter => As(ElectricResistivityUnit.KiloohmCentimeter); + public QuantityValue KiloohmsCentimeter => this.As(ElectricResistivityUnit.KiloohmCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KiloohmMeters => As(ElectricResistivityUnit.KiloohmMeter); + public QuantityValue KiloohmMeters => this.As(ElectricResistivityUnit.KiloohmMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegaohmsCentimeter => As(ElectricResistivityUnit.MegaohmCentimeter); + public QuantityValue MegaohmsCentimeter => this.As(ElectricResistivityUnit.MegaohmCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegaohmMeters => As(ElectricResistivityUnit.MegaohmMeter); + public QuantityValue MegaohmMeters => this.As(ElectricResistivityUnit.MegaohmMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicroohmsCentimeter => As(ElectricResistivityUnit.MicroohmCentimeter); + public QuantityValue MicroohmsCentimeter => this.As(ElectricResistivityUnit.MicroohmCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicroohmMeters => As(ElectricResistivityUnit.MicroohmMeter); + public QuantityValue MicroohmMeters => this.As(ElectricResistivityUnit.MicroohmMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliohmsCentimeter => As(ElectricResistivityUnit.MilliohmCentimeter); + public QuantityValue MilliohmsCentimeter => this.As(ElectricResistivityUnit.MilliohmCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliohmMeters => As(ElectricResistivityUnit.MilliohmMeter); + public QuantityValue MilliohmMeters => this.As(ElectricResistivityUnit.MilliohmMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanoohmsCentimeter => As(ElectricResistivityUnit.NanoohmCentimeter); + public QuantityValue NanoohmsCentimeter => this.As(ElectricResistivityUnit.NanoohmCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanoohmMeters => As(ElectricResistivityUnit.NanoohmMeter); + public QuantityValue NanoohmMeters => this.As(ElectricResistivityUnit.NanoohmMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double OhmsCentimeter => As(ElectricResistivityUnit.OhmCentimeter); + public QuantityValue OhmsCentimeter => this.As(ElectricResistivityUnit.OhmCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double OhmMeters => As(ElectricResistivityUnit.OhmMeter); + public QuantityValue OhmMeters => this.As(ElectricResistivityUnit.OhmMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicoohmsCentimeter => As(ElectricResistivityUnit.PicoohmCentimeter); + public QuantityValue PicoohmsCentimeter => this.As(ElectricResistivityUnit.PicoohmCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicoohmMeters => As(ElectricResistivityUnit.PicoohmMeter); + public QuantityValue PicoohmMeters => this.As(ElectricResistivityUnit.PicoohmMeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricResistivityUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricResistivityUnit.KiloohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.KiloohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.MegaohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.MegaohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.MicroohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.MicroohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.MilliohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.MilliohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.NanoohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.NanoohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.PicoohmCentimeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.PicoohmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.OhmMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricResistivityUnit - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.KiloohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.KiloohmCentimeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.KiloohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.KiloohmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MegaohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MegaohmCentimeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MegaohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MegaohmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MicroohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MicroohmCentimeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MicroohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MicroohmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MilliohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MilliohmCentimeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MilliohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.MilliohmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.NanoohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.NanoohmCentimeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.NanoohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.NanoohmMeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.OhmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.OhmCentimeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.PicoohmCentimeter, quantity => quantity.ToUnit(ElectricResistivityUnit.PicoohmCentimeter)); - unitConverter.SetConversionFunction(ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.PicoohmMeter, quantity => quantity.ToUnit(ElectricResistivityUnit.PicoohmMeter)); - } - /// /// Get unit abbreviation string. /// @@ -385,7 +367,7 @@ public static string GetAbbreviation(ElectricResistivityUnit unit, IFormatProvid /// /// Creates a from . /// - public static ElectricResistivity FromKiloohmsCentimeter(double value) + public static ElectricResistivity FromKiloohmsCentimeter(QuantityValue value) { return new ElectricResistivity(value, ElectricResistivityUnit.KiloohmCentimeter); } @@ -393,7 +375,7 @@ public static ElectricResistivity FromKiloohmsCentimeter(double value) /// /// Creates a from . /// - public static ElectricResistivity FromKiloohmMeters(double value) + public static ElectricResistivity FromKiloohmMeters(QuantityValue value) { return new ElectricResistivity(value, ElectricResistivityUnit.KiloohmMeter); } @@ -401,7 +383,7 @@ public static ElectricResistivity FromKiloohmMeters(double value) /// /// Creates a from . /// - public static ElectricResistivity FromMegaohmsCentimeter(double value) + public static ElectricResistivity FromMegaohmsCentimeter(QuantityValue value) { return new ElectricResistivity(value, ElectricResistivityUnit.MegaohmCentimeter); } @@ -409,7 +391,7 @@ public static ElectricResistivity FromMegaohmsCentimeter(double value) /// /// Creates a from . /// - public static ElectricResistivity FromMegaohmMeters(double value) + public static ElectricResistivity FromMegaohmMeters(QuantityValue value) { return new ElectricResistivity(value, ElectricResistivityUnit.MegaohmMeter); } @@ -417,7 +399,7 @@ public static ElectricResistivity FromMegaohmMeters(double value) /// /// Creates a from . /// - public static ElectricResistivity FromMicroohmsCentimeter(double value) + public static ElectricResistivity FromMicroohmsCentimeter(QuantityValue value) { return new ElectricResistivity(value, ElectricResistivityUnit.MicroohmCentimeter); } @@ -425,7 +407,7 @@ public static ElectricResistivity FromMicroohmsCentimeter(double value) /// /// Creates a from . /// - public static ElectricResistivity FromMicroohmMeters(double value) + public static ElectricResistivity FromMicroohmMeters(QuantityValue value) { return new ElectricResistivity(value, ElectricResistivityUnit.MicroohmMeter); } @@ -433,7 +415,7 @@ public static ElectricResistivity FromMicroohmMeters(double value) /// /// Creates a from . /// - public static ElectricResistivity FromMilliohmsCentimeter(double value) + public static ElectricResistivity FromMilliohmsCentimeter(QuantityValue value) { return new ElectricResistivity(value, ElectricResistivityUnit.MilliohmCentimeter); } @@ -441,7 +423,7 @@ public static ElectricResistivity FromMilliohmsCentimeter(double value) /// /// Creates a from . /// - public static ElectricResistivity FromMilliohmMeters(double value) + public static ElectricResistivity FromMilliohmMeters(QuantityValue value) { return new ElectricResistivity(value, ElectricResistivityUnit.MilliohmMeter); } @@ -449,7 +431,7 @@ public static ElectricResistivity FromMilliohmMeters(double value) /// /// Creates a from . /// - public static ElectricResistivity FromNanoohmsCentimeter(double value) + public static ElectricResistivity FromNanoohmsCentimeter(QuantityValue value) { return new ElectricResistivity(value, ElectricResistivityUnit.NanoohmCentimeter); } @@ -457,7 +439,7 @@ public static ElectricResistivity FromNanoohmsCentimeter(double value) /// /// Creates a from . /// - public static ElectricResistivity FromNanoohmMeters(double value) + public static ElectricResistivity FromNanoohmMeters(QuantityValue value) { return new ElectricResistivity(value, ElectricResistivityUnit.NanoohmMeter); } @@ -465,7 +447,7 @@ public static ElectricResistivity FromNanoohmMeters(double value) /// /// Creates a from . /// - public static ElectricResistivity FromOhmsCentimeter(double value) + public static ElectricResistivity FromOhmsCentimeter(QuantityValue value) { return new ElectricResistivity(value, ElectricResistivityUnit.OhmCentimeter); } @@ -473,7 +455,7 @@ public static ElectricResistivity FromOhmsCentimeter(double value) /// /// Creates a from . /// - public static ElectricResistivity FromOhmMeters(double value) + public static ElectricResistivity FromOhmMeters(QuantityValue value) { return new ElectricResistivity(value, ElectricResistivityUnit.OhmMeter); } @@ -481,7 +463,7 @@ public static ElectricResistivity FromOhmMeters(double value) /// /// Creates a from . /// - public static ElectricResistivity FromPicoohmsCentimeter(double value) + public static ElectricResistivity FromPicoohmsCentimeter(QuantityValue value) { return new ElectricResistivity(value, ElectricResistivityUnit.PicoohmCentimeter); } @@ -489,7 +471,7 @@ public static ElectricResistivity FromPicoohmsCentimeter(double value) /// /// Creates a from . /// - public static ElectricResistivity FromPicoohmMeters(double value) + public static ElectricResistivity FromPicoohmMeters(QuantityValue value) { return new ElectricResistivity(value, ElectricResistivityUnit.PicoohmMeter); } @@ -500,7 +482,7 @@ public static ElectricResistivity FromPicoohmMeters(double value) /// Value to convert from. /// Unit to convert from. /// ElectricResistivity unit value. - public static ElectricResistivity From(double value, ElectricResistivityUnit fromUnit) + public static ElectricResistivity From(QuantityValue value, ElectricResistivityUnit fromUnit) { return new ElectricResistivity(value, fromUnit); } @@ -561,10 +543,7 @@ public static ElectricResistivity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricResistivity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -592,11 +571,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricResistiv /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricResistivity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -617,7 +592,7 @@ public static ElectricResistivityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -628,7 +603,7 @@ public static ElectricResistivityUnit ParseUnit(string str, IFormatProvider? pro return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricResistivityUnit unit) { return TryParseUnit(str, null, out unit); @@ -643,7 +618,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricResi /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricResistivityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -662,35 +637,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricResistivity operator +(ElectricResistivity left, ElectricResistivity right) { - return new ElectricResistivity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricResistivity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricResistivity operator -(ElectricResistivity left, ElectricResistivity right) { - return new ElectricResistivity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricResistivity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -703,7 +678,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// The corresponding inverse quantity, . public ElectricConductivity Inverse() { - return ElectricConductivity.FromSiemensPerMeter(1 / OhmMeters); + return UnitConverter.Default.ConvertTo(Value, Unit, ElectricConductivity.Info); } #endregion @@ -713,97 +688,82 @@ public ElectricConductivity Inverse() /// Returns true if less or equal to. public static bool operator <=(ElectricResistivity left, ElectricResistivity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricResistivity left, ElectricResistivity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricResistivity left, ElectricResistivity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricResistivity left, ElectricResistivity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricResistivity other, ElectricResistivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricResistivity left, ElectricResistivity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricResistivity other, ElectricResistivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricResistivity left, ElectricResistivity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricResistivity other, ElectricResistivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricResistivity otherQuantity)) + if (obj is not ElectricResistivity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricResistivity other, ElectricResistivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricResistivity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricResistivity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricResistivity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricResistivity otherQuantity)) throw new ArgumentException("Expected type ElectricResistivity.", nameof(obj)); + if (obj is not ElectricResistivity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -815,172 +775,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricResistivity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricResistivityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this ElectricResistivity to another ElectricResistivity with the unit representation . - /// - /// The unit to convert to. - /// A ElectricResistivity with the specified unit. - public ElectricResistivity ToUnit(ElectricResistivityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricResistivity with the specified unit. - public ElectricResistivity ToUnit(ElectricResistivityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricResistivity), Unit, typeof(ElectricResistivity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricResistivity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricResistivityUnit unit, [NotNullWhen(true)] out ElectricResistivity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricResistivity? convertedOrNull = (Unit, unit) switch - { - // ElectricResistivityUnit -> BaseUnit - (ElectricResistivityUnit.KiloohmCentimeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value / 100) * 1e3d, ElectricResistivityUnit.OhmMeter), - (ElectricResistivityUnit.KiloohmMeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value) * 1e3d, ElectricResistivityUnit.OhmMeter), - (ElectricResistivityUnit.MegaohmCentimeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value / 100) * 1e6d, ElectricResistivityUnit.OhmMeter), - (ElectricResistivityUnit.MegaohmMeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value) * 1e6d, ElectricResistivityUnit.OhmMeter), - (ElectricResistivityUnit.MicroohmCentimeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value / 100) * 1e-6d, ElectricResistivityUnit.OhmMeter), - (ElectricResistivityUnit.MicroohmMeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value) * 1e-6d, ElectricResistivityUnit.OhmMeter), - (ElectricResistivityUnit.MilliohmCentimeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value / 100) * 1e-3d, ElectricResistivityUnit.OhmMeter), - (ElectricResistivityUnit.MilliohmMeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value) * 1e-3d, ElectricResistivityUnit.OhmMeter), - (ElectricResistivityUnit.NanoohmCentimeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value / 100) * 1e-9d, ElectricResistivityUnit.OhmMeter), - (ElectricResistivityUnit.NanoohmMeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value) * 1e-9d, ElectricResistivityUnit.OhmMeter), - (ElectricResistivityUnit.OhmCentimeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity(_value / 100, ElectricResistivityUnit.OhmMeter), - (ElectricResistivityUnit.PicoohmCentimeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value / 100) * 1e-12d, ElectricResistivityUnit.OhmMeter), - (ElectricResistivityUnit.PicoohmMeter, ElectricResistivityUnit.OhmMeter) => new ElectricResistivity((_value) * 1e-12d, ElectricResistivityUnit.OhmMeter), - - // BaseUnit -> ElectricResistivityUnit - (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.KiloohmCentimeter) => new ElectricResistivity((_value * 100) / 1e3d, ElectricResistivityUnit.KiloohmCentimeter), - (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.KiloohmMeter) => new ElectricResistivity((_value) / 1e3d, ElectricResistivityUnit.KiloohmMeter), - (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MegaohmCentimeter) => new ElectricResistivity((_value * 100) / 1e6d, ElectricResistivityUnit.MegaohmCentimeter), - (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MegaohmMeter) => new ElectricResistivity((_value) / 1e6d, ElectricResistivityUnit.MegaohmMeter), - (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MicroohmCentimeter) => new ElectricResistivity((_value * 100) / 1e-6d, ElectricResistivityUnit.MicroohmCentimeter), - (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MicroohmMeter) => new ElectricResistivity((_value) / 1e-6d, ElectricResistivityUnit.MicroohmMeter), - (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MilliohmCentimeter) => new ElectricResistivity((_value * 100) / 1e-3d, ElectricResistivityUnit.MilliohmCentimeter), - (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.MilliohmMeter) => new ElectricResistivity((_value) / 1e-3d, ElectricResistivityUnit.MilliohmMeter), - (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.NanoohmCentimeter) => new ElectricResistivity((_value * 100) / 1e-9d, ElectricResistivityUnit.NanoohmCentimeter), - (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.NanoohmMeter) => new ElectricResistivity((_value) / 1e-9d, ElectricResistivityUnit.NanoohmMeter), - (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.OhmCentimeter) => new ElectricResistivity(_value * 100, ElectricResistivityUnit.OhmCentimeter), - (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.PicoohmCentimeter) => new ElectricResistivity((_value * 100) / 1e-12d, ElectricResistivityUnit.PicoohmCentimeter), - (ElectricResistivityUnit.OhmMeter, ElectricResistivityUnit.PicoohmMeter) => new ElectricResistivity((_value) / 1e-12d, ElectricResistivityUnit.PicoohmMeter), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricResistivity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricResistivityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricResistivityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ElectricResistivityUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricResistivityUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -995,7 +807,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs index ad8aedf6ff..35f7007e47 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricSurfaceChargeDensity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Charge_density /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricSurfaceChargeDensity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricSurfaceChargeDensityUnit? _unit; /// @@ -104,7 +103,7 @@ public static ElectricSurfaceChargeDensityInfo CreateDefault(Func - /// The for is [T][L^-2][I]. + /// The for is TL^-2I. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 0, 1, 1, 0, 0, 0); @@ -119,17 +118,19 @@ public static ElectricSurfaceChargeDensityInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricSurfaceChargeDensity. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, "CoulombPerSquareCentimeter", "CoulombsPerSquareCentimeter", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, "CoulombPerSquareInch", "CoulombsPerSquareInch", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, "CoulombPerSquareCentimeter", "CoulombsPerSquareCentimeter", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 10000) + ); + yield return new (ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, "CoulombPerSquareInch", "CoulombsPerSquareInch", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(16129, 25000000) + ); yield return new (ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, "CoulombPerSquareMeter", "CoulombsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); } } static ElectricSurfaceChargeDensity() { - Info = ElectricSurfaceChargeDensityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricSurfaceChargeDensityInfo.CreateDefault); } /// @@ -137,7 +138,7 @@ static ElectricSurfaceChargeDensity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricSurfaceChargeDensity(double value, ElectricSurfaceChargeDensityUnit unit) + public ElectricSurfaceChargeDensity(QuantityValue value, ElectricSurfaceChargeDensityUnit unit) { _value = value; _unit = unit; @@ -151,7 +152,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -162,7 +163,8 @@ public ElectricSurfaceChargeDensity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -191,10 +193,8 @@ public ElectricSurfaceChargeDensity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricSurfaceChargeDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -233,42 +233,24 @@ public ElectricSurfaceChargeDensity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CoulombsPerSquareCentimeter => As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter); + public QuantityValue CoulombsPerSquareCentimeter => this.As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CoulombsPerSquareInch => As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch); + public QuantityValue CoulombsPerSquareInch => this.As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CoulombsPerSquareMeter => As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter); + public QuantityValue CoulombsPerSquareMeter => this.As(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricSurfaceChargeDensityUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, quantity => quantity.ToUnit(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter)); - unitConverter.SetConversionFunction(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, quantity => quantity.ToUnit(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricSurfaceChargeDensityUnit - unitConverter.SetConversionFunction(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, quantity => quantity.ToUnit(ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter)); - unitConverter.SetConversionFunction(ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, quantity => quantity.ToUnit(ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch)); - } - /// /// Get unit abbreviation string. /// @@ -297,7 +279,7 @@ public static string GetAbbreviation(ElectricSurfaceChargeDensityUnit unit, IFor /// /// Creates a from . /// - public static ElectricSurfaceChargeDensity FromCoulombsPerSquareCentimeter(double value) + public static ElectricSurfaceChargeDensity FromCoulombsPerSquareCentimeter(QuantityValue value) { return new ElectricSurfaceChargeDensity(value, ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter); } @@ -305,7 +287,7 @@ public static ElectricSurfaceChargeDensity FromCoulombsPerSquareCentimeter(doubl /// /// Creates a from . /// - public static ElectricSurfaceChargeDensity FromCoulombsPerSquareInch(double value) + public static ElectricSurfaceChargeDensity FromCoulombsPerSquareInch(QuantityValue value) { return new ElectricSurfaceChargeDensity(value, ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch); } @@ -313,7 +295,7 @@ public static ElectricSurfaceChargeDensity FromCoulombsPerSquareInch(double valu /// /// Creates a from . /// - public static ElectricSurfaceChargeDensity FromCoulombsPerSquareMeter(double value) + public static ElectricSurfaceChargeDensity FromCoulombsPerSquareMeter(QuantityValue value) { return new ElectricSurfaceChargeDensity(value, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter); } @@ -324,7 +306,7 @@ public static ElectricSurfaceChargeDensity FromCoulombsPerSquareMeter(double val /// Value to convert from. /// Unit to convert from. /// ElectricSurfaceChargeDensity unit value. - public static ElectricSurfaceChargeDensity From(double value, ElectricSurfaceChargeDensityUnit fromUnit) + public static ElectricSurfaceChargeDensity From(QuantityValue value, ElectricSurfaceChargeDensityUnit fromUnit) { return new ElectricSurfaceChargeDensity(value, fromUnit); } @@ -385,10 +367,7 @@ public static ElectricSurfaceChargeDensity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricSurfaceChargeDensity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -416,11 +395,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricSurfaceC /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricSurfaceChargeDensity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -441,7 +416,7 @@ public static ElectricSurfaceChargeDensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -452,7 +427,7 @@ public static ElectricSurfaceChargeDensityUnit ParseUnit(string str, IFormatProv return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricSurfaceChargeDensityUnit unit) { return TryParseUnit(str, null, out unit); @@ -467,7 +442,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricSurf /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricSurfaceChargeDensityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -486,35 +461,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricSurfaceChargeDensity operator +(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) { - return new ElectricSurfaceChargeDensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricSurfaceChargeDensity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricSurfaceChargeDensity operator -(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) { - return new ElectricSurfaceChargeDensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricSurfaceChargeDensity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -526,97 +501,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricSurfaceChargeDensity other, ElectricSurfaceChargeDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricSurfaceChargeDensity other, ElectricSurfaceChargeDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricSurfaceChargeDensity left, ElectricSurfaceChargeDensity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricSurfaceChargeDensity other, ElectricSurfaceChargeDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricSurfaceChargeDensity otherQuantity)) + if (obj is not ElectricSurfaceChargeDensity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricSurfaceChargeDensity other, ElectricSurfaceChargeDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricSurfaceChargeDensity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricSurfaceChargeDensity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricSurfaceChargeDensity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricSurfaceChargeDensity otherQuantity)) throw new ArgumentException("Expected type ElectricSurfaceChargeDensity.", nameof(obj)); + if (obj is not ElectricSurfaceChargeDensity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -628,150 +588,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricSurfaceChargeDensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricSurfaceChargeDensityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this ElectricSurfaceChargeDensity to another ElectricSurfaceChargeDensity with the unit representation . - /// - /// The unit to convert to. - /// A ElectricSurfaceChargeDensity with the specified unit. - public ElectricSurfaceChargeDensity ToUnit(ElectricSurfaceChargeDensityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricSurfaceChargeDensity with the specified unit. - public ElectricSurfaceChargeDensity ToUnit(ElectricSurfaceChargeDensityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricSurfaceChargeDensity), Unit, typeof(ElectricSurfaceChargeDensity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricSurfaceChargeDensity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricSurfaceChargeDensityUnit unit, [NotNullWhen(true)] out ElectricSurfaceChargeDensity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricSurfaceChargeDensity? convertedOrNull = (Unit, unit) switch - { - // ElectricSurfaceChargeDensityUnit -> BaseUnit - (ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter) => new ElectricSurfaceChargeDensity(_value * 1.0e4, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter), - (ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter) => new ElectricSurfaceChargeDensity(_value / 0.00064516, ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> ElectricSurfaceChargeDensityUnit - (ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter) => new ElectricSurfaceChargeDensity(_value / 1.0e4, ElectricSurfaceChargeDensityUnit.CoulombPerSquareCentimeter), - (ElectricSurfaceChargeDensityUnit.CoulombPerSquareMeter, ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch) => new ElectricSurfaceChargeDensity(_value * 0.00064516, ElectricSurfaceChargeDensityUnit.CoulombPerSquareInch), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricSurfaceChargeDensity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricSurfaceChargeDensityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricSurfaceChargeDensityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ElectricSurfaceChargeDensityUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricSurfaceChargeDensityUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricSurfaceChargeDensityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(ElectricSurfaceChargeDensityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -786,7 +620,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ElectricSusceptance.g.cs b/UnitsNet/GeneratedCode/Quantities/ElectricSusceptance.g.cs index 28a289d017..9c76e6e40c 100644 --- a/UnitsNet/GeneratedCode/Quantities/ElectricSusceptance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ElectricSusceptance.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Electrical_susceptance /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ElectricSusceptance : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ElectricSusceptanceUnit? _unit; /// @@ -104,7 +103,7 @@ public static ElectricSusceptanceInfo CreateDefault(Func - /// The for is [T^3][L^-2][M^-1][I^2]. + /// The for is T^3L^-2M^-1I^2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, -1, 3, 2, 0, 0, 0); @@ -119,30 +118,58 @@ public static ElectricSusceptanceInfo CreateDefault(FuncAn of representing the default unit mappings for ElectricSusceptance. public static IEnumerable> GetDefaultMappings() { - yield return new (ElectricSusceptanceUnit.Gigamho, "Gigamho", "Gigamhos", BaseUnits.Undefined); - yield return new (ElectricSusceptanceUnit.Gigasiemens, "Gigasiemens", "Gigasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricSusceptanceUnit.Kilomho, "Kilomho", "Kilomhos", BaseUnits.Undefined); - yield return new (ElectricSusceptanceUnit.Kilosiemens, "Kilosiemens", "Kilosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricSusceptanceUnit.Megamho, "Megamho", "Megamhos", BaseUnits.Undefined); - yield return new (ElectricSusceptanceUnit.Megasiemens, "Megasiemens", "Megasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricSusceptanceUnit.Mho, "Mho", "Mhos", BaseUnits.Undefined); - yield return new (ElectricSusceptanceUnit.Micromho, "Micromho", "Micromhos", BaseUnits.Undefined); - yield return new (ElectricSusceptanceUnit.Microsiemens, "Microsiemens", "Microsiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere)); - yield return new (ElectricSusceptanceUnit.Millimho, "Millimho", "Millimhos", BaseUnits.Undefined); - yield return new (ElectricSusceptanceUnit.Millisiemens, "Millisiemens", "Millisiemens", BaseUnits.Undefined); - yield return new (ElectricSusceptanceUnit.Nanomho, "Nanomho", "Nanomhos", BaseUnits.Undefined); - yield return new (ElectricSusceptanceUnit.Nanosiemens, "Nanosiemens", "Nanosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricSusceptanceUnit.Gigamho, "Gigamho", "Gigamhos", BaseUnits.Undefined, + new QuantityValue(1, 1000000000) + ); + yield return new (ElectricSusceptanceUnit.Gigasiemens, "Gigasiemens", "Gigasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000000) + ); + yield return new (ElectricSusceptanceUnit.Kilomho, "Kilomho", "Kilomhos", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (ElectricSusceptanceUnit.Kilosiemens, "Kilosiemens", "Kilosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000) + ); + yield return new (ElectricSusceptanceUnit.Megamho, "Megamho", "Megamhos", BaseUnits.Undefined, + new QuantityValue(1, 1000000) + ); + yield return new (ElectricSusceptanceUnit.Megasiemens, "Megasiemens", "Megasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000) + ); + yield return new (ElectricSusceptanceUnit.Mho, "Mho", "Mhos", BaseUnits.Undefined, + 1 + ); + yield return new (ElectricSusceptanceUnit.Micromho, "Micromho", "Micromhos", BaseUnits.Undefined, + 1000000 + ); + yield return new (ElectricSusceptanceUnit.Microsiemens, "Microsiemens", "Microsiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), + 1000000 + ); + yield return new (ElectricSusceptanceUnit.Millimho, "Millimho", "Millimhos", BaseUnits.Undefined, + 1000 + ); + yield return new (ElectricSusceptanceUnit.Millisiemens, "Millisiemens", "Millisiemens", BaseUnits.Undefined, + 1000 + ); + yield return new (ElectricSusceptanceUnit.Nanomho, "Nanomho", "Nanomhos", BaseUnits.Undefined, + 1000000000 + ); + yield return new (ElectricSusceptanceUnit.Nanosiemens, "Nanosiemens", "Nanosiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond, current: ElectricCurrentUnit.Ampere), + 1000000000 + ); yield return new (ElectricSusceptanceUnit.Siemens, "Siemens", "Siemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (ElectricSusceptanceUnit.Teramho, "Teramho", "Teramhos", BaseUnits.Undefined); - yield return new (ElectricSusceptanceUnit.Terasiemens, "Terasiemens", "Terasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + yield return new (ElectricSusceptanceUnit.Teramho, "Teramho", "Teramhos", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000) + ); + yield return new (ElectricSusceptanceUnit.Terasiemens, "Terasiemens", "Terasiemens", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(1, 1000000000000) + ); } } static ElectricSusceptance() { - Info = ElectricSusceptanceInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ElectricSusceptanceInfo.CreateDefault); } /// @@ -150,7 +177,7 @@ static ElectricSusceptance() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ElectricSusceptance(double value, ElectricSusceptanceUnit unit) + public ElectricSusceptance(QuantityValue value, ElectricSusceptanceUnit unit) { _value = value; _unit = unit; @@ -164,7 +191,7 @@ public ElectricSusceptance(double value, ElectricSusceptanceUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ElectricSusceptance(double value, UnitSystem unitSystem) + public ElectricSusceptance(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -175,7 +202,8 @@ public ElectricSusceptance(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -204,10 +232,8 @@ public ElectricSusceptance(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ElectricSusceptanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -246,133 +272,89 @@ public ElectricSusceptance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigamhos => As(ElectricSusceptanceUnit.Gigamho); + public QuantityValue Gigamhos => this.As(ElectricSusceptanceUnit.Gigamho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigasiemens => As(ElectricSusceptanceUnit.Gigasiemens); + public QuantityValue Gigasiemens => this.As(ElectricSusceptanceUnit.Gigasiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilomhos => As(ElectricSusceptanceUnit.Kilomho); + public QuantityValue Kilomhos => this.As(ElectricSusceptanceUnit.Kilomho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilosiemens => As(ElectricSusceptanceUnit.Kilosiemens); + public QuantityValue Kilosiemens => this.As(ElectricSusceptanceUnit.Kilosiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megamhos => As(ElectricSusceptanceUnit.Megamho); + public QuantityValue Megamhos => this.As(ElectricSusceptanceUnit.Megamho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megasiemens => As(ElectricSusceptanceUnit.Megasiemens); + public QuantityValue Megasiemens => this.As(ElectricSusceptanceUnit.Megasiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Mhos => As(ElectricSusceptanceUnit.Mho); + public QuantityValue Mhos => this.As(ElectricSusceptanceUnit.Mho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Micromhos => As(ElectricSusceptanceUnit.Micromho); + public QuantityValue Micromhos => this.As(ElectricSusceptanceUnit.Micromho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microsiemens => As(ElectricSusceptanceUnit.Microsiemens); + public QuantityValue Microsiemens => this.As(ElectricSusceptanceUnit.Microsiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millimhos => As(ElectricSusceptanceUnit.Millimho); + public QuantityValue Millimhos => this.As(ElectricSusceptanceUnit.Millimho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millisiemens => As(ElectricSusceptanceUnit.Millisiemens); + public QuantityValue Millisiemens => this.As(ElectricSusceptanceUnit.Millisiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanomhos => As(ElectricSusceptanceUnit.Nanomho); + public QuantityValue Nanomhos => this.As(ElectricSusceptanceUnit.Nanomho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanosiemens => As(ElectricSusceptanceUnit.Nanosiemens); + public QuantityValue Nanosiemens => this.As(ElectricSusceptanceUnit.Nanosiemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Siemens => As(ElectricSusceptanceUnit.Siemens); + public QuantityValue Siemens => this.As(ElectricSusceptanceUnit.Siemens); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Teramhos => As(ElectricSusceptanceUnit.Teramho); + public QuantityValue Teramhos => this.As(ElectricSusceptanceUnit.Teramho); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Terasiemens => As(ElectricSusceptanceUnit.Terasiemens); + public QuantityValue Terasiemens => this.As(ElectricSusceptanceUnit.Terasiemens); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ElectricSusceptanceUnit -> BaseUnit - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Gigamho, ElectricSusceptanceUnit.Siemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Gigasiemens, ElectricSusceptanceUnit.Siemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Kilomho, ElectricSusceptanceUnit.Siemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Kilosiemens, ElectricSusceptanceUnit.Siemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Megamho, ElectricSusceptanceUnit.Siemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Megasiemens, ElectricSusceptanceUnit.Siemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Mho, ElectricSusceptanceUnit.Siemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Micromho, ElectricSusceptanceUnit.Siemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Microsiemens, ElectricSusceptanceUnit.Siemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Millimho, ElectricSusceptanceUnit.Siemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Millisiemens, ElectricSusceptanceUnit.Siemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Nanomho, ElectricSusceptanceUnit.Siemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Nanosiemens, ElectricSusceptanceUnit.Siemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Teramho, ElectricSusceptanceUnit.Siemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Siemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Terasiemens, ElectricSusceptanceUnit.Siemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Siemens)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Siemens, quantity => quantity); - - // Register in unit converter: BaseUnit -> ElectricSusceptanceUnit - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Gigamho, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Gigamho)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Gigasiemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Gigasiemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Kilomho, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Kilomho)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Kilosiemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Kilosiemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Megamho, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Megamho)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Megasiemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Megasiemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Mho, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Mho)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Micromho, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Micromho)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Microsiemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Microsiemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Millimho, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Millimho)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Millisiemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Millisiemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Nanomho, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Nanomho)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Nanosiemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Nanosiemens)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Teramho, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Teramho)); - unitConverter.SetConversionFunction(ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Terasiemens, quantity => quantity.ToUnit(ElectricSusceptanceUnit.Terasiemens)); - } - /// /// Get unit abbreviation string. /// @@ -401,7 +383,7 @@ public static string GetAbbreviation(ElectricSusceptanceUnit unit, IFormatProvid /// /// Creates a from . /// - public static ElectricSusceptance FromGigamhos(double value) + public static ElectricSusceptance FromGigamhos(QuantityValue value) { return new ElectricSusceptance(value, ElectricSusceptanceUnit.Gigamho); } @@ -409,7 +391,7 @@ public static ElectricSusceptance FromGigamhos(double value) /// /// Creates a from . /// - public static ElectricSusceptance FromGigasiemens(double value) + public static ElectricSusceptance FromGigasiemens(QuantityValue value) { return new ElectricSusceptance(value, ElectricSusceptanceUnit.Gigasiemens); } @@ -417,7 +399,7 @@ public static ElectricSusceptance FromGigasiemens(double value) /// /// Creates a from . /// - public static ElectricSusceptance FromKilomhos(double value) + public static ElectricSusceptance FromKilomhos(QuantityValue value) { return new ElectricSusceptance(value, ElectricSusceptanceUnit.Kilomho); } @@ -425,7 +407,7 @@ public static ElectricSusceptance FromKilomhos(double value) /// /// Creates a from . /// - public static ElectricSusceptance FromKilosiemens(double value) + public static ElectricSusceptance FromKilosiemens(QuantityValue value) { return new ElectricSusceptance(value, ElectricSusceptanceUnit.Kilosiemens); } @@ -433,7 +415,7 @@ public static ElectricSusceptance FromKilosiemens(double value) /// /// Creates a from . /// - public static ElectricSusceptance FromMegamhos(double value) + public static ElectricSusceptance FromMegamhos(QuantityValue value) { return new ElectricSusceptance(value, ElectricSusceptanceUnit.Megamho); } @@ -441,7 +423,7 @@ public static ElectricSusceptance FromMegamhos(double value) /// /// Creates a from . /// - public static ElectricSusceptance FromMegasiemens(double value) + public static ElectricSusceptance FromMegasiemens(QuantityValue value) { return new ElectricSusceptance(value, ElectricSusceptanceUnit.Megasiemens); } @@ -449,7 +431,7 @@ public static ElectricSusceptance FromMegasiemens(double value) /// /// Creates a from . /// - public static ElectricSusceptance FromMhos(double value) + public static ElectricSusceptance FromMhos(QuantityValue value) { return new ElectricSusceptance(value, ElectricSusceptanceUnit.Mho); } @@ -457,7 +439,7 @@ public static ElectricSusceptance FromMhos(double value) /// /// Creates a from . /// - public static ElectricSusceptance FromMicromhos(double value) + public static ElectricSusceptance FromMicromhos(QuantityValue value) { return new ElectricSusceptance(value, ElectricSusceptanceUnit.Micromho); } @@ -465,7 +447,7 @@ public static ElectricSusceptance FromMicromhos(double value) /// /// Creates a from . /// - public static ElectricSusceptance FromMicrosiemens(double value) + public static ElectricSusceptance FromMicrosiemens(QuantityValue value) { return new ElectricSusceptance(value, ElectricSusceptanceUnit.Microsiemens); } @@ -473,7 +455,7 @@ public static ElectricSusceptance FromMicrosiemens(double value) /// /// Creates a from . /// - public static ElectricSusceptance FromMillimhos(double value) + public static ElectricSusceptance FromMillimhos(QuantityValue value) { return new ElectricSusceptance(value, ElectricSusceptanceUnit.Millimho); } @@ -481,7 +463,7 @@ public static ElectricSusceptance FromMillimhos(double value) /// /// Creates a from . /// - public static ElectricSusceptance FromMillisiemens(double value) + public static ElectricSusceptance FromMillisiemens(QuantityValue value) { return new ElectricSusceptance(value, ElectricSusceptanceUnit.Millisiemens); } @@ -489,7 +471,7 @@ public static ElectricSusceptance FromMillisiemens(double value) /// /// Creates a from . /// - public static ElectricSusceptance FromNanomhos(double value) + public static ElectricSusceptance FromNanomhos(QuantityValue value) { return new ElectricSusceptance(value, ElectricSusceptanceUnit.Nanomho); } @@ -497,7 +479,7 @@ public static ElectricSusceptance FromNanomhos(double value) /// /// Creates a from . /// - public static ElectricSusceptance FromNanosiemens(double value) + public static ElectricSusceptance FromNanosiemens(QuantityValue value) { return new ElectricSusceptance(value, ElectricSusceptanceUnit.Nanosiemens); } @@ -505,7 +487,7 @@ public static ElectricSusceptance FromNanosiemens(double value) /// /// Creates a from . /// - public static ElectricSusceptance FromSiemens(double value) + public static ElectricSusceptance FromSiemens(QuantityValue value) { return new ElectricSusceptance(value, ElectricSusceptanceUnit.Siemens); } @@ -513,7 +495,7 @@ public static ElectricSusceptance FromSiemens(double value) /// /// Creates a from . /// - public static ElectricSusceptance FromTeramhos(double value) + public static ElectricSusceptance FromTeramhos(QuantityValue value) { return new ElectricSusceptance(value, ElectricSusceptanceUnit.Teramho); } @@ -521,7 +503,7 @@ public static ElectricSusceptance FromTeramhos(double value) /// /// Creates a from . /// - public static ElectricSusceptance FromTerasiemens(double value) + public static ElectricSusceptance FromTerasiemens(QuantityValue value) { return new ElectricSusceptance(value, ElectricSusceptanceUnit.Terasiemens); } @@ -532,7 +514,7 @@ public static ElectricSusceptance FromTerasiemens(double value) /// Value to convert from. /// Unit to convert from. /// ElectricSusceptance unit value. - public static ElectricSusceptance From(double value, ElectricSusceptanceUnit fromUnit) + public static ElectricSusceptance From(QuantityValue value, ElectricSusceptanceUnit fromUnit) { return new ElectricSusceptance(value, fromUnit); } @@ -593,10 +575,7 @@ public static ElectricSusceptance Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ElectricSusceptance Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -624,11 +603,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ElectricSuscepta /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricSusceptance result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -649,7 +624,7 @@ public static ElectricSusceptanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -660,7 +635,7 @@ public static ElectricSusceptanceUnit ParseUnit(string str, IFormatProvider? pro return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricSusceptanceUnit unit) { return TryParseUnit(str, null, out unit); @@ -675,7 +650,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ElectricSusc /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ElectricSusceptanceUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -694,35 +669,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ElectricSusceptance operator +(ElectricSusceptance left, ElectricSusceptance right) { - return new ElectricSusceptance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricSusceptance(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ElectricSusceptance operator -(ElectricSusceptance left, ElectricSusceptance right) { - return new ElectricSusceptance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ElectricSusceptance(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static ElectricSusceptance operator *(double left, ElectricSusceptance right) + public static ElectricSusceptance operator *(QuantityValue left, ElectricSusceptance right) { return new ElectricSusceptance(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ElectricSusceptance operator *(ElectricSusceptance left, double right) + public static ElectricSusceptance operator *(ElectricSusceptance left, QuantityValue right) { return new ElectricSusceptance(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ElectricSusceptance operator /(ElectricSusceptance left, double right) + public static ElectricSusceptance operator /(ElectricSusceptance left, QuantityValue right) { return new ElectricSusceptance(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ElectricSusceptance left, ElectricSusceptance right) + public static QuantityValue operator /(ElectricSusceptance left, ElectricSusceptance right) { return left.Siemens / right.Siemens; } @@ -734,97 +709,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ElectricSusceptance left, ElectricSusceptance right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ElectricSusceptance left, ElectricSusceptance right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ElectricSusceptance left, ElectricSusceptance right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ElectricSusceptance left, ElectricSusceptance right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricSusceptance other, ElectricSusceptance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ElectricSusceptance left, ElectricSusceptance right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ElectricSusceptance other, ElectricSusceptance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ElectricSusceptance left, ElectricSusceptance right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricSusceptance other, ElectricSusceptance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ElectricSusceptance otherQuantity)) + if (obj is not ElectricSusceptance otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ElectricSusceptance other, ElectricSusceptance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ElectricSusceptance other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ElectricSusceptance. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ElectricSusceptance), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ElectricSusceptance otherQuantity)) throw new ArgumentException("Expected type ElectricSusceptance.", nameof(obj)); + if (obj is not ElectricSusceptance otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -836,176 +796,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ElectricSusceptance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ElectricSusceptanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this ElectricSusceptance to another ElectricSusceptance with the unit representation . - /// - /// The unit to convert to. - /// A ElectricSusceptance with the specified unit. - public ElectricSusceptance ToUnit(ElectricSusceptanceUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ElectricSusceptance with the specified unit. - public ElectricSusceptance ToUnit(ElectricSusceptanceUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ElectricSusceptance), Unit, typeof(ElectricSusceptance), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ElectricSusceptance)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ElectricSusceptanceUnit unit, [NotNullWhen(true)] out ElectricSusceptance? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ElectricSusceptance? convertedOrNull = (Unit, unit) switch - { - // ElectricSusceptanceUnit -> BaseUnit - (ElectricSusceptanceUnit.Gigamho, ElectricSusceptanceUnit.Siemens) => new ElectricSusceptance((_value) * 1e9d, ElectricSusceptanceUnit.Siemens), - (ElectricSusceptanceUnit.Gigasiemens, ElectricSusceptanceUnit.Siemens) => new ElectricSusceptance((_value) * 1e9d, ElectricSusceptanceUnit.Siemens), - (ElectricSusceptanceUnit.Kilomho, ElectricSusceptanceUnit.Siemens) => new ElectricSusceptance((_value) * 1e3d, ElectricSusceptanceUnit.Siemens), - (ElectricSusceptanceUnit.Kilosiemens, ElectricSusceptanceUnit.Siemens) => new ElectricSusceptance((_value) * 1e3d, ElectricSusceptanceUnit.Siemens), - (ElectricSusceptanceUnit.Megamho, ElectricSusceptanceUnit.Siemens) => new ElectricSusceptance((_value) * 1e6d, ElectricSusceptanceUnit.Siemens), - (ElectricSusceptanceUnit.Megasiemens, ElectricSusceptanceUnit.Siemens) => new ElectricSusceptance((_value) * 1e6d, ElectricSusceptanceUnit.Siemens), - (ElectricSusceptanceUnit.Mho, ElectricSusceptanceUnit.Siemens) => new ElectricSusceptance(_value, ElectricSusceptanceUnit.Siemens), - (ElectricSusceptanceUnit.Micromho, ElectricSusceptanceUnit.Siemens) => new ElectricSusceptance((_value) * 1e-6d, ElectricSusceptanceUnit.Siemens), - (ElectricSusceptanceUnit.Microsiemens, ElectricSusceptanceUnit.Siemens) => new ElectricSusceptance((_value) * 1e-6d, ElectricSusceptanceUnit.Siemens), - (ElectricSusceptanceUnit.Millimho, ElectricSusceptanceUnit.Siemens) => new ElectricSusceptance((_value) * 1e-3d, ElectricSusceptanceUnit.Siemens), - (ElectricSusceptanceUnit.Millisiemens, ElectricSusceptanceUnit.Siemens) => new ElectricSusceptance((_value) * 1e-3d, ElectricSusceptanceUnit.Siemens), - (ElectricSusceptanceUnit.Nanomho, ElectricSusceptanceUnit.Siemens) => new ElectricSusceptance((_value) * 1e-9d, ElectricSusceptanceUnit.Siemens), - (ElectricSusceptanceUnit.Nanosiemens, ElectricSusceptanceUnit.Siemens) => new ElectricSusceptance((_value) * 1e-9d, ElectricSusceptanceUnit.Siemens), - (ElectricSusceptanceUnit.Teramho, ElectricSusceptanceUnit.Siemens) => new ElectricSusceptance((_value) * 1e12d, ElectricSusceptanceUnit.Siemens), - (ElectricSusceptanceUnit.Terasiemens, ElectricSusceptanceUnit.Siemens) => new ElectricSusceptance((_value) * 1e12d, ElectricSusceptanceUnit.Siemens), - - // BaseUnit -> ElectricSusceptanceUnit - (ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Gigamho) => new ElectricSusceptance((_value) / 1e9d, ElectricSusceptanceUnit.Gigamho), - (ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Gigasiemens) => new ElectricSusceptance((_value) / 1e9d, ElectricSusceptanceUnit.Gigasiemens), - (ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Kilomho) => new ElectricSusceptance((_value) / 1e3d, ElectricSusceptanceUnit.Kilomho), - (ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Kilosiemens) => new ElectricSusceptance((_value) / 1e3d, ElectricSusceptanceUnit.Kilosiemens), - (ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Megamho) => new ElectricSusceptance((_value) / 1e6d, ElectricSusceptanceUnit.Megamho), - (ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Megasiemens) => new ElectricSusceptance((_value) / 1e6d, ElectricSusceptanceUnit.Megasiemens), - (ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Mho) => new ElectricSusceptance(_value, ElectricSusceptanceUnit.Mho), - (ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Micromho) => new ElectricSusceptance((_value) / 1e-6d, ElectricSusceptanceUnit.Micromho), - (ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Microsiemens) => new ElectricSusceptance((_value) / 1e-6d, ElectricSusceptanceUnit.Microsiemens), - (ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Millimho) => new ElectricSusceptance((_value) / 1e-3d, ElectricSusceptanceUnit.Millimho), - (ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Millisiemens) => new ElectricSusceptance((_value) / 1e-3d, ElectricSusceptanceUnit.Millisiemens), - (ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Nanomho) => new ElectricSusceptance((_value) / 1e-9d, ElectricSusceptanceUnit.Nanomho), - (ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Nanosiemens) => new ElectricSusceptance((_value) / 1e-9d, ElectricSusceptanceUnit.Nanosiemens), - (ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Teramho) => new ElectricSusceptance((_value) / 1e12d, ElectricSusceptanceUnit.Teramho), - (ElectricSusceptanceUnit.Siemens, ElectricSusceptanceUnit.Terasiemens) => new ElectricSusceptance((_value) / 1e12d, ElectricSusceptanceUnit.Terasiemens), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ElectricSusceptance ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ElectricSusceptanceUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricSusceptanceUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ElectricSusceptanceUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ElectricSusceptanceUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ElectricSusceptanceUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ElectricSusceptanceUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1020,7 +828,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Energy.g.cs b/UnitsNet/GeneratedCode/Quantities/Energy.g.cs index 461c050225..50c8ad94ff 100644 --- a/UnitsNet/GeneratedCode/Quantities/Energy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Energy.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Energy : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -65,13 +64,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly EnergyUnit? _unit; /// @@ -116,7 +115,7 @@ public static EnergyInfo CreateDefault(Func - /// The for is [T^-2][L^2][M]. + /// The for is T^-2L^2M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); @@ -131,54 +130,130 @@ public static EnergyInfo CreateDefault(FuncAn of representing the default unit mappings for Energy. public static IEnumerable> GetDefaultMappings() { - yield return new (EnergyUnit.BritishThermalUnit, "BritishThermalUnit", "BritishThermalUnits", BaseUnits.Undefined); - yield return new (EnergyUnit.Calorie, "Calorie", "Calories", BaseUnits.Undefined); - yield return new (EnergyUnit.DecathermEc, "DecathermEc", "DecathermsEc", BaseUnits.Undefined); - yield return new (EnergyUnit.DecathermImperial, "DecathermImperial", "DecathermsImperial", BaseUnits.Undefined); - yield return new (EnergyUnit.DecathermUs, "DecathermUs", "DecathermsUs", BaseUnits.Undefined); - yield return new (EnergyUnit.ElectronVolt, "ElectronVolt", "ElectronVolts", BaseUnits.Undefined); - yield return new (EnergyUnit.Erg, "Erg", "Ergs", BaseUnits.Undefined); - yield return new (EnergyUnit.FootPound, "FootPound", "FootPounds", BaseUnits.Undefined); - yield return new (EnergyUnit.GigabritishThermalUnit, "GigabritishThermalUnit", "GigabritishThermalUnits", BaseUnits.Undefined); - yield return new (EnergyUnit.GigaelectronVolt, "GigaelectronVolt", "GigaelectronVolts", BaseUnits.Undefined); - yield return new (EnergyUnit.Gigajoule, "Gigajoule", "Gigajoules", BaseUnits.Undefined); - yield return new (EnergyUnit.GigawattDay, "GigawattDay", "GigawattDays", BaseUnits.Undefined); - yield return new (EnergyUnit.GigawattHour, "GigawattHour", "GigawattHours", BaseUnits.Undefined); - yield return new (EnergyUnit.HorsepowerHour, "HorsepowerHour", "HorsepowerHours", BaseUnits.Undefined); + yield return new (EnergyUnit.BritishThermalUnit, "BritishThermalUnit", "BritishThermalUnits", BaseUnits.Undefined, + new QuantityValue(50000000, 52752792631) + ); + yield return new (EnergyUnit.Calorie, "Calorie", "Calories", BaseUnits.Undefined, + new QuantityValue(125, 523) + ); + yield return new (EnergyUnit.DecathermEc, "DecathermEc", "DecathermsEc", BaseUnits.Undefined, + new QuantityValue(50, 52752792631) + ); + yield return new (EnergyUnit.DecathermImperial, "DecathermImperial", "DecathermsImperial", BaseUnits.Undefined, + new QuantityValue(25000, 26376396314337) + ); + yield return new (EnergyUnit.DecathermUs, "DecathermUs", "DecathermsUs", BaseUnits.Undefined, + new QuantityValue(1, 1054804000) + ); + yield return new (EnergyUnit.ElectronVolt, "ElectronVolt", "ElectronVolts", BaseUnits.Undefined, + new QuantityValue(new BigInteger(5) * QuantityValue.PowerOfTen(27), 801088317) + ); + yield return new (EnergyUnit.Erg, "Erg", "Ergs", BaseUnits.Undefined, + 10000000 + ); + yield return new (EnergyUnit.FootPound, "FootPound", "FootPounds", BaseUnits.Undefined, + new QuantityValue(2500000000000000, 3389544870828501) + ); + yield return new (EnergyUnit.GigabritishThermalUnit, "GigabritishThermalUnit", "GigabritishThermalUnits", BaseUnits.Undefined, + new QuantityValue(1, 1055055852620) + ); + yield return new (EnergyUnit.GigaelectronVolt, "GigaelectronVolt", "GigaelectronVolts", BaseUnits.Undefined, + new QuantityValue(5000000000000000000, 801088317) + ); + yield return new (EnergyUnit.Gigajoule, "Gigajoule", "Gigajoules", BaseUnits.Undefined, + new QuantityValue(1, 1000000000) + ); + yield return new (EnergyUnit.GigawattDay, "GigawattDay", "GigawattDays", BaseUnits.Undefined, + new QuantityValue(1, 86400000000000) + ); + yield return new (EnergyUnit.GigawattHour, "GigawattHour", "GigawattHours", BaseUnits.Undefined, + new QuantityValue(1, 3600000000000) + ); + yield return new (EnergyUnit.HorsepowerHour, "HorsepowerHour", "HorsepowerHours", BaseUnits.Undefined, + new QuantityValue(500000000, 1342259768728053) + ); yield return new (EnergyUnit.Joule, "Joule", "Joules", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (EnergyUnit.KilobritishThermalUnit, "KilobritishThermalUnit", "KilobritishThermalUnits", BaseUnits.Undefined); - yield return new (EnergyUnit.Kilocalorie, "Kilocalorie", "Kilocalories", BaseUnits.Undefined); - yield return new (EnergyUnit.KiloelectronVolt, "KiloelectronVolt", "KiloelectronVolts", BaseUnits.Undefined); - yield return new (EnergyUnit.Kilojoule, "Kilojoule", "Kilojoules", BaseUnits.Undefined); - yield return new (EnergyUnit.KilowattDay, "KilowattDay", "KilowattDays", BaseUnits.Undefined); - yield return new (EnergyUnit.KilowattHour, "KilowattHour", "KilowattHours", BaseUnits.Undefined); - yield return new (EnergyUnit.MegabritishThermalUnit, "MegabritishThermalUnit", "MegabritishThermalUnits", BaseUnits.Undefined); - yield return new (EnergyUnit.Megacalorie, "Megacalorie", "Megacalories", BaseUnits.Undefined); - yield return new (EnergyUnit.MegaelectronVolt, "MegaelectronVolt", "MegaelectronVolts", BaseUnits.Undefined); - yield return new (EnergyUnit.Megajoule, "Megajoule", "Megajoules", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (EnergyUnit.MegawattDay, "MegawattDay", "MegawattDays", BaseUnits.Undefined); - yield return new (EnergyUnit.MegawattHour, "MegawattHour", "MegawattHours", BaseUnits.Undefined); - yield return new (EnergyUnit.Microjoule, "Microjoule", "Microjoules", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second)); - yield return new (EnergyUnit.Millijoule, "Millijoule", "Millijoules", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second)); - yield return new (EnergyUnit.Nanojoule, "Nanojoule", "Nanojoules", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second)); - yield return new (EnergyUnit.Petajoule, "Petajoule", "Petajoules", BaseUnits.Undefined); - yield return new (EnergyUnit.TeraelectronVolt, "TeraelectronVolt", "TeraelectronVolts", BaseUnits.Undefined); - yield return new (EnergyUnit.Terajoule, "Terajoule", "Terajoules", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (EnergyUnit.TerawattDay, "TerawattDay", "TerawattDays", BaseUnits.Undefined); - yield return new (EnergyUnit.TerawattHour, "TerawattHour", "TerawattHours", BaseUnits.Undefined); - yield return new (EnergyUnit.ThermEc, "ThermEc", "ThermsEc", BaseUnits.Undefined); - yield return new (EnergyUnit.ThermImperial, "ThermImperial", "ThermsImperial", BaseUnits.Undefined); - yield return new (EnergyUnit.ThermUs, "ThermUs", "ThermsUs", BaseUnits.Undefined); - yield return new (EnergyUnit.WattDay, "WattDay", "WattDays", BaseUnits.Undefined); - yield return new (EnergyUnit.WattHour, "WattHour", "WattHours", BaseUnits.Undefined); + yield return new (EnergyUnit.KilobritishThermalUnit, "KilobritishThermalUnit", "KilobritishThermalUnits", BaseUnits.Undefined, + new QuantityValue(50000, 52752792631) + ); + yield return new (EnergyUnit.Kilocalorie, "Kilocalorie", "Kilocalories", BaseUnits.Undefined, + new QuantityValue(1, 4184) + ); + yield return new (EnergyUnit.KiloelectronVolt, "KiloelectronVolt", "KiloelectronVolts", BaseUnits.Undefined, + new QuantityValue(new BigInteger(5) * QuantityValue.PowerOfTen(24), 801088317) + ); + yield return new (EnergyUnit.Kilojoule, "Kilojoule", "Kilojoules", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (EnergyUnit.KilowattDay, "KilowattDay", "KilowattDays", BaseUnits.Undefined, + new QuantityValue(1, 86400000) + ); + yield return new (EnergyUnit.KilowattHour, "KilowattHour", "KilowattHours", BaseUnits.Undefined, + new QuantityValue(1, 3600000) + ); + yield return new (EnergyUnit.MegabritishThermalUnit, "MegabritishThermalUnit", "MegabritishThermalUnits", BaseUnits.Undefined, + new QuantityValue(50, 52752792631) + ); + yield return new (EnergyUnit.Megacalorie, "Megacalorie", "Megacalories", BaseUnits.Undefined, + new QuantityValue(1, 4184000) + ); + yield return new (EnergyUnit.MegaelectronVolt, "MegaelectronVolt", "MegaelectronVolts", BaseUnits.Undefined, + new QuantityValue(new BigInteger(5) * QuantityValue.PowerOfTen(21), 801088317) + ); + yield return new (EnergyUnit.Megajoule, "Megajoule", "Megajoules", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (EnergyUnit.MegawattDay, "MegawattDay", "MegawattDays", BaseUnits.Undefined, + new QuantityValue(1, 86400000000) + ); + yield return new (EnergyUnit.MegawattHour, "MegawattHour", "MegawattHours", BaseUnits.Undefined, + new QuantityValue(1, 3600000000) + ); + yield return new (EnergyUnit.Microjoule, "Microjoule", "Microjoules", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second), + 1000000 + ); + yield return new (EnergyUnit.Millijoule, "Millijoule", "Millijoules", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second), + 1000 + ); + yield return new (EnergyUnit.Nanojoule, "Nanojoule", "Nanojoules", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second), + 1000000000 + ); + yield return new (EnergyUnit.Petajoule, "Petajoule", "Petajoules", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000000) + ); + yield return new (EnergyUnit.TeraelectronVolt, "TeraelectronVolt", "TeraelectronVolts", BaseUnits.Undefined, + new QuantityValue(5000000000000000, 801088317) + ); + yield return new (EnergyUnit.Terajoule, "Terajoule", "Terajoules", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000000000) + ); + yield return new (EnergyUnit.TerawattDay, "TerawattDay", "TerawattDays", BaseUnits.Undefined, + new QuantityValue(1, 86400000000000000) + ); + yield return new (EnergyUnit.TerawattHour, "TerawattHour", "TerawattHours", BaseUnits.Undefined, + new QuantityValue(1, 3600000000000000) + ); + yield return new (EnergyUnit.ThermEc, "ThermEc", "ThermsEc", BaseUnits.Undefined, + new QuantityValue(500, 52752792631) + ); + yield return new (EnergyUnit.ThermImperial, "ThermImperial", "ThermsImperial", BaseUnits.Undefined, + new QuantityValue(250000, 26376396314337) + ); + yield return new (EnergyUnit.ThermUs, "ThermUs", "ThermsUs", BaseUnits.Undefined, + new QuantityValue(1, 105480400) + ); + yield return new (EnergyUnit.WattDay, "WattDay", "WattDays", BaseUnits.Undefined, + new QuantityValue(1, 86400) + ); + yield return new (EnergyUnit.WattHour, "WattHour", "WattHours", BaseUnits.Undefined, + new QuantityValue(1, 3600) + ); } } static Energy() { - Info = EnergyInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(EnergyInfo.CreateDefault); } /// @@ -186,7 +261,7 @@ static Energy() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Energy(double value, EnergyUnit unit) + public Energy(QuantityValue value, EnergyUnit unit) { _value = value; _unit = unit; @@ -200,7 +275,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -211,7 +286,8 @@ public Energy(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -240,10 +316,8 @@ public Energy(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public EnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -282,301 +356,209 @@ public Energy(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BritishThermalUnits => As(EnergyUnit.BritishThermalUnit); + public QuantityValue BritishThermalUnits => this.As(EnergyUnit.BritishThermalUnit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Calories => As(EnergyUnit.Calorie); + public QuantityValue Calories => this.As(EnergyUnit.Calorie); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecathermsEc => As(EnergyUnit.DecathermEc); + public QuantityValue DecathermsEc => this.As(EnergyUnit.DecathermEc); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecathermsImperial => As(EnergyUnit.DecathermImperial); + public QuantityValue DecathermsImperial => this.As(EnergyUnit.DecathermImperial); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecathermsUs => As(EnergyUnit.DecathermUs); + public QuantityValue DecathermsUs => this.As(EnergyUnit.DecathermUs); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ElectronVolts => As(EnergyUnit.ElectronVolt); + public QuantityValue ElectronVolts => this.As(EnergyUnit.ElectronVolt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Ergs => As(EnergyUnit.Erg); + public QuantityValue Ergs => this.As(EnergyUnit.Erg); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double FootPounds => As(EnergyUnit.FootPound); + public QuantityValue FootPounds => this.As(EnergyUnit.FootPound); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigabritishThermalUnits => As(EnergyUnit.GigabritishThermalUnit); + public QuantityValue GigabritishThermalUnits => this.As(EnergyUnit.GigabritishThermalUnit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigaelectronVolts => As(EnergyUnit.GigaelectronVolt); + public QuantityValue GigaelectronVolts => this.As(EnergyUnit.GigaelectronVolt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigajoules => As(EnergyUnit.Gigajoule); + public QuantityValue Gigajoules => this.As(EnergyUnit.Gigajoule); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigawattDays => As(EnergyUnit.GigawattDay); + public QuantityValue GigawattDays => this.As(EnergyUnit.GigawattDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigawattHours => As(EnergyUnit.GigawattHour); + public QuantityValue GigawattHours => this.As(EnergyUnit.GigawattHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HorsepowerHours => As(EnergyUnit.HorsepowerHour); + public QuantityValue HorsepowerHours => this.As(EnergyUnit.HorsepowerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Joules => As(EnergyUnit.Joule); + public QuantityValue Joules => this.As(EnergyUnit.Joule); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilobritishThermalUnits => As(EnergyUnit.KilobritishThermalUnit); + public QuantityValue KilobritishThermalUnits => this.As(EnergyUnit.KilobritishThermalUnit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilocalories => As(EnergyUnit.Kilocalorie); + public QuantityValue Kilocalories => this.As(EnergyUnit.Kilocalorie); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KiloelectronVolts => As(EnergyUnit.KiloelectronVolt); + public QuantityValue KiloelectronVolts => this.As(EnergyUnit.KiloelectronVolt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilojoules => As(EnergyUnit.Kilojoule); + public QuantityValue Kilojoules => this.As(EnergyUnit.Kilojoule); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattDays => As(EnergyUnit.KilowattDay); + public QuantityValue KilowattDays => this.As(EnergyUnit.KilowattDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattHours => As(EnergyUnit.KilowattHour); + public QuantityValue KilowattHours => this.As(EnergyUnit.KilowattHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegabritishThermalUnits => As(EnergyUnit.MegabritishThermalUnit); + public QuantityValue MegabritishThermalUnits => this.As(EnergyUnit.MegabritishThermalUnit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megacalories => As(EnergyUnit.Megacalorie); + public QuantityValue Megacalories => this.As(EnergyUnit.Megacalorie); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegaelectronVolts => As(EnergyUnit.MegaelectronVolt); + public QuantityValue MegaelectronVolts => this.As(EnergyUnit.MegaelectronVolt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megajoules => As(EnergyUnit.Megajoule); + public QuantityValue Megajoules => this.As(EnergyUnit.Megajoule); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattDays => As(EnergyUnit.MegawattDay); + public QuantityValue MegawattDays => this.As(EnergyUnit.MegawattDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattHours => As(EnergyUnit.MegawattHour); + public QuantityValue MegawattHours => this.As(EnergyUnit.MegawattHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microjoules => As(EnergyUnit.Microjoule); + public QuantityValue Microjoules => this.As(EnergyUnit.Microjoule); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millijoules => As(EnergyUnit.Millijoule); + public QuantityValue Millijoules => this.As(EnergyUnit.Millijoule); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanojoules => As(EnergyUnit.Nanojoule); + public QuantityValue Nanojoules => this.As(EnergyUnit.Nanojoule); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Petajoules => As(EnergyUnit.Petajoule); + public QuantityValue Petajoules => this.As(EnergyUnit.Petajoule); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TeraelectronVolts => As(EnergyUnit.TeraelectronVolt); + public QuantityValue TeraelectronVolts => this.As(EnergyUnit.TeraelectronVolt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Terajoules => As(EnergyUnit.Terajoule); + public QuantityValue Terajoules => this.As(EnergyUnit.Terajoule); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TerawattDays => As(EnergyUnit.TerawattDay); + public QuantityValue TerawattDays => this.As(EnergyUnit.TerawattDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TerawattHours => As(EnergyUnit.TerawattHour); + public QuantityValue TerawattHours => this.As(EnergyUnit.TerawattHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ThermsEc => As(EnergyUnit.ThermEc); + public QuantityValue ThermsEc => this.As(EnergyUnit.ThermEc); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ThermsImperial => As(EnergyUnit.ThermImperial); + public QuantityValue ThermsImperial => this.As(EnergyUnit.ThermImperial); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ThermsUs => As(EnergyUnit.ThermUs); + public QuantityValue ThermsUs => this.As(EnergyUnit.ThermUs); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattDays => As(EnergyUnit.WattDay); + public QuantityValue WattDays => this.As(EnergyUnit.WattDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattHours => As(EnergyUnit.WattHour); + public QuantityValue WattHours => this.As(EnergyUnit.WattHour); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: EnergyUnit -> BaseUnit - unitConverter.SetConversionFunction(EnergyUnit.BritishThermalUnit, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.Calorie, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.DecathermEc, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.DecathermImperial, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.DecathermUs, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.ElectronVolt, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.Erg, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.FootPound, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.GigabritishThermalUnit, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.GigaelectronVolt, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.Gigajoule, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.GigawattDay, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.GigawattHour, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.HorsepowerHour, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.KilobritishThermalUnit, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.Kilocalorie, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.KiloelectronVolt, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.Kilojoule, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.KilowattDay, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.KilowattHour, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.MegabritishThermalUnit, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.Megacalorie, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.MegaelectronVolt, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.Megajoule, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.MegawattDay, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.MegawattHour, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.Microjoule, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.Millijoule, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.Nanojoule, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.Petajoule, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.TeraelectronVolt, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.Terajoule, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.TerawattDay, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.TerawattHour, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.ThermEc, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.ThermImperial, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.ThermUs, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.WattDay, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - unitConverter.SetConversionFunction(EnergyUnit.WattHour, EnergyUnit.Joule, quantity => quantity.ToUnit(EnergyUnit.Joule)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Joule, quantity => quantity); - - // Register in unit converter: BaseUnit -> EnergyUnit - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.BritishThermalUnit, quantity => quantity.ToUnit(EnergyUnit.BritishThermalUnit)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Calorie, quantity => quantity.ToUnit(EnergyUnit.Calorie)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.DecathermEc, quantity => quantity.ToUnit(EnergyUnit.DecathermEc)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.DecathermImperial, quantity => quantity.ToUnit(EnergyUnit.DecathermImperial)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.DecathermUs, quantity => quantity.ToUnit(EnergyUnit.DecathermUs)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.ElectronVolt, quantity => quantity.ToUnit(EnergyUnit.ElectronVolt)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Erg, quantity => quantity.ToUnit(EnergyUnit.Erg)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.FootPound, quantity => quantity.ToUnit(EnergyUnit.FootPound)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.GigabritishThermalUnit, quantity => quantity.ToUnit(EnergyUnit.GigabritishThermalUnit)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.GigaelectronVolt, quantity => quantity.ToUnit(EnergyUnit.GigaelectronVolt)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Gigajoule, quantity => quantity.ToUnit(EnergyUnit.Gigajoule)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.GigawattDay, quantity => quantity.ToUnit(EnergyUnit.GigawattDay)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.GigawattHour, quantity => quantity.ToUnit(EnergyUnit.GigawattHour)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.HorsepowerHour, quantity => quantity.ToUnit(EnergyUnit.HorsepowerHour)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.KilobritishThermalUnit, quantity => quantity.ToUnit(EnergyUnit.KilobritishThermalUnit)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Kilocalorie, quantity => quantity.ToUnit(EnergyUnit.Kilocalorie)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.KiloelectronVolt, quantity => quantity.ToUnit(EnergyUnit.KiloelectronVolt)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Kilojoule, quantity => quantity.ToUnit(EnergyUnit.Kilojoule)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.KilowattDay, quantity => quantity.ToUnit(EnergyUnit.KilowattDay)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.KilowattHour, quantity => quantity.ToUnit(EnergyUnit.KilowattHour)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.MegabritishThermalUnit, quantity => quantity.ToUnit(EnergyUnit.MegabritishThermalUnit)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Megacalorie, quantity => quantity.ToUnit(EnergyUnit.Megacalorie)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.MegaelectronVolt, quantity => quantity.ToUnit(EnergyUnit.MegaelectronVolt)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Megajoule, quantity => quantity.ToUnit(EnergyUnit.Megajoule)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.MegawattDay, quantity => quantity.ToUnit(EnergyUnit.MegawattDay)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.MegawattHour, quantity => quantity.ToUnit(EnergyUnit.MegawattHour)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Microjoule, quantity => quantity.ToUnit(EnergyUnit.Microjoule)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Millijoule, quantity => quantity.ToUnit(EnergyUnit.Millijoule)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Nanojoule, quantity => quantity.ToUnit(EnergyUnit.Nanojoule)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Petajoule, quantity => quantity.ToUnit(EnergyUnit.Petajoule)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.TeraelectronVolt, quantity => quantity.ToUnit(EnergyUnit.TeraelectronVolt)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.Terajoule, quantity => quantity.ToUnit(EnergyUnit.Terajoule)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.TerawattDay, quantity => quantity.ToUnit(EnergyUnit.TerawattDay)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.TerawattHour, quantity => quantity.ToUnit(EnergyUnit.TerawattHour)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.ThermEc, quantity => quantity.ToUnit(EnergyUnit.ThermEc)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.ThermImperial, quantity => quantity.ToUnit(EnergyUnit.ThermImperial)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.ThermUs, quantity => quantity.ToUnit(EnergyUnit.ThermUs)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.WattDay, quantity => quantity.ToUnit(EnergyUnit.WattDay)); - unitConverter.SetConversionFunction(EnergyUnit.Joule, EnergyUnit.WattHour, quantity => quantity.ToUnit(EnergyUnit.WattHour)); - } - /// /// Get unit abbreviation string. /// @@ -605,7 +587,7 @@ public static string GetAbbreviation(EnergyUnit unit, IFormatProvider? provider) /// /// Creates a from . /// - public static Energy FromBritishThermalUnits(double value) + public static Energy FromBritishThermalUnits(QuantityValue value) { return new Energy(value, EnergyUnit.BritishThermalUnit); } @@ -613,7 +595,7 @@ public static Energy FromBritishThermalUnits(double value) /// /// Creates a from . /// - public static Energy FromCalories(double value) + public static Energy FromCalories(QuantityValue value) { return new Energy(value, EnergyUnit.Calorie); } @@ -621,7 +603,7 @@ public static Energy FromCalories(double value) /// /// Creates a from . /// - public static Energy FromDecathermsEc(double value) + public static Energy FromDecathermsEc(QuantityValue value) { return new Energy(value, EnergyUnit.DecathermEc); } @@ -629,7 +611,7 @@ public static Energy FromDecathermsEc(double value) /// /// Creates a from . /// - public static Energy FromDecathermsImperial(double value) + public static Energy FromDecathermsImperial(QuantityValue value) { return new Energy(value, EnergyUnit.DecathermImperial); } @@ -637,7 +619,7 @@ public static Energy FromDecathermsImperial(double value) /// /// Creates a from . /// - public static Energy FromDecathermsUs(double value) + public static Energy FromDecathermsUs(QuantityValue value) { return new Energy(value, EnergyUnit.DecathermUs); } @@ -645,7 +627,7 @@ public static Energy FromDecathermsUs(double value) /// /// Creates a from . /// - public static Energy FromElectronVolts(double value) + public static Energy FromElectronVolts(QuantityValue value) { return new Energy(value, EnergyUnit.ElectronVolt); } @@ -653,7 +635,7 @@ public static Energy FromElectronVolts(double value) /// /// Creates a from . /// - public static Energy FromErgs(double value) + public static Energy FromErgs(QuantityValue value) { return new Energy(value, EnergyUnit.Erg); } @@ -661,7 +643,7 @@ public static Energy FromErgs(double value) /// /// Creates a from . /// - public static Energy FromFootPounds(double value) + public static Energy FromFootPounds(QuantityValue value) { return new Energy(value, EnergyUnit.FootPound); } @@ -669,7 +651,7 @@ public static Energy FromFootPounds(double value) /// /// Creates a from . /// - public static Energy FromGigabritishThermalUnits(double value) + public static Energy FromGigabritishThermalUnits(QuantityValue value) { return new Energy(value, EnergyUnit.GigabritishThermalUnit); } @@ -677,7 +659,7 @@ public static Energy FromGigabritishThermalUnits(double value) /// /// Creates a from . /// - public static Energy FromGigaelectronVolts(double value) + public static Energy FromGigaelectronVolts(QuantityValue value) { return new Energy(value, EnergyUnit.GigaelectronVolt); } @@ -685,7 +667,7 @@ public static Energy FromGigaelectronVolts(double value) /// /// Creates a from . /// - public static Energy FromGigajoules(double value) + public static Energy FromGigajoules(QuantityValue value) { return new Energy(value, EnergyUnit.Gigajoule); } @@ -693,7 +675,7 @@ public static Energy FromGigajoules(double value) /// /// Creates a from . /// - public static Energy FromGigawattDays(double value) + public static Energy FromGigawattDays(QuantityValue value) { return new Energy(value, EnergyUnit.GigawattDay); } @@ -701,7 +683,7 @@ public static Energy FromGigawattDays(double value) /// /// Creates a from . /// - public static Energy FromGigawattHours(double value) + public static Energy FromGigawattHours(QuantityValue value) { return new Energy(value, EnergyUnit.GigawattHour); } @@ -709,7 +691,7 @@ public static Energy FromGigawattHours(double value) /// /// Creates a from . /// - public static Energy FromHorsepowerHours(double value) + public static Energy FromHorsepowerHours(QuantityValue value) { return new Energy(value, EnergyUnit.HorsepowerHour); } @@ -717,7 +699,7 @@ public static Energy FromHorsepowerHours(double value) /// /// Creates a from . /// - public static Energy FromJoules(double value) + public static Energy FromJoules(QuantityValue value) { return new Energy(value, EnergyUnit.Joule); } @@ -725,7 +707,7 @@ public static Energy FromJoules(double value) /// /// Creates a from . /// - public static Energy FromKilobritishThermalUnits(double value) + public static Energy FromKilobritishThermalUnits(QuantityValue value) { return new Energy(value, EnergyUnit.KilobritishThermalUnit); } @@ -733,7 +715,7 @@ public static Energy FromKilobritishThermalUnits(double value) /// /// Creates a from . /// - public static Energy FromKilocalories(double value) + public static Energy FromKilocalories(QuantityValue value) { return new Energy(value, EnergyUnit.Kilocalorie); } @@ -741,7 +723,7 @@ public static Energy FromKilocalories(double value) /// /// Creates a from . /// - public static Energy FromKiloelectronVolts(double value) + public static Energy FromKiloelectronVolts(QuantityValue value) { return new Energy(value, EnergyUnit.KiloelectronVolt); } @@ -749,7 +731,7 @@ public static Energy FromKiloelectronVolts(double value) /// /// Creates a from . /// - public static Energy FromKilojoules(double value) + public static Energy FromKilojoules(QuantityValue value) { return new Energy(value, EnergyUnit.Kilojoule); } @@ -757,7 +739,7 @@ public static Energy FromKilojoules(double value) /// /// Creates a from . /// - public static Energy FromKilowattDays(double value) + public static Energy FromKilowattDays(QuantityValue value) { return new Energy(value, EnergyUnit.KilowattDay); } @@ -765,7 +747,7 @@ public static Energy FromKilowattDays(double value) /// /// Creates a from . /// - public static Energy FromKilowattHours(double value) + public static Energy FromKilowattHours(QuantityValue value) { return new Energy(value, EnergyUnit.KilowattHour); } @@ -773,7 +755,7 @@ public static Energy FromKilowattHours(double value) /// /// Creates a from . /// - public static Energy FromMegabritishThermalUnits(double value) + public static Energy FromMegabritishThermalUnits(QuantityValue value) { return new Energy(value, EnergyUnit.MegabritishThermalUnit); } @@ -781,7 +763,7 @@ public static Energy FromMegabritishThermalUnits(double value) /// /// Creates a from . /// - public static Energy FromMegacalories(double value) + public static Energy FromMegacalories(QuantityValue value) { return new Energy(value, EnergyUnit.Megacalorie); } @@ -789,7 +771,7 @@ public static Energy FromMegacalories(double value) /// /// Creates a from . /// - public static Energy FromMegaelectronVolts(double value) + public static Energy FromMegaelectronVolts(QuantityValue value) { return new Energy(value, EnergyUnit.MegaelectronVolt); } @@ -797,7 +779,7 @@ public static Energy FromMegaelectronVolts(double value) /// /// Creates a from . /// - public static Energy FromMegajoules(double value) + public static Energy FromMegajoules(QuantityValue value) { return new Energy(value, EnergyUnit.Megajoule); } @@ -805,7 +787,7 @@ public static Energy FromMegajoules(double value) /// /// Creates a from . /// - public static Energy FromMegawattDays(double value) + public static Energy FromMegawattDays(QuantityValue value) { return new Energy(value, EnergyUnit.MegawattDay); } @@ -813,7 +795,7 @@ public static Energy FromMegawattDays(double value) /// /// Creates a from . /// - public static Energy FromMegawattHours(double value) + public static Energy FromMegawattHours(QuantityValue value) { return new Energy(value, EnergyUnit.MegawattHour); } @@ -821,7 +803,7 @@ public static Energy FromMegawattHours(double value) /// /// Creates a from . /// - public static Energy FromMicrojoules(double value) + public static Energy FromMicrojoules(QuantityValue value) { return new Energy(value, EnergyUnit.Microjoule); } @@ -829,7 +811,7 @@ public static Energy FromMicrojoules(double value) /// /// Creates a from . /// - public static Energy FromMillijoules(double value) + public static Energy FromMillijoules(QuantityValue value) { return new Energy(value, EnergyUnit.Millijoule); } @@ -837,7 +819,7 @@ public static Energy FromMillijoules(double value) /// /// Creates a from . /// - public static Energy FromNanojoules(double value) + public static Energy FromNanojoules(QuantityValue value) { return new Energy(value, EnergyUnit.Nanojoule); } @@ -845,7 +827,7 @@ public static Energy FromNanojoules(double value) /// /// Creates a from . /// - public static Energy FromPetajoules(double value) + public static Energy FromPetajoules(QuantityValue value) { return new Energy(value, EnergyUnit.Petajoule); } @@ -853,7 +835,7 @@ public static Energy FromPetajoules(double value) /// /// Creates a from . /// - public static Energy FromTeraelectronVolts(double value) + public static Energy FromTeraelectronVolts(QuantityValue value) { return new Energy(value, EnergyUnit.TeraelectronVolt); } @@ -861,7 +843,7 @@ public static Energy FromTeraelectronVolts(double value) /// /// Creates a from . /// - public static Energy FromTerajoules(double value) + public static Energy FromTerajoules(QuantityValue value) { return new Energy(value, EnergyUnit.Terajoule); } @@ -869,7 +851,7 @@ public static Energy FromTerajoules(double value) /// /// Creates a from . /// - public static Energy FromTerawattDays(double value) + public static Energy FromTerawattDays(QuantityValue value) { return new Energy(value, EnergyUnit.TerawattDay); } @@ -877,7 +859,7 @@ public static Energy FromTerawattDays(double value) /// /// Creates a from . /// - public static Energy FromTerawattHours(double value) + public static Energy FromTerawattHours(QuantityValue value) { return new Energy(value, EnergyUnit.TerawattHour); } @@ -885,7 +867,7 @@ public static Energy FromTerawattHours(double value) /// /// Creates a from . /// - public static Energy FromThermsEc(double value) + public static Energy FromThermsEc(QuantityValue value) { return new Energy(value, EnergyUnit.ThermEc); } @@ -893,7 +875,7 @@ public static Energy FromThermsEc(double value) /// /// Creates a from . /// - public static Energy FromThermsImperial(double value) + public static Energy FromThermsImperial(QuantityValue value) { return new Energy(value, EnergyUnit.ThermImperial); } @@ -901,7 +883,7 @@ public static Energy FromThermsImperial(double value) /// /// Creates a from . /// - public static Energy FromThermsUs(double value) + public static Energy FromThermsUs(QuantityValue value) { return new Energy(value, EnergyUnit.ThermUs); } @@ -909,7 +891,7 @@ public static Energy FromThermsUs(double value) /// /// Creates a from . /// - public static Energy FromWattDays(double value) + public static Energy FromWattDays(QuantityValue value) { return new Energy(value, EnergyUnit.WattDay); } @@ -917,7 +899,7 @@ public static Energy FromWattDays(double value) /// /// Creates a from . /// - public static Energy FromWattHours(double value) + public static Energy FromWattHours(QuantityValue value) { return new Energy(value, EnergyUnit.WattHour); } @@ -928,7 +910,7 @@ public static Energy FromWattHours(double value) /// Value to convert from. /// Unit to convert from. /// Energy unit value. - public static Energy From(double value, EnergyUnit fromUnit) + public static Energy From(QuantityValue value, EnergyUnit fromUnit) { return new Energy(value, fromUnit); } @@ -989,10 +971,7 @@ public static Energy Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Energy Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -1020,11 +999,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Energy result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Energy result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -1045,7 +1020,7 @@ public static EnergyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -1056,7 +1031,7 @@ public static EnergyUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out EnergyUnit unit) { return TryParseUnit(str, null, out unit); @@ -1071,7 +1046,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out EnergyUnit u /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out EnergyUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -1090,35 +1065,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Energy operator +(Energy left, Energy right) { - return new Energy(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Energy(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Energy operator -(Energy left, Energy right) { - return new Energy(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Energy(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -1212,97 +1187,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Energy left, Energy right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Energy left, Energy right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Energy left, Energy right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Energy left, Energy right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Energy other, Energy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Energy left, Energy right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Energy other, Energy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Energy left, Energy right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Energy other, Energy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Energy otherQuantity)) + if (obj is not Energy otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Energy other, Energy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Energy other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Energy. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Energy), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Energy otherQuantity)) throw new ArgumentException("Expected type Energy.", nameof(obj)); + if (obj is not Energy otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1314,224 +1274,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Energy other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(EnergyUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Energy to another Energy with the unit representation . - /// - /// The unit to convert to. - /// A Energy with the specified unit. - public Energy ToUnit(EnergyUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Energy with the specified unit. - public Energy ToUnit(EnergyUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Energy), Unit, typeof(Energy), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Energy)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(EnergyUnit unit, [NotNullWhen(true)] out Energy? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Energy? convertedOrNull = (Unit, unit) switch - { - // EnergyUnit -> BaseUnit - (EnergyUnit.BritishThermalUnit, EnergyUnit.Joule) => new Energy(_value * 1055.05585262, EnergyUnit.Joule), - (EnergyUnit.Calorie, EnergyUnit.Joule) => new Energy(_value * 4.184, EnergyUnit.Joule), - (EnergyUnit.DecathermEc, EnergyUnit.Joule) => new Energy((_value * 1.05505585262e8) * 1e1d, EnergyUnit.Joule), - (EnergyUnit.DecathermImperial, EnergyUnit.Joule) => new Energy((_value * 1.05505585257348e8) * 1e1d, EnergyUnit.Joule), - (EnergyUnit.DecathermUs, EnergyUnit.Joule) => new Energy((_value * 1.054804e8) * 1e1d, EnergyUnit.Joule), - (EnergyUnit.ElectronVolt, EnergyUnit.Joule) => new Energy(_value * 1.602176634e-19, EnergyUnit.Joule), - (EnergyUnit.Erg, EnergyUnit.Joule) => new Energy(_value * 1e-7, EnergyUnit.Joule), - (EnergyUnit.FootPound, EnergyUnit.Joule) => new Energy(_value * 1.3558179483314004, EnergyUnit.Joule), - (EnergyUnit.GigabritishThermalUnit, EnergyUnit.Joule) => new Energy((_value * 1055.05585262) * 1e9d, EnergyUnit.Joule), - (EnergyUnit.GigaelectronVolt, EnergyUnit.Joule) => new Energy((_value * 1.602176634e-19) * 1e9d, EnergyUnit.Joule), - (EnergyUnit.Gigajoule, EnergyUnit.Joule) => new Energy((_value) * 1e9d, EnergyUnit.Joule), - (EnergyUnit.GigawattDay, EnergyUnit.Joule) => new Energy((_value * 24 * 3600d) * 1e9d, EnergyUnit.Joule), - (EnergyUnit.GigawattHour, EnergyUnit.Joule) => new Energy((_value * 3600d) * 1e9d, EnergyUnit.Joule), - (EnergyUnit.HorsepowerHour, EnergyUnit.Joule) => new Energy(_value * 76.0402249 * 9.80665 * 3600, EnergyUnit.Joule), - (EnergyUnit.KilobritishThermalUnit, EnergyUnit.Joule) => new Energy((_value * 1055.05585262) * 1e3d, EnergyUnit.Joule), - (EnergyUnit.Kilocalorie, EnergyUnit.Joule) => new Energy((_value * 4.184) * 1e3d, EnergyUnit.Joule), - (EnergyUnit.KiloelectronVolt, EnergyUnit.Joule) => new Energy((_value * 1.602176634e-19) * 1e3d, EnergyUnit.Joule), - (EnergyUnit.Kilojoule, EnergyUnit.Joule) => new Energy((_value) * 1e3d, EnergyUnit.Joule), - (EnergyUnit.KilowattDay, EnergyUnit.Joule) => new Energy((_value * 24 * 3600d) * 1e3d, EnergyUnit.Joule), - (EnergyUnit.KilowattHour, EnergyUnit.Joule) => new Energy((_value * 3600d) * 1e3d, EnergyUnit.Joule), - (EnergyUnit.MegabritishThermalUnit, EnergyUnit.Joule) => new Energy((_value * 1055.05585262) * 1e6d, EnergyUnit.Joule), - (EnergyUnit.Megacalorie, EnergyUnit.Joule) => new Energy((_value * 4.184) * 1e6d, EnergyUnit.Joule), - (EnergyUnit.MegaelectronVolt, EnergyUnit.Joule) => new Energy((_value * 1.602176634e-19) * 1e6d, EnergyUnit.Joule), - (EnergyUnit.Megajoule, EnergyUnit.Joule) => new Energy((_value) * 1e6d, EnergyUnit.Joule), - (EnergyUnit.MegawattDay, EnergyUnit.Joule) => new Energy((_value * 24 * 3600d) * 1e6d, EnergyUnit.Joule), - (EnergyUnit.MegawattHour, EnergyUnit.Joule) => new Energy((_value * 3600d) * 1e6d, EnergyUnit.Joule), - (EnergyUnit.Microjoule, EnergyUnit.Joule) => new Energy((_value) * 1e-6d, EnergyUnit.Joule), - (EnergyUnit.Millijoule, EnergyUnit.Joule) => new Energy((_value) * 1e-3d, EnergyUnit.Joule), - (EnergyUnit.Nanojoule, EnergyUnit.Joule) => new Energy((_value) * 1e-9d, EnergyUnit.Joule), - (EnergyUnit.Petajoule, EnergyUnit.Joule) => new Energy((_value) * 1e15d, EnergyUnit.Joule), - (EnergyUnit.TeraelectronVolt, EnergyUnit.Joule) => new Energy((_value * 1.602176634e-19) * 1e12d, EnergyUnit.Joule), - (EnergyUnit.Terajoule, EnergyUnit.Joule) => new Energy((_value) * 1e12d, EnergyUnit.Joule), - (EnergyUnit.TerawattDay, EnergyUnit.Joule) => new Energy((_value * 24 * 3600d) * 1e12d, EnergyUnit.Joule), - (EnergyUnit.TerawattHour, EnergyUnit.Joule) => new Energy((_value * 3600d) * 1e12d, EnergyUnit.Joule), - (EnergyUnit.ThermEc, EnergyUnit.Joule) => new Energy(_value * 1.05505585262e8, EnergyUnit.Joule), - (EnergyUnit.ThermImperial, EnergyUnit.Joule) => new Energy(_value * 1.05505585257348e8, EnergyUnit.Joule), - (EnergyUnit.ThermUs, EnergyUnit.Joule) => new Energy(_value * 1.054804e8, EnergyUnit.Joule), - (EnergyUnit.WattDay, EnergyUnit.Joule) => new Energy(_value * 24 * 3600d, EnergyUnit.Joule), - (EnergyUnit.WattHour, EnergyUnit.Joule) => new Energy(_value * 3600d, EnergyUnit.Joule), - - // BaseUnit -> EnergyUnit - (EnergyUnit.Joule, EnergyUnit.BritishThermalUnit) => new Energy(_value / 1055.05585262, EnergyUnit.BritishThermalUnit), - (EnergyUnit.Joule, EnergyUnit.Calorie) => new Energy(_value / 4.184, EnergyUnit.Calorie), - (EnergyUnit.Joule, EnergyUnit.DecathermEc) => new Energy((_value / 1.05505585262e8) / 1e1d, EnergyUnit.DecathermEc), - (EnergyUnit.Joule, EnergyUnit.DecathermImperial) => new Energy((_value / 1.05505585257348e8) / 1e1d, EnergyUnit.DecathermImperial), - (EnergyUnit.Joule, EnergyUnit.DecathermUs) => new Energy((_value / 1.054804e8) / 1e1d, EnergyUnit.DecathermUs), - (EnergyUnit.Joule, EnergyUnit.ElectronVolt) => new Energy(_value / 1.602176634e-19, EnergyUnit.ElectronVolt), - (EnergyUnit.Joule, EnergyUnit.Erg) => new Energy(_value / 1e-7, EnergyUnit.Erg), - (EnergyUnit.Joule, EnergyUnit.FootPound) => new Energy(_value / 1.3558179483314004, EnergyUnit.FootPound), - (EnergyUnit.Joule, EnergyUnit.GigabritishThermalUnit) => new Energy((_value / 1055.05585262) / 1e9d, EnergyUnit.GigabritishThermalUnit), - (EnergyUnit.Joule, EnergyUnit.GigaelectronVolt) => new Energy((_value / 1.602176634e-19) / 1e9d, EnergyUnit.GigaelectronVolt), - (EnergyUnit.Joule, EnergyUnit.Gigajoule) => new Energy((_value) / 1e9d, EnergyUnit.Gigajoule), - (EnergyUnit.Joule, EnergyUnit.GigawattDay) => new Energy((_value / (24 * 3600d)) / 1e9d, EnergyUnit.GigawattDay), - (EnergyUnit.Joule, EnergyUnit.GigawattHour) => new Energy((_value / 3600d) / 1e9d, EnergyUnit.GigawattHour), - (EnergyUnit.Joule, EnergyUnit.HorsepowerHour) => new Energy(_value / (76.0402249 * 9.80665 * 3600), EnergyUnit.HorsepowerHour), - (EnergyUnit.Joule, EnergyUnit.KilobritishThermalUnit) => new Energy((_value / 1055.05585262) / 1e3d, EnergyUnit.KilobritishThermalUnit), - (EnergyUnit.Joule, EnergyUnit.Kilocalorie) => new Energy((_value / 4.184) / 1e3d, EnergyUnit.Kilocalorie), - (EnergyUnit.Joule, EnergyUnit.KiloelectronVolt) => new Energy((_value / 1.602176634e-19) / 1e3d, EnergyUnit.KiloelectronVolt), - (EnergyUnit.Joule, EnergyUnit.Kilojoule) => new Energy((_value) / 1e3d, EnergyUnit.Kilojoule), - (EnergyUnit.Joule, EnergyUnit.KilowattDay) => new Energy((_value / (24 * 3600d)) / 1e3d, EnergyUnit.KilowattDay), - (EnergyUnit.Joule, EnergyUnit.KilowattHour) => new Energy((_value / 3600d) / 1e3d, EnergyUnit.KilowattHour), - (EnergyUnit.Joule, EnergyUnit.MegabritishThermalUnit) => new Energy((_value / 1055.05585262) / 1e6d, EnergyUnit.MegabritishThermalUnit), - (EnergyUnit.Joule, EnergyUnit.Megacalorie) => new Energy((_value / 4.184) / 1e6d, EnergyUnit.Megacalorie), - (EnergyUnit.Joule, EnergyUnit.MegaelectronVolt) => new Energy((_value / 1.602176634e-19) / 1e6d, EnergyUnit.MegaelectronVolt), - (EnergyUnit.Joule, EnergyUnit.Megajoule) => new Energy((_value) / 1e6d, EnergyUnit.Megajoule), - (EnergyUnit.Joule, EnergyUnit.MegawattDay) => new Energy((_value / (24 * 3600d)) / 1e6d, EnergyUnit.MegawattDay), - (EnergyUnit.Joule, EnergyUnit.MegawattHour) => new Energy((_value / 3600d) / 1e6d, EnergyUnit.MegawattHour), - (EnergyUnit.Joule, EnergyUnit.Microjoule) => new Energy((_value) / 1e-6d, EnergyUnit.Microjoule), - (EnergyUnit.Joule, EnergyUnit.Millijoule) => new Energy((_value) / 1e-3d, EnergyUnit.Millijoule), - (EnergyUnit.Joule, EnergyUnit.Nanojoule) => new Energy((_value) / 1e-9d, EnergyUnit.Nanojoule), - (EnergyUnit.Joule, EnergyUnit.Petajoule) => new Energy((_value) / 1e15d, EnergyUnit.Petajoule), - (EnergyUnit.Joule, EnergyUnit.TeraelectronVolt) => new Energy((_value / 1.602176634e-19) / 1e12d, EnergyUnit.TeraelectronVolt), - (EnergyUnit.Joule, EnergyUnit.Terajoule) => new Energy((_value) / 1e12d, EnergyUnit.Terajoule), - (EnergyUnit.Joule, EnergyUnit.TerawattDay) => new Energy((_value / (24 * 3600d)) / 1e12d, EnergyUnit.TerawattDay), - (EnergyUnit.Joule, EnergyUnit.TerawattHour) => new Energy((_value / 3600d) / 1e12d, EnergyUnit.TerawattHour), - (EnergyUnit.Joule, EnergyUnit.ThermEc) => new Energy(_value / 1.05505585262e8, EnergyUnit.ThermEc), - (EnergyUnit.Joule, EnergyUnit.ThermImperial) => new Energy(_value / 1.05505585257348e8, EnergyUnit.ThermImperial), - (EnergyUnit.Joule, EnergyUnit.ThermUs) => new Energy(_value / 1.054804e8, EnergyUnit.ThermUs), - (EnergyUnit.Joule, EnergyUnit.WattDay) => new Energy(_value / (24 * 3600d), EnergyUnit.WattDay), - (EnergyUnit.Joule, EnergyUnit.WattHour) => new Energy(_value / 3600d, EnergyUnit.WattHour), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Energy ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not EnergyUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EnergyUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(EnergyUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(EnergyUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1546,7 +1306,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/EnergyDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/EnergyDensity.g.cs index fa89880d5e..6c6b74a033 100644 --- a/UnitsNet/GeneratedCode/Quantities/EnergyDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/EnergyDensity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct EnergyDensity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly EnergyDensityUnit? _unit; /// @@ -104,7 +103,7 @@ public static EnergyDensityInfo CreateDefault(Func - /// The for is [T^-2][L^-1][M]. + /// The for is T^-2L^-1M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 1, -2, 0, 0, 0, 0); @@ -119,26 +118,46 @@ public static EnergyDensityInfo CreateDefault(FuncAn of representing the default unit mappings for EnergyDensity. public static IEnumerable> GetDefaultMappings() { - yield return new (EnergyDensityUnit.GigajoulePerCubicMeter, "GigajoulePerCubicMeter", "GigajoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Nanometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (EnergyDensityUnit.GigawattHourPerCubicMeter, "GigawattHourPerCubicMeter", "GigawattHoursPerCubicMeter", BaseUnits.Undefined); + yield return new (EnergyDensityUnit.GigajoulePerCubicMeter, "GigajoulePerCubicMeter", "GigajoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Nanometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000000) + ); + yield return new (EnergyDensityUnit.GigawattHourPerCubicMeter, "GigawattHourPerCubicMeter", "GigawattHoursPerCubicMeter", BaseUnits.Undefined, + new QuantityValue(1, 3600000000000) + ); yield return new (EnergyDensityUnit.JoulePerCubicMeter, "JoulePerCubicMeter", "JoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (EnergyDensityUnit.KilojoulePerCubicMeter, "KilojoulePerCubicMeter", "KilojoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (EnergyDensityUnit.KilowattHourPerCubicMeter, "KilowattHourPerCubicMeter", "KilowattHoursPerCubicMeter", BaseUnits.Undefined); - yield return new (EnergyDensityUnit.MegajoulePerCubicMeter, "MegajoulePerCubicMeter", "MegajoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (EnergyDensityUnit.MegawattHourPerCubicMeter, "MegawattHourPerCubicMeter", "MegawattHoursPerCubicMeter", BaseUnits.Undefined); - yield return new (EnergyDensityUnit.PetajoulePerCubicMeter, "PetajoulePerCubicMeter", "PetajoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Femtometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (EnergyDensityUnit.PetawattHourPerCubicMeter, "PetawattHourPerCubicMeter", "PetawattHoursPerCubicMeter", BaseUnits.Undefined); - yield return new (EnergyDensityUnit.TerajoulePerCubicMeter, "TerajoulePerCubicMeter", "TerajoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Picometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (EnergyDensityUnit.TerawattHourPerCubicMeter, "TerawattHourPerCubicMeter", "TerawattHoursPerCubicMeter", BaseUnits.Undefined); - yield return new (EnergyDensityUnit.WattHourPerCubicMeter, "WattHourPerCubicMeter", "WattHoursPerCubicMeter", BaseUnits.Undefined); + yield return new (EnergyDensityUnit.KilojoulePerCubicMeter, "KilojoulePerCubicMeter", "KilojoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000) + ); + yield return new (EnergyDensityUnit.KilowattHourPerCubicMeter, "KilowattHourPerCubicMeter", "KilowattHoursPerCubicMeter", BaseUnits.Undefined, + new QuantityValue(1, 3600000) + ); + yield return new (EnergyDensityUnit.MegajoulePerCubicMeter, "MegajoulePerCubicMeter", "MegajoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (EnergyDensityUnit.MegawattHourPerCubicMeter, "MegawattHourPerCubicMeter", "MegawattHoursPerCubicMeter", BaseUnits.Undefined, + new QuantityValue(1, 3600000000) + ); + yield return new (EnergyDensityUnit.PetajoulePerCubicMeter, "PetajoulePerCubicMeter", "PetajoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Femtometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000000000000) + ); + yield return new (EnergyDensityUnit.PetawattHourPerCubicMeter, "PetawattHourPerCubicMeter", "PetawattHoursPerCubicMeter", BaseUnits.Undefined, + new QuantityValue(1, 3600000000000000000) + ); + yield return new (EnergyDensityUnit.TerajoulePerCubicMeter, "TerajoulePerCubicMeter", "TerajoulesPerCubicMeter", new BaseUnits(length: LengthUnit.Picometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000000000) + ); + yield return new (EnergyDensityUnit.TerawattHourPerCubicMeter, "TerawattHourPerCubicMeter", "TerawattHoursPerCubicMeter", BaseUnits.Undefined, + new QuantityValue(1, 3600000000000000) + ); + yield return new (EnergyDensityUnit.WattHourPerCubicMeter, "WattHourPerCubicMeter", "WattHoursPerCubicMeter", BaseUnits.Undefined, + new QuantityValue(1, 3600) + ); } } static EnergyDensity() { - Info = EnergyDensityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(EnergyDensityInfo.CreateDefault); } /// @@ -146,7 +165,7 @@ static EnergyDensity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public EnergyDensity(double value, EnergyDensityUnit unit) + public EnergyDensity(QuantityValue value, EnergyDensityUnit unit) { _value = value; _unit = unit; @@ -160,7 +179,7 @@ public EnergyDensity(double value, EnergyDensityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public EnergyDensity(double value, UnitSystem unitSystem) + public EnergyDensity(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -171,7 +190,8 @@ public EnergyDensity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -200,10 +220,8 @@ public EnergyDensity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public EnergyDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -242,105 +260,69 @@ public EnergyDensity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigajoulesPerCubicMeter => As(EnergyDensityUnit.GigajoulePerCubicMeter); + public QuantityValue GigajoulesPerCubicMeter => this.As(EnergyDensityUnit.GigajoulePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigawattHoursPerCubicMeter => As(EnergyDensityUnit.GigawattHourPerCubicMeter); + public QuantityValue GigawattHoursPerCubicMeter => this.As(EnergyDensityUnit.GigawattHourPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double JoulesPerCubicMeter => As(EnergyDensityUnit.JoulePerCubicMeter); + public QuantityValue JoulesPerCubicMeter => this.As(EnergyDensityUnit.JoulePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilojoulesPerCubicMeter => As(EnergyDensityUnit.KilojoulePerCubicMeter); + public QuantityValue KilojoulesPerCubicMeter => this.As(EnergyDensityUnit.KilojoulePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattHoursPerCubicMeter => As(EnergyDensityUnit.KilowattHourPerCubicMeter); + public QuantityValue KilowattHoursPerCubicMeter => this.As(EnergyDensityUnit.KilowattHourPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegajoulesPerCubicMeter => As(EnergyDensityUnit.MegajoulePerCubicMeter); + public QuantityValue MegajoulesPerCubicMeter => this.As(EnergyDensityUnit.MegajoulePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattHoursPerCubicMeter => As(EnergyDensityUnit.MegawattHourPerCubicMeter); + public QuantityValue MegawattHoursPerCubicMeter => this.As(EnergyDensityUnit.MegawattHourPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PetajoulesPerCubicMeter => As(EnergyDensityUnit.PetajoulePerCubicMeter); + public QuantityValue PetajoulesPerCubicMeter => this.As(EnergyDensityUnit.PetajoulePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PetawattHoursPerCubicMeter => As(EnergyDensityUnit.PetawattHourPerCubicMeter); + public QuantityValue PetawattHoursPerCubicMeter => this.As(EnergyDensityUnit.PetawattHourPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TerajoulesPerCubicMeter => As(EnergyDensityUnit.TerajoulePerCubicMeter); + public QuantityValue TerajoulesPerCubicMeter => this.As(EnergyDensityUnit.TerajoulePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TerawattHoursPerCubicMeter => As(EnergyDensityUnit.TerawattHourPerCubicMeter); + public QuantityValue TerawattHoursPerCubicMeter => this.As(EnergyDensityUnit.TerawattHourPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattHoursPerCubicMeter => As(EnergyDensityUnit.WattHourPerCubicMeter); + public QuantityValue WattHoursPerCubicMeter => this.As(EnergyDensityUnit.WattHourPerCubicMeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: EnergyDensityUnit -> BaseUnit - unitConverter.SetConversionFunction(EnergyDensityUnit.GigajoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.GigawattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.KilojoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.KilowattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.MegajoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.MegawattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.PetajoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.PetawattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.TerajoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.TerawattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.WattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.JoulePerCubicMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> EnergyDensityUnit - unitConverter.SetConversionFunction(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.GigajoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.GigajoulePerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.GigawattHourPerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.GigawattHourPerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.KilojoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.KilojoulePerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.KilowattHourPerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.KilowattHourPerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.MegajoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.MegajoulePerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.MegawattHourPerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.MegawattHourPerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.PetajoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.PetajoulePerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.PetawattHourPerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.PetawattHourPerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.TerajoulePerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.TerajoulePerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.TerawattHourPerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.TerawattHourPerCubicMeter)); - unitConverter.SetConversionFunction(EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.WattHourPerCubicMeter, quantity => quantity.ToUnit(EnergyDensityUnit.WattHourPerCubicMeter)); - } - /// /// Get unit abbreviation string. /// @@ -369,7 +351,7 @@ public static string GetAbbreviation(EnergyDensityUnit unit, IFormatProvider? pr /// /// Creates a from . /// - public static EnergyDensity FromGigajoulesPerCubicMeter(double value) + public static EnergyDensity FromGigajoulesPerCubicMeter(QuantityValue value) { return new EnergyDensity(value, EnergyDensityUnit.GigajoulePerCubicMeter); } @@ -377,7 +359,7 @@ public static EnergyDensity FromGigajoulesPerCubicMeter(double value) /// /// Creates a from . /// - public static EnergyDensity FromGigawattHoursPerCubicMeter(double value) + public static EnergyDensity FromGigawattHoursPerCubicMeter(QuantityValue value) { return new EnergyDensity(value, EnergyDensityUnit.GigawattHourPerCubicMeter); } @@ -385,7 +367,7 @@ public static EnergyDensity FromGigawattHoursPerCubicMeter(double value) /// /// Creates a from . /// - public static EnergyDensity FromJoulesPerCubicMeter(double value) + public static EnergyDensity FromJoulesPerCubicMeter(QuantityValue value) { return new EnergyDensity(value, EnergyDensityUnit.JoulePerCubicMeter); } @@ -393,7 +375,7 @@ public static EnergyDensity FromJoulesPerCubicMeter(double value) /// /// Creates a from . /// - public static EnergyDensity FromKilojoulesPerCubicMeter(double value) + public static EnergyDensity FromKilojoulesPerCubicMeter(QuantityValue value) { return new EnergyDensity(value, EnergyDensityUnit.KilojoulePerCubicMeter); } @@ -401,7 +383,7 @@ public static EnergyDensity FromKilojoulesPerCubicMeter(double value) /// /// Creates a from . /// - public static EnergyDensity FromKilowattHoursPerCubicMeter(double value) + public static EnergyDensity FromKilowattHoursPerCubicMeter(QuantityValue value) { return new EnergyDensity(value, EnergyDensityUnit.KilowattHourPerCubicMeter); } @@ -409,7 +391,7 @@ public static EnergyDensity FromKilowattHoursPerCubicMeter(double value) /// /// Creates a from . /// - public static EnergyDensity FromMegajoulesPerCubicMeter(double value) + public static EnergyDensity FromMegajoulesPerCubicMeter(QuantityValue value) { return new EnergyDensity(value, EnergyDensityUnit.MegajoulePerCubicMeter); } @@ -417,7 +399,7 @@ public static EnergyDensity FromMegajoulesPerCubicMeter(double value) /// /// Creates a from . /// - public static EnergyDensity FromMegawattHoursPerCubicMeter(double value) + public static EnergyDensity FromMegawattHoursPerCubicMeter(QuantityValue value) { return new EnergyDensity(value, EnergyDensityUnit.MegawattHourPerCubicMeter); } @@ -425,7 +407,7 @@ public static EnergyDensity FromMegawattHoursPerCubicMeter(double value) /// /// Creates a from . /// - public static EnergyDensity FromPetajoulesPerCubicMeter(double value) + public static EnergyDensity FromPetajoulesPerCubicMeter(QuantityValue value) { return new EnergyDensity(value, EnergyDensityUnit.PetajoulePerCubicMeter); } @@ -433,7 +415,7 @@ public static EnergyDensity FromPetajoulesPerCubicMeter(double value) /// /// Creates a from . /// - public static EnergyDensity FromPetawattHoursPerCubicMeter(double value) + public static EnergyDensity FromPetawattHoursPerCubicMeter(QuantityValue value) { return new EnergyDensity(value, EnergyDensityUnit.PetawattHourPerCubicMeter); } @@ -441,7 +423,7 @@ public static EnergyDensity FromPetawattHoursPerCubicMeter(double value) /// /// Creates a from . /// - public static EnergyDensity FromTerajoulesPerCubicMeter(double value) + public static EnergyDensity FromTerajoulesPerCubicMeter(QuantityValue value) { return new EnergyDensity(value, EnergyDensityUnit.TerajoulePerCubicMeter); } @@ -449,7 +431,7 @@ public static EnergyDensity FromTerajoulesPerCubicMeter(double value) /// /// Creates a from . /// - public static EnergyDensity FromTerawattHoursPerCubicMeter(double value) + public static EnergyDensity FromTerawattHoursPerCubicMeter(QuantityValue value) { return new EnergyDensity(value, EnergyDensityUnit.TerawattHourPerCubicMeter); } @@ -457,7 +439,7 @@ public static EnergyDensity FromTerawattHoursPerCubicMeter(double value) /// /// Creates a from . /// - public static EnergyDensity FromWattHoursPerCubicMeter(double value) + public static EnergyDensity FromWattHoursPerCubicMeter(QuantityValue value) { return new EnergyDensity(value, EnergyDensityUnit.WattHourPerCubicMeter); } @@ -468,7 +450,7 @@ public static EnergyDensity FromWattHoursPerCubicMeter(double value) /// Value to convert from. /// Unit to convert from. /// EnergyDensity unit value. - public static EnergyDensity From(double value, EnergyDensityUnit fromUnit) + public static EnergyDensity From(QuantityValue value, EnergyDensityUnit fromUnit) { return new EnergyDensity(value, fromUnit); } @@ -529,10 +511,7 @@ public static EnergyDensity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static EnergyDensity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -560,11 +539,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out EnergyDensity re /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out EnergyDensity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -585,7 +560,7 @@ public static EnergyDensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -596,7 +571,7 @@ public static EnergyDensityUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out EnergyDensityUnit unit) { return TryParseUnit(str, null, out unit); @@ -611,7 +586,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out EnergyDensit /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out EnergyDensityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -630,35 +605,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static EnergyDensity operator +(EnergyDensity left, EnergyDensity right) { - return new EnergyDensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new EnergyDensity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static EnergyDensity operator -(EnergyDensity left, EnergyDensity right) { - return new EnergyDensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new EnergyDensity(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static EnergyDensity operator *(double left, EnergyDensity right) + public static EnergyDensity operator *(QuantityValue left, EnergyDensity right) { return new EnergyDensity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static EnergyDensity operator *(EnergyDensity left, double right) + public static EnergyDensity operator *(EnergyDensity left, QuantityValue right) { return new EnergyDensity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static EnergyDensity operator /(EnergyDensity left, double right) + public static EnergyDensity operator /(EnergyDensity left, QuantityValue right) { return new EnergyDensity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(EnergyDensity left, EnergyDensity right) + public static QuantityValue operator /(EnergyDensity left, EnergyDensity right) { return left.JoulesPerCubicMeter / right.JoulesPerCubicMeter; } @@ -680,97 +655,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(EnergyDensity left, EnergyDensity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(EnergyDensity left, EnergyDensity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(EnergyDensity left, EnergyDensity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(EnergyDensity left, EnergyDensity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(EnergyDensity other, EnergyDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(EnergyDensity left, EnergyDensity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(EnergyDensity other, EnergyDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(EnergyDensity left, EnergyDensity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(EnergyDensity other, EnergyDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is EnergyDensity otherQuantity)) + if (obj is not EnergyDensity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(EnergyDensity other, EnergyDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(EnergyDensity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current EnergyDensity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(EnergyDensity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is EnergyDensity otherQuantity)) throw new ArgumentException("Expected type EnergyDensity.", nameof(obj)); + if (obj is not EnergyDensity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -782,168 +742,24 @@ public int CompareTo(object? obj) /// public int CompareTo(EnergyDensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(EnergyDensityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this EnergyDensity to another EnergyDensity with the unit representation . - /// - /// The unit to convert to. - /// A EnergyDensity with the specified unit. - public EnergyDensity ToUnit(EnergyDensityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A EnergyDensity with the specified unit. - public EnergyDensity ToUnit(EnergyDensityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(EnergyDensity), Unit, typeof(EnergyDensity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (EnergyDensity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(EnergyDensityUnit unit, [NotNullWhen(true)] out EnergyDensity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - EnergyDensity? convertedOrNull = (Unit, unit) switch - { - // EnergyDensityUnit -> BaseUnit - (EnergyDensityUnit.GigajoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value) * 1e9d, EnergyDensityUnit.JoulePerCubicMeter), - (EnergyDensityUnit.GigawattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value * 3.6e+3) * 1e9d, EnergyDensityUnit.JoulePerCubicMeter), - (EnergyDensityUnit.KilojoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value) * 1e3d, EnergyDensityUnit.JoulePerCubicMeter), - (EnergyDensityUnit.KilowattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value * 3.6e+3) * 1e3d, EnergyDensityUnit.JoulePerCubicMeter), - (EnergyDensityUnit.MegajoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value) * 1e6d, EnergyDensityUnit.JoulePerCubicMeter), - (EnergyDensityUnit.MegawattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value * 3.6e+3) * 1e6d, EnergyDensityUnit.JoulePerCubicMeter), - (EnergyDensityUnit.PetajoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value) * 1e15d, EnergyDensityUnit.JoulePerCubicMeter), - (EnergyDensityUnit.PetawattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value * 3.6e+3) * 1e15d, EnergyDensityUnit.JoulePerCubicMeter), - (EnergyDensityUnit.TerajoulePerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value) * 1e12d, EnergyDensityUnit.JoulePerCubicMeter), - (EnergyDensityUnit.TerawattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity((_value * 3.6e+3) * 1e12d, EnergyDensityUnit.JoulePerCubicMeter), - (EnergyDensityUnit.WattHourPerCubicMeter, EnergyDensityUnit.JoulePerCubicMeter) => new EnergyDensity(_value * 3.6e+3, EnergyDensityUnit.JoulePerCubicMeter), - - // BaseUnit -> EnergyDensityUnit - (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.GigajoulePerCubicMeter) => new EnergyDensity((_value) / 1e9d, EnergyDensityUnit.GigajoulePerCubicMeter), - (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.GigawattHourPerCubicMeter) => new EnergyDensity((_value / 3.6e+3) / 1e9d, EnergyDensityUnit.GigawattHourPerCubicMeter), - (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.KilojoulePerCubicMeter) => new EnergyDensity((_value) / 1e3d, EnergyDensityUnit.KilojoulePerCubicMeter), - (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.KilowattHourPerCubicMeter) => new EnergyDensity((_value / 3.6e+3) / 1e3d, EnergyDensityUnit.KilowattHourPerCubicMeter), - (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.MegajoulePerCubicMeter) => new EnergyDensity((_value) / 1e6d, EnergyDensityUnit.MegajoulePerCubicMeter), - (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.MegawattHourPerCubicMeter) => new EnergyDensity((_value / 3.6e+3) / 1e6d, EnergyDensityUnit.MegawattHourPerCubicMeter), - (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.PetajoulePerCubicMeter) => new EnergyDensity((_value) / 1e15d, EnergyDensityUnit.PetajoulePerCubicMeter), - (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.PetawattHourPerCubicMeter) => new EnergyDensity((_value / 3.6e+3) / 1e15d, EnergyDensityUnit.PetawattHourPerCubicMeter), - (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.TerajoulePerCubicMeter) => new EnergyDensity((_value) / 1e12d, EnergyDensityUnit.TerajoulePerCubicMeter), - (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.TerawattHourPerCubicMeter) => new EnergyDensity((_value / 3.6e+3) / 1e12d, EnergyDensityUnit.TerawattHourPerCubicMeter), - (EnergyDensityUnit.JoulePerCubicMeter, EnergyDensityUnit.WattHourPerCubicMeter) => new EnergyDensity(_value / 3.6e+3, EnergyDensityUnit.WattHourPerCubicMeter), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public EnergyDensity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not EnergyDensityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EnergyDensityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is EnergyDensityUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EnergyDensityUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(EnergyDensityUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(EnergyDensityUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -958,7 +774,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs b/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs index 9d856cac66..82c4c5c1e7 100644 --- a/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Entropy.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Entropy : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -55,13 +54,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly EntropyUnit? _unit; /// @@ -106,7 +105,7 @@ public static EntropyInfo CreateDefault(Func - /// The for is [T^-2][L^2][M][Θ^-1]. + /// The for is T^-2L^2MΘ^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, 0, -1, 0, 0); @@ -121,21 +120,31 @@ public static EntropyInfo CreateDefault(FuncAn of representing the default unit mappings for Entropy. public static IEnumerable> GetDefaultMappings() { - yield return new (EntropyUnit.CaloriePerKelvin, "CaloriePerKelvin", "CaloriesPerKelvin", BaseUnits.Undefined); - yield return new (EntropyUnit.JoulePerDegreeCelsius, "JoulePerDegreeCelsius", "JoulesPerDegreeCelsius", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius)); + yield return new (EntropyUnit.CaloriePerKelvin, "CaloriePerKelvin", "CaloriesPerKelvin", BaseUnits.Undefined, + new QuantityValue(125, 523) + ); + yield return new (EntropyUnit.JoulePerDegreeCelsius, "JoulePerDegreeCelsius", "JoulesPerDegreeCelsius", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), + 1 + ); yield return new (EntropyUnit.JoulePerKelvin, "JoulePerKelvin", "JoulesPerKelvin", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin)); - yield return new (EntropyUnit.KilocaloriePerKelvin, "KilocaloriePerKelvin", "KilocaloriesPerKelvin", BaseUnits.Undefined); - yield return new (EntropyUnit.KilojoulePerDegreeCelsius, "KilojoulePerDegreeCelsius", "KilojoulesPerDegreeCelsius", BaseUnits.Undefined); - yield return new (EntropyUnit.KilojoulePerKelvin, "KilojoulePerKelvin", "KilojoulesPerKelvin", BaseUnits.Undefined); - yield return new (EntropyUnit.MegajoulePerKelvin, "MegajoulePerKelvin", "MegajoulesPerKelvin", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin)); + yield return new (EntropyUnit.KilocaloriePerKelvin, "KilocaloriePerKelvin", "KilocaloriesPerKelvin", BaseUnits.Undefined, + new QuantityValue(1, 4184) + ); + yield return new (EntropyUnit.KilojoulePerDegreeCelsius, "KilojoulePerDegreeCelsius", "KilojoulesPerDegreeCelsius", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (EntropyUnit.KilojoulePerKelvin, "KilojoulePerKelvin", "KilojoulesPerKelvin", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (EntropyUnit.MegajoulePerKelvin, "MegajoulePerKelvin", "MegajoulesPerKelvin", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin), + new QuantityValue(1, 1000000) + ); } } static Entropy() { - Info = EntropyInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(EntropyInfo.CreateDefault); } /// @@ -143,7 +152,7 @@ static Entropy() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Entropy(double value, EntropyUnit unit) + public Entropy(QuantityValue value, EntropyUnit unit) { _value = value; _unit = unit; @@ -157,7 +166,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -168,7 +177,8 @@ public Entropy(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -197,10 +207,8 @@ public Entropy(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public EntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -239,70 +247,44 @@ public Entropy(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CaloriesPerKelvin => As(EntropyUnit.CaloriePerKelvin); + public QuantityValue CaloriesPerKelvin => this.As(EntropyUnit.CaloriePerKelvin); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double JoulesPerDegreeCelsius => As(EntropyUnit.JoulePerDegreeCelsius); + public QuantityValue JoulesPerDegreeCelsius => this.As(EntropyUnit.JoulePerDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double JoulesPerKelvin => As(EntropyUnit.JoulePerKelvin); + public QuantityValue JoulesPerKelvin => this.As(EntropyUnit.JoulePerKelvin); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilocaloriesPerKelvin => As(EntropyUnit.KilocaloriePerKelvin); + public QuantityValue KilocaloriesPerKelvin => this.As(EntropyUnit.KilocaloriePerKelvin); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilojoulesPerDegreeCelsius => As(EntropyUnit.KilojoulePerDegreeCelsius); + public QuantityValue KilojoulesPerDegreeCelsius => this.As(EntropyUnit.KilojoulePerDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilojoulesPerKelvin => As(EntropyUnit.KilojoulePerKelvin); + public QuantityValue KilojoulesPerKelvin => this.As(EntropyUnit.KilojoulePerKelvin); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegajoulesPerKelvin => As(EntropyUnit.MegajoulePerKelvin); + public QuantityValue MegajoulesPerKelvin => this.As(EntropyUnit.MegajoulePerKelvin); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: EntropyUnit -> BaseUnit - unitConverter.SetConversionFunction(EntropyUnit.CaloriePerKelvin, EntropyUnit.JoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.JoulePerKelvin)); - unitConverter.SetConversionFunction(EntropyUnit.JoulePerDegreeCelsius, EntropyUnit.JoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.JoulePerKelvin)); - unitConverter.SetConversionFunction(EntropyUnit.KilocaloriePerKelvin, EntropyUnit.JoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.JoulePerKelvin)); - unitConverter.SetConversionFunction(EntropyUnit.KilojoulePerDegreeCelsius, EntropyUnit.JoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.JoulePerKelvin)); - unitConverter.SetConversionFunction(EntropyUnit.KilojoulePerKelvin, EntropyUnit.JoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.JoulePerKelvin)); - unitConverter.SetConversionFunction(EntropyUnit.MegajoulePerKelvin, EntropyUnit.JoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.JoulePerKelvin)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.JoulePerKelvin, quantity => quantity); - - // Register in unit converter: BaseUnit -> EntropyUnit - unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.CaloriePerKelvin, quantity => quantity.ToUnit(EntropyUnit.CaloriePerKelvin)); - unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.JoulePerDegreeCelsius, quantity => quantity.ToUnit(EntropyUnit.JoulePerDegreeCelsius)); - unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.KilocaloriePerKelvin, quantity => quantity.ToUnit(EntropyUnit.KilocaloriePerKelvin)); - unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.KilojoulePerDegreeCelsius, quantity => quantity.ToUnit(EntropyUnit.KilojoulePerDegreeCelsius)); - unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.KilojoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.KilojoulePerKelvin)); - unitConverter.SetConversionFunction(EntropyUnit.JoulePerKelvin, EntropyUnit.MegajoulePerKelvin, quantity => quantity.ToUnit(EntropyUnit.MegajoulePerKelvin)); - } - /// /// Get unit abbreviation string. /// @@ -331,7 +313,7 @@ public static string GetAbbreviation(EntropyUnit unit, IFormatProvider? provider /// /// Creates a from . /// - public static Entropy FromCaloriesPerKelvin(double value) + public static Entropy FromCaloriesPerKelvin(QuantityValue value) { return new Entropy(value, EntropyUnit.CaloriePerKelvin); } @@ -339,7 +321,7 @@ public static Entropy FromCaloriesPerKelvin(double value) /// /// Creates a from . /// - public static Entropy FromJoulesPerDegreeCelsius(double value) + public static Entropy FromJoulesPerDegreeCelsius(QuantityValue value) { return new Entropy(value, EntropyUnit.JoulePerDegreeCelsius); } @@ -347,7 +329,7 @@ public static Entropy FromJoulesPerDegreeCelsius(double value) /// /// Creates a from . /// - public static Entropy FromJoulesPerKelvin(double value) + public static Entropy FromJoulesPerKelvin(QuantityValue value) { return new Entropy(value, EntropyUnit.JoulePerKelvin); } @@ -355,7 +337,7 @@ public static Entropy FromJoulesPerKelvin(double value) /// /// Creates a from . /// - public static Entropy FromKilocaloriesPerKelvin(double value) + public static Entropy FromKilocaloriesPerKelvin(QuantityValue value) { return new Entropy(value, EntropyUnit.KilocaloriePerKelvin); } @@ -363,7 +345,7 @@ public static Entropy FromKilocaloriesPerKelvin(double value) /// /// Creates a from . /// - public static Entropy FromKilojoulesPerDegreeCelsius(double value) + public static Entropy FromKilojoulesPerDegreeCelsius(QuantityValue value) { return new Entropy(value, EntropyUnit.KilojoulePerDegreeCelsius); } @@ -371,7 +353,7 @@ public static Entropy FromKilojoulesPerDegreeCelsius(double value) /// /// Creates a from . /// - public static Entropy FromKilojoulesPerKelvin(double value) + public static Entropy FromKilojoulesPerKelvin(QuantityValue value) { return new Entropy(value, EntropyUnit.KilojoulePerKelvin); } @@ -379,7 +361,7 @@ public static Entropy FromKilojoulesPerKelvin(double value) /// /// Creates a from . /// - public static Entropy FromMegajoulesPerKelvin(double value) + public static Entropy FromMegajoulesPerKelvin(QuantityValue value) { return new Entropy(value, EntropyUnit.MegajoulePerKelvin); } @@ -390,7 +372,7 @@ public static Entropy FromMegajoulesPerKelvin(double value) /// Value to convert from. /// Unit to convert from. /// Entropy unit value. - public static Entropy From(double value, EntropyUnit fromUnit) + public static Entropy From(QuantityValue value, EntropyUnit fromUnit) { return new Entropy(value, fromUnit); } @@ -451,10 +433,7 @@ public static Entropy Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Entropy Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -482,11 +461,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Entropy result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Entropy result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -507,7 +482,7 @@ public static EntropyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -518,7 +493,7 @@ public static EntropyUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out EntropyUnit unit) { return TryParseUnit(str, null, out unit); @@ -533,7 +508,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out EntropyUnit /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out EntropyUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -552,35 +527,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Entropy operator +(Entropy left, Entropy right) { - return new Entropy(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Entropy(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Entropy operator -(Entropy left, Entropy right) { - return new Entropy(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Entropy(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -614,97 +589,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Entropy left, Entropy right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Entropy left, Entropy right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Entropy left, Entropy right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Entropy left, Entropy right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Entropy other, Entropy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Entropy left, Entropy right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Entropy other, Entropy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Entropy left, Entropy right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Entropy other, Entropy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Entropy otherQuantity)) + if (obj is not Entropy otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Entropy other, Entropy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Entropy other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Entropy. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Entropy), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Entropy otherQuantity)) throw new ArgumentException("Expected type Entropy.", nameof(obj)); + if (obj is not Entropy otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -716,158 +676,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Entropy other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(EntropyUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Entropy to another Entropy with the unit representation . - /// - /// The unit to convert to. - /// A Entropy with the specified unit. - public Entropy ToUnit(EntropyUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Entropy with the specified unit. - public Entropy ToUnit(EntropyUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Entropy), Unit, typeof(Entropy), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Entropy)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(EntropyUnit unit, [NotNullWhen(true)] out Entropy? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Entropy? convertedOrNull = (Unit, unit) switch - { - // EntropyUnit -> BaseUnit - (EntropyUnit.CaloriePerKelvin, EntropyUnit.JoulePerKelvin) => new Entropy(_value * 4.184, EntropyUnit.JoulePerKelvin), - (EntropyUnit.JoulePerDegreeCelsius, EntropyUnit.JoulePerKelvin) => new Entropy(_value, EntropyUnit.JoulePerKelvin), - (EntropyUnit.KilocaloriePerKelvin, EntropyUnit.JoulePerKelvin) => new Entropy((_value * 4.184) * 1e3d, EntropyUnit.JoulePerKelvin), - (EntropyUnit.KilojoulePerDegreeCelsius, EntropyUnit.JoulePerKelvin) => new Entropy((_value) * 1e3d, EntropyUnit.JoulePerKelvin), - (EntropyUnit.KilojoulePerKelvin, EntropyUnit.JoulePerKelvin) => new Entropy((_value) * 1e3d, EntropyUnit.JoulePerKelvin), - (EntropyUnit.MegajoulePerKelvin, EntropyUnit.JoulePerKelvin) => new Entropy((_value) * 1e6d, EntropyUnit.JoulePerKelvin), - - // BaseUnit -> EntropyUnit - (EntropyUnit.JoulePerKelvin, EntropyUnit.CaloriePerKelvin) => new Entropy(_value / 4.184, EntropyUnit.CaloriePerKelvin), - (EntropyUnit.JoulePerKelvin, EntropyUnit.JoulePerDegreeCelsius) => new Entropy(_value, EntropyUnit.JoulePerDegreeCelsius), - (EntropyUnit.JoulePerKelvin, EntropyUnit.KilocaloriePerKelvin) => new Entropy((_value / 4.184) / 1e3d, EntropyUnit.KilocaloriePerKelvin), - (EntropyUnit.JoulePerKelvin, EntropyUnit.KilojoulePerDegreeCelsius) => new Entropy((_value) / 1e3d, EntropyUnit.KilojoulePerDegreeCelsius), - (EntropyUnit.JoulePerKelvin, EntropyUnit.KilojoulePerKelvin) => new Entropy((_value) / 1e3d, EntropyUnit.KilojoulePerKelvin), - (EntropyUnit.JoulePerKelvin, EntropyUnit.MegajoulePerKelvin) => new Entropy((_value) / 1e6d, EntropyUnit.MegajoulePerKelvin), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Entropy ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not EntropyUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(EntropyUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(EntropyUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(EntropyUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -882,7 +708,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/FluidResistance.g.cs b/UnitsNet/GeneratedCode/Quantities/FluidResistance.g.cs index 636f440c35..132b871423 100644 --- a/UnitsNet/GeneratedCode/Quantities/FluidResistance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/FluidResistance.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Friction#Fluid /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct FluidResistance : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly FluidResistanceUnit? _unit; /// @@ -104,7 +103,7 @@ public static FluidResistanceInfo CreateDefault(Func - /// The for is [T^-1][L^-4][M]. + /// The for is T^-1L^-4M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-4, 1, -1, 0, 0, 0, 0); @@ -119,33 +118,67 @@ public static FluidResistanceInfo CreateDefault(FuncAn of representing the default unit mappings for FluidResistance. public static IEnumerable> GetDefaultMappings() { - yield return new (FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, "DyneSecondPerCentimeterToTheFifth", "DyneSecondsPerCentimeterToTheFifth", BaseUnits.Undefined); - yield return new (FluidResistanceUnit.MegapascalSecondPerCubicMeter, "MegapascalSecondPerCubicMeter", "MegapascalSecondsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Microsecond)); - yield return new (FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter, "MillimeterMercuryMinutePerCubicCentimeter", "MillimeterMercuryMinutesPerCubicCentimeter", BaseUnits.Undefined); - yield return new (FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter, "MillimeterMercuryMinutePerCubicMeter", "MillimeterMercuryMinutesPerCubicMeter", BaseUnits.Undefined); - yield return new (FluidResistanceUnit.MillimeterMercuryMinutePerLiter, "MillimeterMercuryMinutePerLiter", "MillimeterMercuryMinutesPerLiter", BaseUnits.Undefined); - yield return new (FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter, "MillimeterMercuryMinutePerMilliliter", "MillimeterMercuryMinutesPerMilliliter", BaseUnits.Undefined); - yield return new (FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter, "MillimeterMercurySecondPerCubicCentimeter", "MillimeterMercurySecondsPerCubicCentimeter", BaseUnits.Undefined); - yield return new (FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter, "MillimeterMercurySecondPerCubicMeter", "MillimeterMercurySecondsPerCubicMeter", BaseUnits.Undefined); - yield return new (FluidResistanceUnit.MillimeterMercurySecondPerLiter, "MillimeterMercurySecondPerLiter", "MillimeterMercurySecondsPerLiter", BaseUnits.Undefined); - yield return new (FluidResistanceUnit.MillimeterMercurySecondPerMilliliter, "MillimeterMercurySecondPerMilliliter", "MillimeterMercurySecondsPerMilliliter", BaseUnits.Undefined); - yield return new (FluidResistanceUnit.PascalMinutePerCubicCentimeter, "PascalMinutePerCubicCentimeter", "PascalMinutesPerCubicCentimeter", BaseUnits.Undefined); - yield return new (FluidResistanceUnit.PascalMinutePerCubicMeter, "PascalMinutePerCubicMeter", "PascalMinutesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute)); - yield return new (FluidResistanceUnit.PascalMinutePerLiter, "PascalMinutePerLiter", "PascalMinutesPerLiter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute)); - yield return new (FluidResistanceUnit.PascalMinutePerMilliliter, "PascalMinutePerMilliliter", "PascalMinutesPerMilliliter", BaseUnits.Undefined); - yield return new (FluidResistanceUnit.PascalSecondPerCubicCentimeter, "PascalSecondPerCubicCentimeter", "PascalSecondsPerCubicCentimeter", BaseUnits.Undefined); + yield return new (FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, "DyneSecondPerCentimeterToTheFifth", "DyneSecondsPerCentimeterToTheFifth", BaseUnits.Undefined, + new QuantityValue(1, 100000) + ); + yield return new (FluidResistanceUnit.MegapascalSecondPerCubicMeter, "MegapascalSecondPerCubicMeter", "MegapascalSecondsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Microsecond), + new QuantityValue(1, 1000000) + ); + yield return new (FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter, "MillimeterMercuryMinutePerCubicCentimeter", "MillimeterMercuryMinutesPerCubicCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 7999342080) + ); + yield return new (FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter, "MillimeterMercuryMinutePerCubicMeter", "MillimeterMercuryMinutesPerCubicMeter", BaseUnits.Undefined, + new QuantityValue(3125, 24997944) + ); + yield return new (FluidResistanceUnit.MillimeterMercuryMinutePerLiter, "MillimeterMercuryMinutePerLiter", "MillimeterMercuryMinutesPerLiter", BaseUnits.Undefined, + new QuantityValue(25, 199983552) + ); + yield return new (FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter, "MillimeterMercuryMinutePerMilliliter", "MillimeterMercuryMinutesPerMilliliter", BaseUnits.Undefined, + new QuantityValue(1, 7999342080) + ); + yield return new (FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter, "MillimeterMercurySecondPerCubicCentimeter", "MillimeterMercurySecondsPerCubicCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 133322368) + ); + yield return new (FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter, "MillimeterMercurySecondPerCubicMeter", "MillimeterMercurySecondsPerCubicMeter", BaseUnits.Undefined, + new QuantityValue(15625, 2083162) + ); + yield return new (FluidResistanceUnit.MillimeterMercurySecondPerLiter, "MillimeterMercurySecondPerLiter", "MillimeterMercurySecondsPerLiter", BaseUnits.Undefined, + new QuantityValue(125, 16665296) + ); + yield return new (FluidResistanceUnit.MillimeterMercurySecondPerMilliliter, "MillimeterMercurySecondPerMilliliter", "MillimeterMercurySecondsPerMilliliter", BaseUnits.Undefined, + new QuantityValue(1, 133322368) + ); + yield return new (FluidResistanceUnit.PascalMinutePerCubicCentimeter, "PascalMinutePerCubicCentimeter", "PascalMinutesPerCubicCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 60000000) + ); + yield return new (FluidResistanceUnit.PascalMinutePerCubicMeter, "PascalMinutePerCubicMeter", "PascalMinutesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute), + new QuantityValue(1, 60) + ); + yield return new (FluidResistanceUnit.PascalMinutePerLiter, "PascalMinutePerLiter", "PascalMinutesPerLiter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute), + new QuantityValue(1, 60000) + ); + yield return new (FluidResistanceUnit.PascalMinutePerMilliliter, "PascalMinutePerMilliliter", "PascalMinutesPerMilliliter", BaseUnits.Undefined, + new QuantityValue(1, 60000000) + ); + yield return new (FluidResistanceUnit.PascalSecondPerCubicCentimeter, "PascalSecondPerCubicCentimeter", "PascalSecondsPerCubicCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 1000000) + ); yield return new (FluidResistanceUnit.PascalSecondPerCubicMeter, "PascalSecondPerCubicMeter", "PascalSecondsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (FluidResistanceUnit.PascalSecondPerLiter, "PascalSecondPerLiter", "PascalSecondsPerLiter", BaseUnits.Undefined); - yield return new (FluidResistanceUnit.PascalSecondPerMilliliter, "PascalSecondPerMilliliter", "PascalSecondsPerMilliliter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second)); - yield return new (FluidResistanceUnit.WoodUnit, "WoodUnit", "WoodUnits", BaseUnits.Undefined); + yield return new (FluidResistanceUnit.PascalSecondPerLiter, "PascalSecondPerLiter", "PascalSecondsPerLiter", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (FluidResistanceUnit.PascalSecondPerMilliliter, "PascalSecondPerMilliliter", "PascalSecondsPerMilliliter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (FluidResistanceUnit.WoodUnit, "WoodUnit", "WoodUnits", BaseUnits.Undefined, + new QuantityValue(25, 199983552) + ); } } static FluidResistance() { - Info = FluidResistanceInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(FluidResistanceInfo.CreateDefault); } /// @@ -153,7 +186,7 @@ static FluidResistance() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public FluidResistance(double value, FluidResistanceUnit unit) + public FluidResistance(QuantityValue value, FluidResistanceUnit unit) { _value = value; _unit = unit; @@ -167,7 +200,7 @@ public FluidResistance(double value, FluidResistanceUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public FluidResistance(double value, UnitSystem unitSystem) + public FluidResistance(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -178,7 +211,8 @@ public FluidResistance(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -207,10 +241,8 @@ public FluidResistance(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public FluidResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -249,154 +281,104 @@ public FluidResistance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DyneSecondsPerCentimeterToTheFifth => As(FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth); + public QuantityValue DyneSecondsPerCentimeterToTheFifth => this.As(FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegapascalSecondsPerCubicMeter => As(FluidResistanceUnit.MegapascalSecondPerCubicMeter); + public QuantityValue MegapascalSecondsPerCubicMeter => this.As(FluidResistanceUnit.MegapascalSecondPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimeterMercuryMinutesPerCubicCentimeter => As(FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter); + public QuantityValue MillimeterMercuryMinutesPerCubicCentimeter => this.As(FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimeterMercuryMinutesPerCubicMeter => As(FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter); + public QuantityValue MillimeterMercuryMinutesPerCubicMeter => this.As(FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimeterMercuryMinutesPerLiter => As(FluidResistanceUnit.MillimeterMercuryMinutePerLiter); + public QuantityValue MillimeterMercuryMinutesPerLiter => this.As(FluidResistanceUnit.MillimeterMercuryMinutePerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimeterMercuryMinutesPerMilliliter => As(FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter); + public QuantityValue MillimeterMercuryMinutesPerMilliliter => this.As(FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimeterMercurySecondsPerCubicCentimeter => As(FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter); + public QuantityValue MillimeterMercurySecondsPerCubicCentimeter => this.As(FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimeterMercurySecondsPerCubicMeter => As(FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter); + public QuantityValue MillimeterMercurySecondsPerCubicMeter => this.As(FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimeterMercurySecondsPerLiter => As(FluidResistanceUnit.MillimeterMercurySecondPerLiter); + public QuantityValue MillimeterMercurySecondsPerLiter => this.As(FluidResistanceUnit.MillimeterMercurySecondPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimeterMercurySecondsPerMilliliter => As(FluidResistanceUnit.MillimeterMercurySecondPerMilliliter); + public QuantityValue MillimeterMercurySecondsPerMilliliter => this.As(FluidResistanceUnit.MillimeterMercurySecondPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PascalMinutesPerCubicCentimeter => As(FluidResistanceUnit.PascalMinutePerCubicCentimeter); + public QuantityValue PascalMinutesPerCubicCentimeter => this.As(FluidResistanceUnit.PascalMinutePerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PascalMinutesPerCubicMeter => As(FluidResistanceUnit.PascalMinutePerCubicMeter); + public QuantityValue PascalMinutesPerCubicMeter => this.As(FluidResistanceUnit.PascalMinutePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PascalMinutesPerLiter => As(FluidResistanceUnit.PascalMinutePerLiter); + public QuantityValue PascalMinutesPerLiter => this.As(FluidResistanceUnit.PascalMinutePerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PascalMinutesPerMilliliter => As(FluidResistanceUnit.PascalMinutePerMilliliter); + public QuantityValue PascalMinutesPerMilliliter => this.As(FluidResistanceUnit.PascalMinutePerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PascalSecondsPerCubicCentimeter => As(FluidResistanceUnit.PascalSecondPerCubicCentimeter); + public QuantityValue PascalSecondsPerCubicCentimeter => this.As(FluidResistanceUnit.PascalSecondPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PascalSecondsPerCubicMeter => As(FluidResistanceUnit.PascalSecondPerCubicMeter); + public QuantityValue PascalSecondsPerCubicMeter => this.As(FluidResistanceUnit.PascalSecondPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PascalSecondsPerLiter => As(FluidResistanceUnit.PascalSecondPerLiter); + public QuantityValue PascalSecondsPerLiter => this.As(FluidResistanceUnit.PascalSecondPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PascalSecondsPerMilliliter => As(FluidResistanceUnit.PascalSecondPerMilliliter); + public QuantityValue PascalSecondsPerMilliliter => this.As(FluidResistanceUnit.PascalSecondPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WoodUnits => As(FluidResistanceUnit.WoodUnit); + public QuantityValue WoodUnits => this.As(FluidResistanceUnit.WoodUnit); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: FluidResistanceUnit -> BaseUnit - unitConverter.SetConversionFunction(FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.MegapascalSecondPerCubicMeter, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.MillimeterMercuryMinutePerLiter, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.MillimeterMercurySecondPerLiter, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.MillimeterMercurySecondPerMilliliter, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalMinutePerCubicCentimeter, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalMinutePerCubicMeter, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalMinutePerLiter, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalMinutePerMilliliter, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicCentimeter, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerLiter, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerMilliliter, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.WoodUnit, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.PascalSecondPerCubicMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> FluidResistanceUnit - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, quantity => quantity.ToUnit(FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MegapascalSecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.MegapascalSecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter, quantity => quantity.ToUnit(FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MillimeterMercuryMinutePerLiter, quantity => quantity.ToUnit(FluidResistanceUnit.MillimeterMercuryMinutePerLiter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter, quantity => quantity.ToUnit(FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter, quantity => quantity.ToUnit(FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MillimeterMercurySecondPerLiter, quantity => quantity.ToUnit(FluidResistanceUnit.MillimeterMercurySecondPerLiter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MillimeterMercurySecondPerMilliliter, quantity => quantity.ToUnit(FluidResistanceUnit.MillimeterMercurySecondPerMilliliter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.PascalMinutePerCubicCentimeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalMinutePerCubicCentimeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.PascalMinutePerCubicMeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalMinutePerCubicMeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.PascalMinutePerLiter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalMinutePerLiter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.PascalMinutePerMilliliter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalMinutePerMilliliter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.PascalSecondPerCubicCentimeter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerCubicCentimeter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.PascalSecondPerLiter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerLiter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.PascalSecondPerMilliliter, quantity => quantity.ToUnit(FluidResistanceUnit.PascalSecondPerMilliliter)); - unitConverter.SetConversionFunction(FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.WoodUnit, quantity => quantity.ToUnit(FluidResistanceUnit.WoodUnit)); - } - /// /// Get unit abbreviation string. /// @@ -425,7 +407,7 @@ public static string GetAbbreviation(FluidResistanceUnit unit, IFormatProvider? /// /// Creates a from . /// - public static FluidResistance FromDyneSecondsPerCentimeterToTheFifth(double value) + public static FluidResistance FromDyneSecondsPerCentimeterToTheFifth(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth); } @@ -433,7 +415,7 @@ public static FluidResistance FromDyneSecondsPerCentimeterToTheFifth(double valu /// /// Creates a from . /// - public static FluidResistance FromMegapascalSecondsPerCubicMeter(double value) + public static FluidResistance FromMegapascalSecondsPerCubicMeter(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.MegapascalSecondPerCubicMeter); } @@ -441,7 +423,7 @@ public static FluidResistance FromMegapascalSecondsPerCubicMeter(double value) /// /// Creates a from . /// - public static FluidResistance FromMillimeterMercuryMinutesPerCubicCentimeter(double value) + public static FluidResistance FromMillimeterMercuryMinutesPerCubicCentimeter(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter); } @@ -449,7 +431,7 @@ public static FluidResistance FromMillimeterMercuryMinutesPerCubicCentimeter(dou /// /// Creates a from . /// - public static FluidResistance FromMillimeterMercuryMinutesPerCubicMeter(double value) + public static FluidResistance FromMillimeterMercuryMinutesPerCubicMeter(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter); } @@ -457,7 +439,7 @@ public static FluidResistance FromMillimeterMercuryMinutesPerCubicMeter(double v /// /// Creates a from . /// - public static FluidResistance FromMillimeterMercuryMinutesPerLiter(double value) + public static FluidResistance FromMillimeterMercuryMinutesPerLiter(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.MillimeterMercuryMinutePerLiter); } @@ -465,7 +447,7 @@ public static FluidResistance FromMillimeterMercuryMinutesPerLiter(double value) /// /// Creates a from . /// - public static FluidResistance FromMillimeterMercuryMinutesPerMilliliter(double value) + public static FluidResistance FromMillimeterMercuryMinutesPerMilliliter(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter); } @@ -473,7 +455,7 @@ public static FluidResistance FromMillimeterMercuryMinutesPerMilliliter(double v /// /// Creates a from . /// - public static FluidResistance FromMillimeterMercurySecondsPerCubicCentimeter(double value) + public static FluidResistance FromMillimeterMercurySecondsPerCubicCentimeter(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter); } @@ -481,7 +463,7 @@ public static FluidResistance FromMillimeterMercurySecondsPerCubicCentimeter(dou /// /// Creates a from . /// - public static FluidResistance FromMillimeterMercurySecondsPerCubicMeter(double value) + public static FluidResistance FromMillimeterMercurySecondsPerCubicMeter(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter); } @@ -489,7 +471,7 @@ public static FluidResistance FromMillimeterMercurySecondsPerCubicMeter(double v /// /// Creates a from . /// - public static FluidResistance FromMillimeterMercurySecondsPerLiter(double value) + public static FluidResistance FromMillimeterMercurySecondsPerLiter(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.MillimeterMercurySecondPerLiter); } @@ -497,7 +479,7 @@ public static FluidResistance FromMillimeterMercurySecondsPerLiter(double value) /// /// Creates a from . /// - public static FluidResistance FromMillimeterMercurySecondsPerMilliliter(double value) + public static FluidResistance FromMillimeterMercurySecondsPerMilliliter(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.MillimeterMercurySecondPerMilliliter); } @@ -505,7 +487,7 @@ public static FluidResistance FromMillimeterMercurySecondsPerMilliliter(double v /// /// Creates a from . /// - public static FluidResistance FromPascalMinutesPerCubicCentimeter(double value) + public static FluidResistance FromPascalMinutesPerCubicCentimeter(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.PascalMinutePerCubicCentimeter); } @@ -513,7 +495,7 @@ public static FluidResistance FromPascalMinutesPerCubicCentimeter(double value) /// /// Creates a from . /// - public static FluidResistance FromPascalMinutesPerCubicMeter(double value) + public static FluidResistance FromPascalMinutesPerCubicMeter(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.PascalMinutePerCubicMeter); } @@ -521,7 +503,7 @@ public static FluidResistance FromPascalMinutesPerCubicMeter(double value) /// /// Creates a from . /// - public static FluidResistance FromPascalMinutesPerLiter(double value) + public static FluidResistance FromPascalMinutesPerLiter(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.PascalMinutePerLiter); } @@ -529,7 +511,7 @@ public static FluidResistance FromPascalMinutesPerLiter(double value) /// /// Creates a from . /// - public static FluidResistance FromPascalMinutesPerMilliliter(double value) + public static FluidResistance FromPascalMinutesPerMilliliter(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.PascalMinutePerMilliliter); } @@ -537,7 +519,7 @@ public static FluidResistance FromPascalMinutesPerMilliliter(double value) /// /// Creates a from . /// - public static FluidResistance FromPascalSecondsPerCubicCentimeter(double value) + public static FluidResistance FromPascalSecondsPerCubicCentimeter(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.PascalSecondPerCubicCentimeter); } @@ -545,7 +527,7 @@ public static FluidResistance FromPascalSecondsPerCubicCentimeter(double value) /// /// Creates a from . /// - public static FluidResistance FromPascalSecondsPerCubicMeter(double value) + public static FluidResistance FromPascalSecondsPerCubicMeter(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.PascalSecondPerCubicMeter); } @@ -553,7 +535,7 @@ public static FluidResistance FromPascalSecondsPerCubicMeter(double value) /// /// Creates a from . /// - public static FluidResistance FromPascalSecondsPerLiter(double value) + public static FluidResistance FromPascalSecondsPerLiter(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.PascalSecondPerLiter); } @@ -561,7 +543,7 @@ public static FluidResistance FromPascalSecondsPerLiter(double value) /// /// Creates a from . /// - public static FluidResistance FromPascalSecondsPerMilliliter(double value) + public static FluidResistance FromPascalSecondsPerMilliliter(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.PascalSecondPerMilliliter); } @@ -569,7 +551,7 @@ public static FluidResistance FromPascalSecondsPerMilliliter(double value) /// /// Creates a from . /// - public static FluidResistance FromWoodUnits(double value) + public static FluidResistance FromWoodUnits(QuantityValue value) { return new FluidResistance(value, FluidResistanceUnit.WoodUnit); } @@ -580,7 +562,7 @@ public static FluidResistance FromWoodUnits(double value) /// Value to convert from. /// Unit to convert from. /// FluidResistance unit value. - public static FluidResistance From(double value, FluidResistanceUnit fromUnit) + public static FluidResistance From(QuantityValue value, FluidResistanceUnit fromUnit) { return new FluidResistance(value, fromUnit); } @@ -641,10 +623,7 @@ public static FluidResistance Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static FluidResistance Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -672,11 +651,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out FluidResistance /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out FluidResistance result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -697,7 +672,7 @@ public static FluidResistanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -708,7 +683,7 @@ public static FluidResistanceUnit ParseUnit(string str, IFormatProvider? provide return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out FluidResistanceUnit unit) { return TryParseUnit(str, null, out unit); @@ -723,7 +698,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out FluidResista /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out FluidResistanceUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -742,35 +717,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static FluidResistance operator +(FluidResistance left, FluidResistance right) { - return new FluidResistance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new FluidResistance(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static FluidResistance operator -(FluidResistance left, FluidResistance right) { - return new FluidResistance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new FluidResistance(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static FluidResistance operator *(double left, FluidResistance right) + public static FluidResistance operator *(QuantityValue left, FluidResistance right) { return new FluidResistance(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static FluidResistance operator *(FluidResistance left, double right) + public static FluidResistance operator *(FluidResistance left, QuantityValue right) { return new FluidResistance(left.Value * right, left.Unit); } /// Get from dividing by value. - public static FluidResistance operator /(FluidResistance left, double right) + public static FluidResistance operator /(FluidResistance left, QuantityValue right) { return new FluidResistance(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(FluidResistance left, FluidResistance right) + public static QuantityValue operator /(FluidResistance left, FluidResistance right) { return left.PascalSecondsPerCubicMeter / right.PascalSecondsPerCubicMeter; } @@ -782,97 +757,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(FluidResistance left, FluidResistance right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(FluidResistance left, FluidResistance right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(FluidResistance left, FluidResistance right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(FluidResistance left, FluidResistance right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(FluidResistance other, FluidResistance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(FluidResistance left, FluidResistance right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(FluidResistance other, FluidResistance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(FluidResistance left, FluidResistance right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(FluidResistance other, FluidResistance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is FluidResistance otherQuantity)) + if (obj is not FluidResistance otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(FluidResistance other, FluidResistance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(FluidResistance other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current FluidResistance. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(FluidResistance), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is FluidResistance otherQuantity)) throw new ArgumentException("Expected type FluidResistance.", nameof(obj)); + if (obj is not FluidResistance otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -884,182 +844,24 @@ public int CompareTo(object? obj) /// public int CompareTo(FluidResistance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(FluidResistanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this FluidResistance to another FluidResistance with the unit representation . - /// - /// The unit to convert to. - /// A FluidResistance with the specified unit. - public FluidResistance ToUnit(FluidResistanceUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A FluidResistance with the specified unit. - public FluidResistance ToUnit(FluidResistanceUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(FluidResistance), Unit, typeof(FluidResistance), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (FluidResistance)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(FluidResistanceUnit unit, [NotNullWhen(true)] out FluidResistance? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - FluidResistance? convertedOrNull = (Unit, unit) switch - { - // FluidResistanceUnit -> BaseUnit - (FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance(_value * 1e5, FluidResistanceUnit.PascalSecondPerCubicMeter), - (FluidResistanceUnit.MegapascalSecondPerCubicMeter, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance((_value) * 1e6d, FluidResistanceUnit.PascalSecondPerCubicMeter), - (FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance(_value * 7.99934208e9, FluidResistanceUnit.PascalSecondPerCubicMeter), - (FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance(_value * 7.99934208e3, FluidResistanceUnit.PascalSecondPerCubicMeter), - (FluidResistanceUnit.MillimeterMercuryMinutePerLiter, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance(_value * 7.99934208e6, FluidResistanceUnit.PascalSecondPerCubicMeter), - (FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance(_value * 7.99934208e9, FluidResistanceUnit.PascalSecondPerCubicMeter), - (FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance(_value * 1.33322368e8, FluidResistanceUnit.PascalSecondPerCubicMeter), - (FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance(_value * 133.322368, FluidResistanceUnit.PascalSecondPerCubicMeter), - (FluidResistanceUnit.MillimeterMercurySecondPerLiter, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance(_value * 1.33322368e5, FluidResistanceUnit.PascalSecondPerCubicMeter), - (FluidResistanceUnit.MillimeterMercurySecondPerMilliliter, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance(_value * 1.33322368e8, FluidResistanceUnit.PascalSecondPerCubicMeter), - (FluidResistanceUnit.PascalMinutePerCubicCentimeter, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance(_value * 6e7, FluidResistanceUnit.PascalSecondPerCubicMeter), - (FluidResistanceUnit.PascalMinutePerCubicMeter, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance(_value * 60, FluidResistanceUnit.PascalSecondPerCubicMeter), - (FluidResistanceUnit.PascalMinutePerLiter, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance(_value * 6e4, FluidResistanceUnit.PascalSecondPerCubicMeter), - (FluidResistanceUnit.PascalMinutePerMilliliter, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance(_value * 6e7, FluidResistanceUnit.PascalSecondPerCubicMeter), - (FluidResistanceUnit.PascalSecondPerCubicCentimeter, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance(_value * 1e6, FluidResistanceUnit.PascalSecondPerCubicMeter), - (FluidResistanceUnit.PascalSecondPerLiter, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance(_value * 1e3, FluidResistanceUnit.PascalSecondPerCubicMeter), - (FluidResistanceUnit.PascalSecondPerMilliliter, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance(_value * 1e6, FluidResistanceUnit.PascalSecondPerCubicMeter), - (FluidResistanceUnit.WoodUnit, FluidResistanceUnit.PascalSecondPerCubicMeter) => new FluidResistance(_value * 7.99934208e6, FluidResistanceUnit.PascalSecondPerCubicMeter), - - // BaseUnit -> FluidResistanceUnit - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth) => new FluidResistance(_value / 1e5, FluidResistanceUnit.DyneSecondPerCentimeterToTheFifth), - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MegapascalSecondPerCubicMeter) => new FluidResistance((_value) / 1e6d, FluidResistanceUnit.MegapascalSecondPerCubicMeter), - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter) => new FluidResistance(_value / 7.99934208e9, FluidResistanceUnit.MillimeterMercuryMinutePerCubicCentimeter), - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter) => new FluidResistance(_value / 7.99934208e3, FluidResistanceUnit.MillimeterMercuryMinutePerCubicMeter), - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MillimeterMercuryMinutePerLiter) => new FluidResistance(_value / 7.99934208e6, FluidResistanceUnit.MillimeterMercuryMinutePerLiter), - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter) => new FluidResistance(_value / 7.99934208e9, FluidResistanceUnit.MillimeterMercuryMinutePerMilliliter), - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter) => new FluidResistance(_value / 1.33322368e8, FluidResistanceUnit.MillimeterMercurySecondPerCubicCentimeter), - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter) => new FluidResistance(_value / 133.322368, FluidResistanceUnit.MillimeterMercurySecondPerCubicMeter), - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MillimeterMercurySecondPerLiter) => new FluidResistance(_value / 1.33322368e5, FluidResistanceUnit.MillimeterMercurySecondPerLiter), - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.MillimeterMercurySecondPerMilliliter) => new FluidResistance(_value / 1.33322368e8, FluidResistanceUnit.MillimeterMercurySecondPerMilliliter), - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.PascalMinutePerCubicCentimeter) => new FluidResistance(_value / 6e7, FluidResistanceUnit.PascalMinutePerCubicCentimeter), - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.PascalMinutePerCubicMeter) => new FluidResistance(_value / 60, FluidResistanceUnit.PascalMinutePerCubicMeter), - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.PascalMinutePerLiter) => new FluidResistance(_value / 6e4, FluidResistanceUnit.PascalMinutePerLiter), - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.PascalMinutePerMilliliter) => new FluidResistance(_value / 6e7, FluidResistanceUnit.PascalMinutePerMilliliter), - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.PascalSecondPerCubicCentimeter) => new FluidResistance(_value / 1e6, FluidResistanceUnit.PascalSecondPerCubicCentimeter), - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.PascalSecondPerLiter) => new FluidResistance(_value / 1e3, FluidResistanceUnit.PascalSecondPerLiter), - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.PascalSecondPerMilliliter) => new FluidResistance(_value / 1e6, FluidResistanceUnit.PascalSecondPerMilliliter), - (FluidResistanceUnit.PascalSecondPerCubicMeter, FluidResistanceUnit.WoodUnit) => new FluidResistance(_value / 7.99934208e6, FluidResistanceUnit.WoodUnit), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public FluidResistance ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not FluidResistanceUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FluidResistanceUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is FluidResistanceUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FluidResistanceUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(FluidResistanceUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(FluidResistanceUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1074,7 +876,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Force.g.cs b/UnitsNet/GeneratedCode/Quantities/Force.g.cs index c599c8b026..95b314689a 100644 --- a/UnitsNet/GeneratedCode/Quantities/Force.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Force.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Force : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -64,13 +63,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ForceUnit? _unit; /// @@ -115,7 +114,7 @@ public static ForceInfo CreateDefault(Func } /// - /// The for is [T^-2][L][M]. + /// The for is T^-2LM. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); @@ -130,29 +129,55 @@ public static ForceInfo CreateDefault(Func /// An of representing the default unit mappings for Force. public static IEnumerable> GetDefaultMappings() { - yield return new (ForceUnit.Decanewton, "Decanewton", "Decanewtons", new BaseUnits(length: LengthUnit.Decameter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ForceUnit.Dyn, "Dyn", "Dyne", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram, time: DurationUnit.Second)); - yield return new (ForceUnit.KilogramForce, "KilogramForce", "KilogramsForce", BaseUnits.Undefined); - yield return new (ForceUnit.Kilonewton, "Kilonewton", "Kilonewtons", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ForceUnit.KiloPond, "KiloPond", "KiloPonds", BaseUnits.Undefined); - yield return new (ForceUnit.KilopoundForce, "KilopoundForce", "KilopoundsForce", BaseUnits.Undefined); - yield return new (ForceUnit.Meganewton, "Meganewton", "Meganewtons", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ForceUnit.Micronewton, "Micronewton", "Micronewtons", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ForceUnit.Millinewton, "Millinewton", "Millinewtons", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); + yield return new (ForceUnit.Decanewton, "Decanewton", "Decanewtons", new BaseUnits(length: LengthUnit.Decameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 10) + ); + yield return new (ForceUnit.Dyn, "Dyn", "Dyne", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram, time: DurationUnit.Second), + 100000 + ); + yield return new (ForceUnit.KilogramForce, "KilogramForce", "KilogramsForce", BaseUnits.Undefined, + new QuantityValue(20000, 196133) + ); + yield return new (ForceUnit.Kilonewton, "Kilonewton", "Kilonewtons", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000) + ); + yield return new (ForceUnit.KiloPond, "KiloPond", "KiloPonds", BaseUnits.Undefined, + new QuantityValue(20000, 196133) + ); + yield return new (ForceUnit.KilopoundForce, "KilopoundForce", "KilopoundsForce", BaseUnits.Undefined, + new QuantityValue(2000000000, 8896443230521) + ); + yield return new (ForceUnit.Meganewton, "Meganewton", "Meganewtons", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (ForceUnit.Micronewton, "Micronewton", "Micronewtons", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + 1000000 + ); + yield return new (ForceUnit.Millinewton, "Millinewton", "Millinewtons", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + 1000 + ); yield return new (ForceUnit.Newton, "Newton", "Newtons", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ForceUnit.OunceForce, "OunceForce", "OunceForce", BaseUnits.Undefined); - yield return new (ForceUnit.Poundal, "Poundal", "Poundals", BaseUnits.Undefined); - yield return new (ForceUnit.PoundForce, "PoundForce", "PoundsForce", BaseUnits.Undefined); - yield return new (ForceUnit.ShortTonForce, "ShortTonForce", "ShortTonsForce", BaseUnits.Undefined); - yield return new (ForceUnit.TonneForce, "TonneForce", "TonnesForce", BaseUnits.Undefined); + yield return new (ForceUnit.OunceForce, "OunceForce", "OunceForce", BaseUnits.Undefined, + new QuantityValue(32000000000000, 8896443230521) + ); + yield return new (ForceUnit.Poundal, "Poundal", "Poundals", BaseUnits.Undefined, + new QuantityValue(125000000000, 17281869297) + ); + yield return new (ForceUnit.PoundForce, "PoundForce", "PoundsForce", BaseUnits.Undefined, + new QuantityValue(2000000000000, 8896443230521) + ); + yield return new (ForceUnit.ShortTonForce, "ShortTonForce", "ShortTonsForce", BaseUnits.Undefined, + new QuantityValue(1000000000, 8896443230521) + ); + yield return new (ForceUnit.TonneForce, "TonneForce", "TonnesForce", BaseUnits.Undefined, + new QuantityValue(20, 196133) + ); } } static Force() { - Info = ForceInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ForceInfo.CreateDefault); } /// @@ -160,7 +185,7 @@ static Force() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Force(double value, ForceUnit unit) + public Force(QuantityValue value, ForceUnit unit) { _value = value; _unit = unit; @@ -174,7 +199,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -185,7 +210,8 @@ public Force(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -214,10 +240,8 @@ public Force(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ForceUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -256,126 +280,84 @@ public Force(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Decanewtons => As(ForceUnit.Decanewton); + public QuantityValue Decanewtons => this.As(ForceUnit.Decanewton); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Dyne => As(ForceUnit.Dyn); + public QuantityValue Dyne => this.As(ForceUnit.Dyn); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsForce => As(ForceUnit.KilogramForce); + public QuantityValue KilogramsForce => this.As(ForceUnit.KilogramForce); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilonewtons => As(ForceUnit.Kilonewton); + public QuantityValue Kilonewtons => this.As(ForceUnit.Kilonewton); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KiloPonds => As(ForceUnit.KiloPond); + public QuantityValue KiloPonds => this.As(ForceUnit.KiloPond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsForce => As(ForceUnit.KilopoundForce); + public QuantityValue KilopoundsForce => this.As(ForceUnit.KilopoundForce); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Meganewtons => As(ForceUnit.Meganewton); + public QuantityValue Meganewtons => this.As(ForceUnit.Meganewton); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Micronewtons => As(ForceUnit.Micronewton); + public QuantityValue Micronewtons => this.As(ForceUnit.Micronewton); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millinewtons => As(ForceUnit.Millinewton); + public QuantityValue Millinewtons => this.As(ForceUnit.Millinewton); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Newtons => As(ForceUnit.Newton); + public QuantityValue Newtons => this.As(ForceUnit.Newton); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double OunceForce => As(ForceUnit.OunceForce); + public QuantityValue OunceForce => this.As(ForceUnit.OunceForce); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Poundals => As(ForceUnit.Poundal); + public QuantityValue Poundals => this.As(ForceUnit.Poundal); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsForce => As(ForceUnit.PoundForce); + public QuantityValue PoundsForce => this.As(ForceUnit.PoundForce); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ShortTonsForce => As(ForceUnit.ShortTonForce); + public QuantityValue ShortTonsForce => this.As(ForceUnit.ShortTonForce); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesForce => As(ForceUnit.TonneForce); + public QuantityValue TonnesForce => this.As(ForceUnit.TonneForce); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ForceUnit -> BaseUnit - unitConverter.SetConversionFunction(ForceUnit.Decanewton, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); - unitConverter.SetConversionFunction(ForceUnit.Dyn, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); - unitConverter.SetConversionFunction(ForceUnit.KilogramForce, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); - unitConverter.SetConversionFunction(ForceUnit.Kilonewton, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); - unitConverter.SetConversionFunction(ForceUnit.KiloPond, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); - unitConverter.SetConversionFunction(ForceUnit.KilopoundForce, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); - unitConverter.SetConversionFunction(ForceUnit.Meganewton, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); - unitConverter.SetConversionFunction(ForceUnit.Micronewton, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); - unitConverter.SetConversionFunction(ForceUnit.Millinewton, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); - unitConverter.SetConversionFunction(ForceUnit.OunceForce, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); - unitConverter.SetConversionFunction(ForceUnit.Poundal, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); - unitConverter.SetConversionFunction(ForceUnit.PoundForce, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); - unitConverter.SetConversionFunction(ForceUnit.ShortTonForce, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); - unitConverter.SetConversionFunction(ForceUnit.TonneForce, ForceUnit.Newton, quantity => quantity.ToUnit(ForceUnit.Newton)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Newton, quantity => quantity); - - // Register in unit converter: BaseUnit -> ForceUnit - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Decanewton, quantity => quantity.ToUnit(ForceUnit.Decanewton)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Dyn, quantity => quantity.ToUnit(ForceUnit.Dyn)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.KilogramForce, quantity => quantity.ToUnit(ForceUnit.KilogramForce)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Kilonewton, quantity => quantity.ToUnit(ForceUnit.Kilonewton)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.KiloPond, quantity => quantity.ToUnit(ForceUnit.KiloPond)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.KilopoundForce, quantity => quantity.ToUnit(ForceUnit.KilopoundForce)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Meganewton, quantity => quantity.ToUnit(ForceUnit.Meganewton)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Micronewton, quantity => quantity.ToUnit(ForceUnit.Micronewton)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Millinewton, quantity => quantity.ToUnit(ForceUnit.Millinewton)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.OunceForce, quantity => quantity.ToUnit(ForceUnit.OunceForce)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.Poundal, quantity => quantity.ToUnit(ForceUnit.Poundal)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.PoundForce, quantity => quantity.ToUnit(ForceUnit.PoundForce)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.ShortTonForce, quantity => quantity.ToUnit(ForceUnit.ShortTonForce)); - unitConverter.SetConversionFunction(ForceUnit.Newton, ForceUnit.TonneForce, quantity => quantity.ToUnit(ForceUnit.TonneForce)); - } - /// /// Get unit abbreviation string. /// @@ -404,7 +386,7 @@ public static string GetAbbreviation(ForceUnit unit, IFormatProvider? provider) /// /// Creates a from . /// - public static Force FromDecanewtons(double value) + public static Force FromDecanewtons(QuantityValue value) { return new Force(value, ForceUnit.Decanewton); } @@ -412,7 +394,7 @@ public static Force FromDecanewtons(double value) /// /// Creates a from . /// - public static Force FromDyne(double value) + public static Force FromDyne(QuantityValue value) { return new Force(value, ForceUnit.Dyn); } @@ -420,7 +402,7 @@ public static Force FromDyne(double value) /// /// Creates a from . /// - public static Force FromKilogramsForce(double value) + public static Force FromKilogramsForce(QuantityValue value) { return new Force(value, ForceUnit.KilogramForce); } @@ -428,7 +410,7 @@ public static Force FromKilogramsForce(double value) /// /// Creates a from . /// - public static Force FromKilonewtons(double value) + public static Force FromKilonewtons(QuantityValue value) { return new Force(value, ForceUnit.Kilonewton); } @@ -436,7 +418,7 @@ public static Force FromKilonewtons(double value) /// /// Creates a from . /// - public static Force FromKiloPonds(double value) + public static Force FromKiloPonds(QuantityValue value) { return new Force(value, ForceUnit.KiloPond); } @@ -444,7 +426,7 @@ public static Force FromKiloPonds(double value) /// /// Creates a from . /// - public static Force FromKilopoundsForce(double value) + public static Force FromKilopoundsForce(QuantityValue value) { return new Force(value, ForceUnit.KilopoundForce); } @@ -452,7 +434,7 @@ public static Force FromKilopoundsForce(double value) /// /// Creates a from . /// - public static Force FromMeganewtons(double value) + public static Force FromMeganewtons(QuantityValue value) { return new Force(value, ForceUnit.Meganewton); } @@ -460,7 +442,7 @@ public static Force FromMeganewtons(double value) /// /// Creates a from . /// - public static Force FromMicronewtons(double value) + public static Force FromMicronewtons(QuantityValue value) { return new Force(value, ForceUnit.Micronewton); } @@ -468,7 +450,7 @@ public static Force FromMicronewtons(double value) /// /// Creates a from . /// - public static Force FromMillinewtons(double value) + public static Force FromMillinewtons(QuantityValue value) { return new Force(value, ForceUnit.Millinewton); } @@ -476,7 +458,7 @@ public static Force FromMillinewtons(double value) /// /// Creates a from . /// - public static Force FromNewtons(double value) + public static Force FromNewtons(QuantityValue value) { return new Force(value, ForceUnit.Newton); } @@ -484,7 +466,7 @@ public static Force FromNewtons(double value) /// /// Creates a from . /// - public static Force FromOunceForce(double value) + public static Force FromOunceForce(QuantityValue value) { return new Force(value, ForceUnit.OunceForce); } @@ -492,7 +474,7 @@ public static Force FromOunceForce(double value) /// /// Creates a from . /// - public static Force FromPoundals(double value) + public static Force FromPoundals(QuantityValue value) { return new Force(value, ForceUnit.Poundal); } @@ -500,7 +482,7 @@ public static Force FromPoundals(double value) /// /// Creates a from . /// - public static Force FromPoundsForce(double value) + public static Force FromPoundsForce(QuantityValue value) { return new Force(value, ForceUnit.PoundForce); } @@ -508,7 +490,7 @@ public static Force FromPoundsForce(double value) /// /// Creates a from . /// - public static Force FromShortTonsForce(double value) + public static Force FromShortTonsForce(QuantityValue value) { return new Force(value, ForceUnit.ShortTonForce); } @@ -516,7 +498,7 @@ public static Force FromShortTonsForce(double value) /// /// Creates a from . /// - public static Force FromTonnesForce(double value) + public static Force FromTonnesForce(QuantityValue value) { return new Force(value, ForceUnit.TonneForce); } @@ -527,7 +509,7 @@ public static Force FromTonnesForce(double value) /// Value to convert from. /// Unit to convert from. /// Force unit value. - public static Force From(double value, ForceUnit fromUnit) + public static Force From(QuantityValue value, ForceUnit fromUnit) { return new Force(value, fromUnit); } @@ -588,10 +570,7 @@ public static Force Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Force Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -619,11 +598,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Force result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Force result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -644,7 +619,7 @@ public static ForceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -655,7 +630,7 @@ public static ForceUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ForceUnit unit) { return TryParseUnit(str, null, out unit); @@ -670,7 +645,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ForceUnit un /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ForceUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -689,35 +664,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Force operator +(Force left, Force right) { - return new Force(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Force(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Force operator -(Force left, Force right) { - return new Force(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Force(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -805,97 +780,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Force left, Force right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Force left, Force right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Force left, Force right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Force left, Force right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Force other, Force tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Force left, Force right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Force other, Force tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Force left, Force right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Force other, Force tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Force otherQuantity)) + if (obj is not Force otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Force other, Force tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Force other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Force. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Force), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Force otherQuantity)) throw new ArgumentException("Expected type Force.", nameof(obj)); + if (obj is not Force otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -907,174 +867,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Force other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ForceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this Force to another Force with the unit representation . - /// - /// The unit to convert to. - /// A Force with the specified unit. - public Force ToUnit(ForceUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Force with the specified unit. - public Force ToUnit(ForceUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Force), Unit, typeof(Force), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Force)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ForceUnit unit, [NotNullWhen(true)] out Force? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Force? convertedOrNull = (Unit, unit) switch - { - // ForceUnit -> BaseUnit - (ForceUnit.Decanewton, ForceUnit.Newton) => new Force((_value) * 1e1d, ForceUnit.Newton), - (ForceUnit.Dyn, ForceUnit.Newton) => new Force(_value / 1e5, ForceUnit.Newton), - (ForceUnit.KilogramForce, ForceUnit.Newton) => new Force(_value * 9.80665, ForceUnit.Newton), - (ForceUnit.Kilonewton, ForceUnit.Newton) => new Force((_value) * 1e3d, ForceUnit.Newton), - (ForceUnit.KiloPond, ForceUnit.Newton) => new Force(_value * 9.80665, ForceUnit.Newton), - (ForceUnit.KilopoundForce, ForceUnit.Newton) => new Force((_value * 4.4482216152605) * 1e3d, ForceUnit.Newton), - (ForceUnit.Meganewton, ForceUnit.Newton) => new Force((_value) * 1e6d, ForceUnit.Newton), - (ForceUnit.Micronewton, ForceUnit.Newton) => new Force((_value) * 1e-6d, ForceUnit.Newton), - (ForceUnit.Millinewton, ForceUnit.Newton) => new Force((_value) * 1e-3d, ForceUnit.Newton), - (ForceUnit.OunceForce, ForceUnit.Newton) => new Force(_value * (4.4482216152605 / 16), ForceUnit.Newton), - (ForceUnit.Poundal, ForceUnit.Newton) => new Force(_value * 0.138254954376, ForceUnit.Newton), - (ForceUnit.PoundForce, ForceUnit.Newton) => new Force(_value * 4.4482216152605, ForceUnit.Newton), - (ForceUnit.ShortTonForce, ForceUnit.Newton) => new Force(_value * (4.4482216152605 * 2000), ForceUnit.Newton), - (ForceUnit.TonneForce, ForceUnit.Newton) => new Force(_value * (9.80665 * 1000), ForceUnit.Newton), - - // BaseUnit -> ForceUnit - (ForceUnit.Newton, ForceUnit.Decanewton) => new Force((_value) / 1e1d, ForceUnit.Decanewton), - (ForceUnit.Newton, ForceUnit.Dyn) => new Force(_value * 1e5, ForceUnit.Dyn), - (ForceUnit.Newton, ForceUnit.KilogramForce) => new Force(_value / 9.80665, ForceUnit.KilogramForce), - (ForceUnit.Newton, ForceUnit.Kilonewton) => new Force((_value) / 1e3d, ForceUnit.Kilonewton), - (ForceUnit.Newton, ForceUnit.KiloPond) => new Force(_value / 9.80665, ForceUnit.KiloPond), - (ForceUnit.Newton, ForceUnit.KilopoundForce) => new Force((_value / 4.4482216152605) / 1e3d, ForceUnit.KilopoundForce), - (ForceUnit.Newton, ForceUnit.Meganewton) => new Force((_value) / 1e6d, ForceUnit.Meganewton), - (ForceUnit.Newton, ForceUnit.Micronewton) => new Force((_value) / 1e-6d, ForceUnit.Micronewton), - (ForceUnit.Newton, ForceUnit.Millinewton) => new Force((_value) / 1e-3d, ForceUnit.Millinewton), - (ForceUnit.Newton, ForceUnit.OunceForce) => new Force(_value / (4.4482216152605 / 16), ForceUnit.OunceForce), - (ForceUnit.Newton, ForceUnit.Poundal) => new Force(_value / 0.138254954376, ForceUnit.Poundal), - (ForceUnit.Newton, ForceUnit.PoundForce) => new Force(_value / 4.4482216152605, ForceUnit.PoundForce), - (ForceUnit.Newton, ForceUnit.ShortTonForce) => new Force(_value / (4.4482216152605 * 2000), ForceUnit.ShortTonForce), - (ForceUnit.Newton, ForceUnit.TonneForce) => new Force(_value / (9.80665 * 1000), ForceUnit.TonneForce), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Force ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ForceUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForceUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ForceUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ForceUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1089,7 +899,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs index badcaca9b7..6781e1cb61 100644 --- a/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ForceChangeRate.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ForceChangeRate : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ForceChangeRateUnit? _unit; /// @@ -104,7 +103,7 @@ public static ForceChangeRateInfo CreateDefault(Func - /// The for is [T^-3][L][M]. + /// The for is T^-3LM. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 1, -3, 0, 0, 0, 0); @@ -119,29 +118,55 @@ public static ForceChangeRateInfo CreateDefault(FuncAn of representing the default unit mappings for ForceChangeRate. public static IEnumerable> GetDefaultMappings() { - yield return new (ForceChangeRateUnit.CentinewtonPerSecond, "CentinewtonPerSecond", "CentinewtonsPerSecond", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ForceChangeRateUnit.DecanewtonPerMinute, "DecanewtonPerMinute", "DecanewtonsPerMinute", BaseUnits.Undefined); - yield return new (ForceChangeRateUnit.DecanewtonPerSecond, "DecanewtonPerSecond", "DecanewtonsPerSecond", new BaseUnits(length: LengthUnit.Decameter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ForceChangeRateUnit.DecinewtonPerSecond, "DecinewtonPerSecond", "DecinewtonsPerSecond", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ForceChangeRateUnit.KilonewtonPerMinute, "KilonewtonPerMinute", "KilonewtonsPerMinute", BaseUnits.Undefined); - yield return new (ForceChangeRateUnit.KilonewtonPerSecond, "KilonewtonPerSecond", "KilonewtonsPerSecond", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ForceChangeRateUnit.KilopoundForcePerMinute, "KilopoundForcePerMinute", "KilopoundsForcePerMinute", BaseUnits.Undefined); - yield return new (ForceChangeRateUnit.KilopoundForcePerSecond, "KilopoundForcePerSecond", "KilopoundsForcePerSecond", BaseUnits.Undefined); - yield return new (ForceChangeRateUnit.MicronewtonPerSecond, "MicronewtonPerSecond", "MicronewtonsPerSecond", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ForceChangeRateUnit.MillinewtonPerSecond, "MillinewtonPerSecond", "MillinewtonsPerSecond", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ForceChangeRateUnit.NanonewtonPerSecond, "NanonewtonPerSecond", "NanonewtonsPerSecond", new BaseUnits(length: LengthUnit.Nanometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ForceChangeRateUnit.NewtonPerMinute, "NewtonPerMinute", "NewtonsPerMinute", BaseUnits.Undefined); + yield return new (ForceChangeRateUnit.CentinewtonPerSecond, "CentinewtonPerSecond", "CentinewtonsPerSecond", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + 100 + ); + yield return new (ForceChangeRateUnit.DecanewtonPerMinute, "DecanewtonPerMinute", "DecanewtonsPerMinute", BaseUnits.Undefined, + 6 + ); + yield return new (ForceChangeRateUnit.DecanewtonPerSecond, "DecanewtonPerSecond", "DecanewtonsPerSecond", new BaseUnits(length: LengthUnit.Decameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 10) + ); + yield return new (ForceChangeRateUnit.DecinewtonPerSecond, "DecinewtonPerSecond", "DecinewtonsPerSecond", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + 10 + ); + yield return new (ForceChangeRateUnit.KilonewtonPerMinute, "KilonewtonPerMinute", "KilonewtonsPerMinute", BaseUnits.Undefined, + new QuantityValue(3, 50) + ); + yield return new (ForceChangeRateUnit.KilonewtonPerSecond, "KilonewtonPerSecond", "KilonewtonsPerSecond", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000) + ); + yield return new (ForceChangeRateUnit.KilopoundForcePerMinute, "KilopoundForcePerMinute", "KilopoundsForcePerMinute", BaseUnits.Undefined, + new QuantityValue(120000000000, 8896443230521) + ); + yield return new (ForceChangeRateUnit.KilopoundForcePerSecond, "KilopoundForcePerSecond", "KilopoundsForcePerSecond", BaseUnits.Undefined, + new QuantityValue(2000000000, 8896443230521) + ); + yield return new (ForceChangeRateUnit.MicronewtonPerSecond, "MicronewtonPerSecond", "MicronewtonsPerSecond", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + 1000000 + ); + yield return new (ForceChangeRateUnit.MillinewtonPerSecond, "MillinewtonPerSecond", "MillinewtonsPerSecond", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + 1000 + ); + yield return new (ForceChangeRateUnit.NanonewtonPerSecond, "NanonewtonPerSecond", "NanonewtonsPerSecond", new BaseUnits(length: LengthUnit.Nanometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + 1000000000 + ); + yield return new (ForceChangeRateUnit.NewtonPerMinute, "NewtonPerMinute", "NewtonsPerMinute", BaseUnits.Undefined, + 60 + ); yield return new (ForceChangeRateUnit.NewtonPerSecond, "NewtonPerSecond", "NewtonsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ForceChangeRateUnit.PoundForcePerMinute, "PoundForcePerMinute", "PoundsForcePerMinute", BaseUnits.Undefined); - yield return new (ForceChangeRateUnit.PoundForcePerSecond, "PoundForcePerSecond", "PoundsForcePerSecond", BaseUnits.Undefined); + yield return new (ForceChangeRateUnit.PoundForcePerMinute, "PoundForcePerMinute", "PoundsForcePerMinute", BaseUnits.Undefined, + new QuantityValue(120000000000000, 8896443230521) + ); + yield return new (ForceChangeRateUnit.PoundForcePerSecond, "PoundForcePerSecond", "PoundsForcePerSecond", BaseUnits.Undefined, + new QuantityValue(2000000000000, 8896443230521) + ); } } static ForceChangeRate() { - Info = ForceChangeRateInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ForceChangeRateInfo.CreateDefault); } /// @@ -149,7 +174,7 @@ static ForceChangeRate() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ForceChangeRate(double value, ForceChangeRateUnit unit) + public ForceChangeRate(QuantityValue value, ForceChangeRateUnit unit) { _value = value; _unit = unit; @@ -163,7 +188,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -174,7 +199,8 @@ public ForceChangeRate(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -203,10 +229,8 @@ public ForceChangeRate(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ForceChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -245,126 +269,84 @@ public ForceChangeRate(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentinewtonsPerSecond => As(ForceChangeRateUnit.CentinewtonPerSecond); + public QuantityValue CentinewtonsPerSecond => this.As(ForceChangeRateUnit.CentinewtonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecanewtonsPerMinute => As(ForceChangeRateUnit.DecanewtonPerMinute); + public QuantityValue DecanewtonsPerMinute => this.As(ForceChangeRateUnit.DecanewtonPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecanewtonsPerSecond => As(ForceChangeRateUnit.DecanewtonPerSecond); + public QuantityValue DecanewtonsPerSecond => this.As(ForceChangeRateUnit.DecanewtonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecinewtonsPerSecond => As(ForceChangeRateUnit.DecinewtonPerSecond); + public QuantityValue DecinewtonsPerSecond => this.As(ForceChangeRateUnit.DecinewtonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonsPerMinute => As(ForceChangeRateUnit.KilonewtonPerMinute); + public QuantityValue KilonewtonsPerMinute => this.As(ForceChangeRateUnit.KilonewtonPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonsPerSecond => As(ForceChangeRateUnit.KilonewtonPerSecond); + public QuantityValue KilonewtonsPerSecond => this.As(ForceChangeRateUnit.KilonewtonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsForcePerMinute => As(ForceChangeRateUnit.KilopoundForcePerMinute); + public QuantityValue KilopoundsForcePerMinute => this.As(ForceChangeRateUnit.KilopoundForcePerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsForcePerSecond => As(ForceChangeRateUnit.KilopoundForcePerSecond); + public QuantityValue KilopoundsForcePerSecond => this.As(ForceChangeRateUnit.KilopoundForcePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicronewtonsPerSecond => As(ForceChangeRateUnit.MicronewtonPerSecond); + public QuantityValue MicronewtonsPerSecond => this.As(ForceChangeRateUnit.MicronewtonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillinewtonsPerSecond => As(ForceChangeRateUnit.MillinewtonPerSecond); + public QuantityValue MillinewtonsPerSecond => this.As(ForceChangeRateUnit.MillinewtonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanonewtonsPerSecond => As(ForceChangeRateUnit.NanonewtonPerSecond); + public QuantityValue NanonewtonsPerSecond => this.As(ForceChangeRateUnit.NanonewtonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonsPerMinute => As(ForceChangeRateUnit.NewtonPerMinute); + public QuantityValue NewtonsPerMinute => this.As(ForceChangeRateUnit.NewtonPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonsPerSecond => As(ForceChangeRateUnit.NewtonPerSecond); + public QuantityValue NewtonsPerSecond => this.As(ForceChangeRateUnit.NewtonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsForcePerMinute => As(ForceChangeRateUnit.PoundForcePerMinute); + public QuantityValue PoundsForcePerMinute => this.As(ForceChangeRateUnit.PoundForcePerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsForcePerSecond => As(ForceChangeRateUnit.PoundForcePerSecond); + public QuantityValue PoundsForcePerSecond => this.As(ForceChangeRateUnit.PoundForcePerSecond); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ForceChangeRateUnit -> BaseUnit - unitConverter.SetConversionFunction(ForceChangeRateUnit.CentinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.DecanewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.DecanewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.DecinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.KilonewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.KilonewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.KilopoundForcePerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.KilopoundForcePerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.MicronewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.MillinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NanonewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.PoundForcePerMinute, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.PoundForcePerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> ForceChangeRateUnit - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.CentinewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.CentinewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecanewtonPerMinute, quantity => quantity.ToUnit(ForceChangeRateUnit.DecanewtonPerMinute)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecanewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.DecanewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecinewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.DecinewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilonewtonPerMinute, quantity => quantity.ToUnit(ForceChangeRateUnit.KilonewtonPerMinute)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilonewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.KilonewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilopoundForcePerMinute, quantity => quantity.ToUnit(ForceChangeRateUnit.KilopoundForcePerMinute)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilopoundForcePerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.KilopoundForcePerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.MicronewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.MicronewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.MillinewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.MillinewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.NanonewtonPerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.NanonewtonPerSecond)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.NewtonPerMinute, quantity => quantity.ToUnit(ForceChangeRateUnit.NewtonPerMinute)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.PoundForcePerMinute, quantity => quantity.ToUnit(ForceChangeRateUnit.PoundForcePerMinute)); - unitConverter.SetConversionFunction(ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.PoundForcePerSecond, quantity => quantity.ToUnit(ForceChangeRateUnit.PoundForcePerSecond)); - } - /// /// Get unit abbreviation string. /// @@ -393,7 +375,7 @@ public static string GetAbbreviation(ForceChangeRateUnit unit, IFormatProvider? /// /// Creates a from . /// - public static ForceChangeRate FromCentinewtonsPerSecond(double value) + public static ForceChangeRate FromCentinewtonsPerSecond(QuantityValue value) { return new ForceChangeRate(value, ForceChangeRateUnit.CentinewtonPerSecond); } @@ -401,7 +383,7 @@ public static ForceChangeRate FromCentinewtonsPerSecond(double value) /// /// Creates a from . /// - public static ForceChangeRate FromDecanewtonsPerMinute(double value) + public static ForceChangeRate FromDecanewtonsPerMinute(QuantityValue value) { return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerMinute); } @@ -409,7 +391,7 @@ public static ForceChangeRate FromDecanewtonsPerMinute(double value) /// /// Creates a from . /// - public static ForceChangeRate FromDecanewtonsPerSecond(double value) + public static ForceChangeRate FromDecanewtonsPerSecond(QuantityValue value) { return new ForceChangeRate(value, ForceChangeRateUnit.DecanewtonPerSecond); } @@ -417,7 +399,7 @@ public static ForceChangeRate FromDecanewtonsPerSecond(double value) /// /// Creates a from . /// - public static ForceChangeRate FromDecinewtonsPerSecond(double value) + public static ForceChangeRate FromDecinewtonsPerSecond(QuantityValue value) { return new ForceChangeRate(value, ForceChangeRateUnit.DecinewtonPerSecond); } @@ -425,7 +407,7 @@ public static ForceChangeRate FromDecinewtonsPerSecond(double value) /// /// Creates a from . /// - public static ForceChangeRate FromKilonewtonsPerMinute(double value) + public static ForceChangeRate FromKilonewtonsPerMinute(QuantityValue value) { return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerMinute); } @@ -433,7 +415,7 @@ public static ForceChangeRate FromKilonewtonsPerMinute(double value) /// /// Creates a from . /// - public static ForceChangeRate FromKilonewtonsPerSecond(double value) + public static ForceChangeRate FromKilonewtonsPerSecond(QuantityValue value) { return new ForceChangeRate(value, ForceChangeRateUnit.KilonewtonPerSecond); } @@ -441,7 +423,7 @@ public static ForceChangeRate FromKilonewtonsPerSecond(double value) /// /// Creates a from . /// - public static ForceChangeRate FromKilopoundsForcePerMinute(double value) + public static ForceChangeRate FromKilopoundsForcePerMinute(QuantityValue value) { return new ForceChangeRate(value, ForceChangeRateUnit.KilopoundForcePerMinute); } @@ -449,7 +431,7 @@ public static ForceChangeRate FromKilopoundsForcePerMinute(double value) /// /// Creates a from . /// - public static ForceChangeRate FromKilopoundsForcePerSecond(double value) + public static ForceChangeRate FromKilopoundsForcePerSecond(QuantityValue value) { return new ForceChangeRate(value, ForceChangeRateUnit.KilopoundForcePerSecond); } @@ -457,7 +439,7 @@ public static ForceChangeRate FromKilopoundsForcePerSecond(double value) /// /// Creates a from . /// - public static ForceChangeRate FromMicronewtonsPerSecond(double value) + public static ForceChangeRate FromMicronewtonsPerSecond(QuantityValue value) { return new ForceChangeRate(value, ForceChangeRateUnit.MicronewtonPerSecond); } @@ -465,7 +447,7 @@ public static ForceChangeRate FromMicronewtonsPerSecond(double value) /// /// Creates a from . /// - public static ForceChangeRate FromMillinewtonsPerSecond(double value) + public static ForceChangeRate FromMillinewtonsPerSecond(QuantityValue value) { return new ForceChangeRate(value, ForceChangeRateUnit.MillinewtonPerSecond); } @@ -473,7 +455,7 @@ public static ForceChangeRate FromMillinewtonsPerSecond(double value) /// /// Creates a from . /// - public static ForceChangeRate FromNanonewtonsPerSecond(double value) + public static ForceChangeRate FromNanonewtonsPerSecond(QuantityValue value) { return new ForceChangeRate(value, ForceChangeRateUnit.NanonewtonPerSecond); } @@ -481,7 +463,7 @@ public static ForceChangeRate FromNanonewtonsPerSecond(double value) /// /// Creates a from . /// - public static ForceChangeRate FromNewtonsPerMinute(double value) + public static ForceChangeRate FromNewtonsPerMinute(QuantityValue value) { return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerMinute); } @@ -489,7 +471,7 @@ public static ForceChangeRate FromNewtonsPerMinute(double value) /// /// Creates a from . /// - public static ForceChangeRate FromNewtonsPerSecond(double value) + public static ForceChangeRate FromNewtonsPerSecond(QuantityValue value) { return new ForceChangeRate(value, ForceChangeRateUnit.NewtonPerSecond); } @@ -497,7 +479,7 @@ public static ForceChangeRate FromNewtonsPerSecond(double value) /// /// Creates a from . /// - public static ForceChangeRate FromPoundsForcePerMinute(double value) + public static ForceChangeRate FromPoundsForcePerMinute(QuantityValue value) { return new ForceChangeRate(value, ForceChangeRateUnit.PoundForcePerMinute); } @@ -505,7 +487,7 @@ public static ForceChangeRate FromPoundsForcePerMinute(double value) /// /// Creates a from . /// - public static ForceChangeRate FromPoundsForcePerSecond(double value) + public static ForceChangeRate FromPoundsForcePerSecond(QuantityValue value) { return new ForceChangeRate(value, ForceChangeRateUnit.PoundForcePerSecond); } @@ -516,7 +498,7 @@ public static ForceChangeRate FromPoundsForcePerSecond(double value) /// Value to convert from. /// Unit to convert from. /// ForceChangeRate unit value. - public static ForceChangeRate From(double value, ForceChangeRateUnit fromUnit) + public static ForceChangeRate From(QuantityValue value, ForceChangeRateUnit fromUnit) { return new ForceChangeRate(value, fromUnit); } @@ -577,10 +559,7 @@ public static ForceChangeRate Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ForceChangeRate Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -608,11 +587,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ForceChangeRate /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ForceChangeRate result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -633,7 +608,7 @@ public static ForceChangeRateUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -644,7 +619,7 @@ public static ForceChangeRateUnit ParseUnit(string str, IFormatProvider? provide return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ForceChangeRateUnit unit) { return TryParseUnit(str, null, out unit); @@ -659,7 +634,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ForceChangeR /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ForceChangeRateUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -678,35 +653,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ForceChangeRate operator +(ForceChangeRate left, ForceChangeRate right) { - return new ForceChangeRate(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ForceChangeRate(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ForceChangeRate operator -(ForceChangeRate left, ForceChangeRate right) { - return new ForceChangeRate(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ForceChangeRate(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -728,97 +703,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ForceChangeRate left, ForceChangeRate right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ForceChangeRate left, ForceChangeRate right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ForceChangeRate left, ForceChangeRate right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ForceChangeRate left, ForceChangeRate right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ForceChangeRate other, ForceChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ForceChangeRate left, ForceChangeRate right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ForceChangeRate other, ForceChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ForceChangeRate left, ForceChangeRate right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ForceChangeRate other, ForceChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ForceChangeRate otherQuantity)) + if (obj is not ForceChangeRate otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ForceChangeRate other, ForceChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ForceChangeRate other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ForceChangeRate. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ForceChangeRate), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ForceChangeRate otherQuantity)) throw new ArgumentException("Expected type ForceChangeRate.", nameof(obj)); + if (obj is not ForceChangeRate otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -830,174 +790,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ForceChangeRate other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ForceChangeRateUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this ForceChangeRate to another ForceChangeRate with the unit representation . - /// - /// The unit to convert to. - /// A ForceChangeRate with the specified unit. - public ForceChangeRate ToUnit(ForceChangeRateUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ForceChangeRate with the specified unit. - public ForceChangeRate ToUnit(ForceChangeRateUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ForceChangeRate), Unit, typeof(ForceChangeRate), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ForceChangeRate)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ForceChangeRateUnit unit, [NotNullWhen(true)] out ForceChangeRate? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ForceChangeRate? convertedOrNull = (Unit, unit) switch - { - // ForceChangeRateUnit -> BaseUnit - (ForceChangeRateUnit.CentinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value) * 1e-2d, ForceChangeRateUnit.NewtonPerSecond), - (ForceChangeRateUnit.DecanewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value / 60) * 1e1d, ForceChangeRateUnit.NewtonPerSecond), - (ForceChangeRateUnit.DecanewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value) * 1e1d, ForceChangeRateUnit.NewtonPerSecond), - (ForceChangeRateUnit.DecinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value) * 1e-1d, ForceChangeRateUnit.NewtonPerSecond), - (ForceChangeRateUnit.KilonewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value / 60) * 1e3d, ForceChangeRateUnit.NewtonPerSecond), - (ForceChangeRateUnit.KilonewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value) * 1e3d, ForceChangeRateUnit.NewtonPerSecond), - (ForceChangeRateUnit.KilopoundForcePerMinute, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value * 4.4482216152605 / 60) * 1e3d, ForceChangeRateUnit.NewtonPerSecond), - (ForceChangeRateUnit.KilopoundForcePerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value * 4.4482216152605) * 1e3d, ForceChangeRateUnit.NewtonPerSecond), - (ForceChangeRateUnit.MicronewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value) * 1e-6d, ForceChangeRateUnit.NewtonPerSecond), - (ForceChangeRateUnit.MillinewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value) * 1e-3d, ForceChangeRateUnit.NewtonPerSecond), - (ForceChangeRateUnit.NanonewtonPerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate((_value) * 1e-9d, ForceChangeRateUnit.NewtonPerSecond), - (ForceChangeRateUnit.NewtonPerMinute, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate(_value / 60, ForceChangeRateUnit.NewtonPerSecond), - (ForceChangeRateUnit.PoundForcePerMinute, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate(_value * 4.4482216152605 / 60, ForceChangeRateUnit.NewtonPerSecond), - (ForceChangeRateUnit.PoundForcePerSecond, ForceChangeRateUnit.NewtonPerSecond) => new ForceChangeRate(_value * 4.4482216152605, ForceChangeRateUnit.NewtonPerSecond), - - // BaseUnit -> ForceChangeRateUnit - (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.CentinewtonPerSecond) => new ForceChangeRate((_value) / 1e-2d, ForceChangeRateUnit.CentinewtonPerSecond), - (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecanewtonPerMinute) => new ForceChangeRate((_value * 60) / 1e1d, ForceChangeRateUnit.DecanewtonPerMinute), - (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecanewtonPerSecond) => new ForceChangeRate((_value) / 1e1d, ForceChangeRateUnit.DecanewtonPerSecond), - (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.DecinewtonPerSecond) => new ForceChangeRate((_value) / 1e-1d, ForceChangeRateUnit.DecinewtonPerSecond), - (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilonewtonPerMinute) => new ForceChangeRate((_value * 60) / 1e3d, ForceChangeRateUnit.KilonewtonPerMinute), - (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilonewtonPerSecond) => new ForceChangeRate((_value) / 1e3d, ForceChangeRateUnit.KilonewtonPerSecond), - (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilopoundForcePerMinute) => new ForceChangeRate((_value / 4.4482216152605 * 60) / 1e3d, ForceChangeRateUnit.KilopoundForcePerMinute), - (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.KilopoundForcePerSecond) => new ForceChangeRate((_value / 4.4482216152605) / 1e3d, ForceChangeRateUnit.KilopoundForcePerSecond), - (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.MicronewtonPerSecond) => new ForceChangeRate((_value) / 1e-6d, ForceChangeRateUnit.MicronewtonPerSecond), - (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.MillinewtonPerSecond) => new ForceChangeRate((_value) / 1e-3d, ForceChangeRateUnit.MillinewtonPerSecond), - (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.NanonewtonPerSecond) => new ForceChangeRate((_value) / 1e-9d, ForceChangeRateUnit.NanonewtonPerSecond), - (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.NewtonPerMinute) => new ForceChangeRate(_value * 60, ForceChangeRateUnit.NewtonPerMinute), - (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.PoundForcePerMinute) => new ForceChangeRate(_value / 4.4482216152605 * 60, ForceChangeRateUnit.PoundForcePerMinute), - (ForceChangeRateUnit.NewtonPerSecond, ForceChangeRateUnit.PoundForcePerSecond) => new ForceChangeRate(_value / 4.4482216152605, ForceChangeRateUnit.PoundForcePerSecond), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ForceChangeRate ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ForceChangeRateUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForceChangeRateUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ForceChangeRateUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ForceChangeRateUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1012,7 +822,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs index 18e744827b..45bd527bf5 100644 --- a/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ForcePerLength.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// The magnitude of force per unit length. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ForcePerLength : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -61,13 +60,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ForcePerLengthUnit? _unit; /// @@ -112,7 +111,7 @@ public static ForcePerLengthInfo CreateDefault(Func - /// The for is [T^-2][M]. + /// The for is T^-2M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); @@ -127,52 +126,124 @@ public static ForcePerLengthInfo CreateDefault(FuncAn of representing the default unit mappings for ForcePerLength. public static IEnumerable> GetDefaultMappings() { - yield return new (ForcePerLengthUnit.CentinewtonPerCentimeter, "CentinewtonPerCentimeter", "CentinewtonsPerCentimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.CentinewtonPerMeter, "CentinewtonPerMeter", "CentinewtonsPerMeter", new BaseUnits(mass: MassUnit.Decagram, time: DurationUnit.Second)); - yield return new (ForcePerLengthUnit.CentinewtonPerMillimeter, "CentinewtonPerMillimeter", "CentinewtonsPerMillimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.DecanewtonPerCentimeter, "DecanewtonPerCentimeter", "DecanewtonsPerCentimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.DecanewtonPerMeter, "DecanewtonPerMeter", "DecanewtonsPerMeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.DecanewtonPerMillimeter, "DecanewtonPerMillimeter", "DecanewtonsPerMillimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.DecinewtonPerCentimeter, "DecinewtonPerCentimeter", "DecinewtonsPerCentimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.DecinewtonPerMeter, "DecinewtonPerMeter", "DecinewtonsPerMeter", new BaseUnits(mass: MassUnit.Hectogram, time: DurationUnit.Second)); - yield return new (ForcePerLengthUnit.DecinewtonPerMillimeter, "DecinewtonPerMillimeter", "DecinewtonsPerMillimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.KilogramForcePerCentimeter, "KilogramForcePerCentimeter", "KilogramsForcePerCentimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.KilogramForcePerMeter, "KilogramForcePerMeter", "KilogramsForcePerMeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.KilogramForcePerMillimeter, "KilogramForcePerMillimeter", "KilogramsForcePerMillimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.KilonewtonPerCentimeter, "KilonewtonPerCentimeter", "KilonewtonsPerCentimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.KilonewtonPerMeter, "KilonewtonPerMeter", "KilonewtonsPerMeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.KilonewtonPerMillimeter, "KilonewtonPerMillimeter", "KilonewtonsPerMillimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.KilopoundForcePerFoot, "KilopoundForcePerFoot", "KilopoundsForcePerFoot", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.KilopoundForcePerInch, "KilopoundForcePerInch", "KilopoundsForcePerInch", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.MeganewtonPerCentimeter, "MeganewtonPerCentimeter", "MeganewtonsPerCentimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.MeganewtonPerMeter, "MeganewtonPerMeter", "MeganewtonsPerMeter", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Millisecond)); - yield return new (ForcePerLengthUnit.MeganewtonPerMillimeter, "MeganewtonPerMillimeter", "MeganewtonsPerMillimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.MicronewtonPerCentimeter, "MicronewtonPerCentimeter", "MicronewtonsPerCentimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.MicronewtonPerMeter, "MicronewtonPerMeter", "MicronewtonsPerMeter", new BaseUnits(mass: MassUnit.Milligram, time: DurationUnit.Second)); - yield return new (ForcePerLengthUnit.MicronewtonPerMillimeter, "MicronewtonPerMillimeter", "MicronewtonsPerMillimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.MillinewtonPerCentimeter, "MillinewtonPerCentimeter", "MillinewtonsPerCentimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.MillinewtonPerMeter, "MillinewtonPerMeter", "MillinewtonsPerMeter", new BaseUnits(mass: MassUnit.Gram, time: DurationUnit.Second)); - yield return new (ForcePerLengthUnit.MillinewtonPerMillimeter, "MillinewtonPerMillimeter", "MillinewtonsPerMillimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.NanonewtonPerCentimeter, "NanonewtonPerCentimeter", "NanonewtonsPerCentimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.NanonewtonPerMeter, "NanonewtonPerMeter", "NanonewtonsPerMeter", new BaseUnits(mass: MassUnit.Microgram, time: DurationUnit.Second)); - yield return new (ForcePerLengthUnit.NanonewtonPerMillimeter, "NanonewtonPerMillimeter", "NanonewtonsPerMillimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.NewtonPerCentimeter, "NewtonPerCentimeter", "NewtonsPerCentimeter", BaseUnits.Undefined); + yield return new (ForcePerLengthUnit.CentinewtonPerCentimeter, "CentinewtonPerCentimeter", "CentinewtonsPerCentimeter", BaseUnits.Undefined, + 1 + ); + yield return new (ForcePerLengthUnit.CentinewtonPerMeter, "CentinewtonPerMeter", "CentinewtonsPerMeter", new BaseUnits(mass: MassUnit.Decagram, time: DurationUnit.Second), + 100 + ); + yield return new (ForcePerLengthUnit.CentinewtonPerMillimeter, "CentinewtonPerMillimeter", "CentinewtonsPerMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 10) + ); + yield return new (ForcePerLengthUnit.DecanewtonPerCentimeter, "DecanewtonPerCentimeter", "DecanewtonsPerCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (ForcePerLengthUnit.DecanewtonPerMeter, "DecanewtonPerMeter", "DecanewtonsPerMeter", BaseUnits.Undefined, + new QuantityValue(1, 10) + ); + yield return new (ForcePerLengthUnit.DecanewtonPerMillimeter, "DecanewtonPerMillimeter", "DecanewtonsPerMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 10000) + ); + yield return new (ForcePerLengthUnit.DecinewtonPerCentimeter, "DecinewtonPerCentimeter", "DecinewtonsPerCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 10) + ); + yield return new (ForcePerLengthUnit.DecinewtonPerMeter, "DecinewtonPerMeter", "DecinewtonsPerMeter", new BaseUnits(mass: MassUnit.Hectogram, time: DurationUnit.Second), + 10 + ); + yield return new (ForcePerLengthUnit.DecinewtonPerMillimeter, "DecinewtonPerMillimeter", "DecinewtonsPerMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 100) + ); + yield return new (ForcePerLengthUnit.KilogramForcePerCentimeter, "KilogramForcePerCentimeter", "KilogramsForcePerCentimeter", BaseUnits.Undefined, + new QuantityValue(200, 196133) + ); + yield return new (ForcePerLengthUnit.KilogramForcePerMeter, "KilogramForcePerMeter", "KilogramsForcePerMeter", BaseUnits.Undefined, + new QuantityValue(20000, 196133) + ); + yield return new (ForcePerLengthUnit.KilogramForcePerMillimeter, "KilogramForcePerMillimeter", "KilogramsForcePerMillimeter", BaseUnits.Undefined, + new QuantityValue(20, 196133) + ); + yield return new (ForcePerLengthUnit.KilonewtonPerCentimeter, "KilonewtonPerCentimeter", "KilonewtonsPerCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 100000) + ); + yield return new (ForcePerLengthUnit.KilonewtonPerMeter, "KilonewtonPerMeter", "KilonewtonsPerMeter", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (ForcePerLengthUnit.KilonewtonPerMillimeter, "KilonewtonPerMillimeter", "KilonewtonsPerMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 1000000) + ); + yield return new (ForcePerLengthUnit.KilopoundForcePerFoot, "KilopoundForcePerFoot", "KilopoundsForcePerFoot", BaseUnits.Undefined, + new QuantityValue(609600000, 8896443230521) + ); + yield return new (ForcePerLengthUnit.KilopoundForcePerInch, "KilopoundForcePerInch", "KilopoundsForcePerInch", BaseUnits.Undefined, + new QuantityValue(50800000, 8896443230521) + ); + yield return new (ForcePerLengthUnit.MeganewtonPerCentimeter, "MeganewtonPerCentimeter", "MeganewtonsPerCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 100000000) + ); + yield return new (ForcePerLengthUnit.MeganewtonPerMeter, "MeganewtonPerMeter", "MeganewtonsPerMeter", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Millisecond), + new QuantityValue(1, 1000000) + ); + yield return new (ForcePerLengthUnit.MeganewtonPerMillimeter, "MeganewtonPerMillimeter", "MeganewtonsPerMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 1000000000) + ); + yield return new (ForcePerLengthUnit.MicronewtonPerCentimeter, "MicronewtonPerCentimeter", "MicronewtonsPerCentimeter", BaseUnits.Undefined, + 10000 + ); + yield return new (ForcePerLengthUnit.MicronewtonPerMeter, "MicronewtonPerMeter", "MicronewtonsPerMeter", new BaseUnits(mass: MassUnit.Milligram, time: DurationUnit.Second), + 1000000 + ); + yield return new (ForcePerLengthUnit.MicronewtonPerMillimeter, "MicronewtonPerMillimeter", "MicronewtonsPerMillimeter", BaseUnits.Undefined, + 1000 + ); + yield return new (ForcePerLengthUnit.MillinewtonPerCentimeter, "MillinewtonPerCentimeter", "MillinewtonsPerCentimeter", BaseUnits.Undefined, + 10 + ); + yield return new (ForcePerLengthUnit.MillinewtonPerMeter, "MillinewtonPerMeter", "MillinewtonsPerMeter", new BaseUnits(mass: MassUnit.Gram, time: DurationUnit.Second), + 1000 + ); + yield return new (ForcePerLengthUnit.MillinewtonPerMillimeter, "MillinewtonPerMillimeter", "MillinewtonsPerMillimeter", BaseUnits.Undefined, + 1 + ); + yield return new (ForcePerLengthUnit.NanonewtonPerCentimeter, "NanonewtonPerCentimeter", "NanonewtonsPerCentimeter", BaseUnits.Undefined, + 10000000 + ); + yield return new (ForcePerLengthUnit.NanonewtonPerMeter, "NanonewtonPerMeter", "NanonewtonsPerMeter", new BaseUnits(mass: MassUnit.Microgram, time: DurationUnit.Second), + 1000000000 + ); + yield return new (ForcePerLengthUnit.NanonewtonPerMillimeter, "NanonewtonPerMillimeter", "NanonewtonsPerMillimeter", BaseUnits.Undefined, + 1000000 + ); + yield return new (ForcePerLengthUnit.NewtonPerCentimeter, "NewtonPerCentimeter", "NewtonsPerCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 100) + ); yield return new (ForcePerLengthUnit.NewtonPerMeter, "NewtonPerMeter", "NewtonsPerMeter", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ForcePerLengthUnit.NewtonPerMillimeter, "NewtonPerMillimeter", "NewtonsPerMillimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.PoundForcePerFoot, "PoundForcePerFoot", "PoundsForcePerFoot", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.PoundForcePerInch, "PoundForcePerInch", "PoundsForcePerInch", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.PoundForcePerYard, "PoundForcePerYard", "PoundsForcePerYard", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.TonneForcePerCentimeter, "TonneForcePerCentimeter", "TonnesForcePerCentimeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.TonneForcePerMeter, "TonneForcePerMeter", "TonnesForcePerMeter", BaseUnits.Undefined); - yield return new (ForcePerLengthUnit.TonneForcePerMillimeter, "TonneForcePerMillimeter", "TonnesForcePerMillimeter", BaseUnits.Undefined); + yield return new (ForcePerLengthUnit.NewtonPerMillimeter, "NewtonPerMillimeter", "NewtonsPerMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (ForcePerLengthUnit.PoundForcePerFoot, "PoundForcePerFoot", "PoundsForcePerFoot", BaseUnits.Undefined, + new QuantityValue(609600000000, 8896443230521) + ); + yield return new (ForcePerLengthUnit.PoundForcePerInch, "PoundForcePerInch", "PoundsForcePerInch", BaseUnits.Undefined, + new QuantityValue(50800000000, 8896443230521) + ); + yield return new (ForcePerLengthUnit.PoundForcePerYard, "PoundForcePerYard", "PoundsForcePerYard", BaseUnits.Undefined, + new QuantityValue(1828800000000, 8896443230521) + ); + yield return new (ForcePerLengthUnit.TonneForcePerCentimeter, "TonneForcePerCentimeter", "TonnesForcePerCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 980665) + ); + yield return new (ForcePerLengthUnit.TonneForcePerMeter, "TonneForcePerMeter", "TonnesForcePerMeter", BaseUnits.Undefined, + new QuantityValue(20, 196133) + ); + yield return new (ForcePerLengthUnit.TonneForcePerMillimeter, "TonneForcePerMillimeter", "TonnesForcePerMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 9806650) + ); } } static ForcePerLength() { - Info = ForcePerLengthInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ForcePerLengthInfo.CreateDefault); } /// @@ -180,7 +251,7 @@ static ForcePerLength() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ForcePerLength(double value, ForcePerLengthUnit unit) + public ForcePerLength(QuantityValue value, ForcePerLengthUnit unit) { _value = value; _unit = unit; @@ -194,7 +265,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -205,7 +276,8 @@ public ForcePerLength(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -234,10 +306,8 @@ public ForcePerLength(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ForcePerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -276,287 +346,199 @@ public ForcePerLength(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentinewtonsPerCentimeter => As(ForcePerLengthUnit.CentinewtonPerCentimeter); + public QuantityValue CentinewtonsPerCentimeter => this.As(ForcePerLengthUnit.CentinewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentinewtonsPerMeter => As(ForcePerLengthUnit.CentinewtonPerMeter); + public QuantityValue CentinewtonsPerMeter => this.As(ForcePerLengthUnit.CentinewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentinewtonsPerMillimeter => As(ForcePerLengthUnit.CentinewtonPerMillimeter); + public QuantityValue CentinewtonsPerMillimeter => this.As(ForcePerLengthUnit.CentinewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecanewtonsPerCentimeter => As(ForcePerLengthUnit.DecanewtonPerCentimeter); + public QuantityValue DecanewtonsPerCentimeter => this.As(ForcePerLengthUnit.DecanewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecanewtonsPerMeter => As(ForcePerLengthUnit.DecanewtonPerMeter); + public QuantityValue DecanewtonsPerMeter => this.As(ForcePerLengthUnit.DecanewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecanewtonsPerMillimeter => As(ForcePerLengthUnit.DecanewtonPerMillimeter); + public QuantityValue DecanewtonsPerMillimeter => this.As(ForcePerLengthUnit.DecanewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecinewtonsPerCentimeter => As(ForcePerLengthUnit.DecinewtonPerCentimeter); + public QuantityValue DecinewtonsPerCentimeter => this.As(ForcePerLengthUnit.DecinewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecinewtonsPerMeter => As(ForcePerLengthUnit.DecinewtonPerMeter); + public QuantityValue DecinewtonsPerMeter => this.As(ForcePerLengthUnit.DecinewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecinewtonsPerMillimeter => As(ForcePerLengthUnit.DecinewtonPerMillimeter); + public QuantityValue DecinewtonsPerMillimeter => this.As(ForcePerLengthUnit.DecinewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsForcePerCentimeter => As(ForcePerLengthUnit.KilogramForcePerCentimeter); + public QuantityValue KilogramsForcePerCentimeter => this.As(ForcePerLengthUnit.KilogramForcePerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsForcePerMeter => As(ForcePerLengthUnit.KilogramForcePerMeter); + public QuantityValue KilogramsForcePerMeter => this.As(ForcePerLengthUnit.KilogramForcePerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsForcePerMillimeter => As(ForcePerLengthUnit.KilogramForcePerMillimeter); + public QuantityValue KilogramsForcePerMillimeter => this.As(ForcePerLengthUnit.KilogramForcePerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonsPerCentimeter => As(ForcePerLengthUnit.KilonewtonPerCentimeter); + public QuantityValue KilonewtonsPerCentimeter => this.As(ForcePerLengthUnit.KilonewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonsPerMeter => As(ForcePerLengthUnit.KilonewtonPerMeter); + public QuantityValue KilonewtonsPerMeter => this.As(ForcePerLengthUnit.KilonewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonsPerMillimeter => As(ForcePerLengthUnit.KilonewtonPerMillimeter); + public QuantityValue KilonewtonsPerMillimeter => this.As(ForcePerLengthUnit.KilonewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsForcePerFoot => As(ForcePerLengthUnit.KilopoundForcePerFoot); + public QuantityValue KilopoundsForcePerFoot => this.As(ForcePerLengthUnit.KilopoundForcePerFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsForcePerInch => As(ForcePerLengthUnit.KilopoundForcePerInch); + public QuantityValue KilopoundsForcePerInch => this.As(ForcePerLengthUnit.KilopoundForcePerInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MeganewtonsPerCentimeter => As(ForcePerLengthUnit.MeganewtonPerCentimeter); + public QuantityValue MeganewtonsPerCentimeter => this.As(ForcePerLengthUnit.MeganewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MeganewtonsPerMeter => As(ForcePerLengthUnit.MeganewtonPerMeter); + public QuantityValue MeganewtonsPerMeter => this.As(ForcePerLengthUnit.MeganewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MeganewtonsPerMillimeter => As(ForcePerLengthUnit.MeganewtonPerMillimeter); + public QuantityValue MeganewtonsPerMillimeter => this.As(ForcePerLengthUnit.MeganewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicronewtonsPerCentimeter => As(ForcePerLengthUnit.MicronewtonPerCentimeter); + public QuantityValue MicronewtonsPerCentimeter => this.As(ForcePerLengthUnit.MicronewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicronewtonsPerMeter => As(ForcePerLengthUnit.MicronewtonPerMeter); + public QuantityValue MicronewtonsPerMeter => this.As(ForcePerLengthUnit.MicronewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicronewtonsPerMillimeter => As(ForcePerLengthUnit.MicronewtonPerMillimeter); + public QuantityValue MicronewtonsPerMillimeter => this.As(ForcePerLengthUnit.MicronewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillinewtonsPerCentimeter => As(ForcePerLengthUnit.MillinewtonPerCentimeter); + public QuantityValue MillinewtonsPerCentimeter => this.As(ForcePerLengthUnit.MillinewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillinewtonsPerMeter => As(ForcePerLengthUnit.MillinewtonPerMeter); + public QuantityValue MillinewtonsPerMeter => this.As(ForcePerLengthUnit.MillinewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillinewtonsPerMillimeter => As(ForcePerLengthUnit.MillinewtonPerMillimeter); + public QuantityValue MillinewtonsPerMillimeter => this.As(ForcePerLengthUnit.MillinewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanonewtonsPerCentimeter => As(ForcePerLengthUnit.NanonewtonPerCentimeter); + public QuantityValue NanonewtonsPerCentimeter => this.As(ForcePerLengthUnit.NanonewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanonewtonsPerMeter => As(ForcePerLengthUnit.NanonewtonPerMeter); + public QuantityValue NanonewtonsPerMeter => this.As(ForcePerLengthUnit.NanonewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanonewtonsPerMillimeter => As(ForcePerLengthUnit.NanonewtonPerMillimeter); + public QuantityValue NanonewtonsPerMillimeter => this.As(ForcePerLengthUnit.NanonewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonsPerCentimeter => As(ForcePerLengthUnit.NewtonPerCentimeter); + public QuantityValue NewtonsPerCentimeter => this.As(ForcePerLengthUnit.NewtonPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonsPerMeter => As(ForcePerLengthUnit.NewtonPerMeter); + public QuantityValue NewtonsPerMeter => this.As(ForcePerLengthUnit.NewtonPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonsPerMillimeter => As(ForcePerLengthUnit.NewtonPerMillimeter); + public QuantityValue NewtonsPerMillimeter => this.As(ForcePerLengthUnit.NewtonPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsForcePerFoot => As(ForcePerLengthUnit.PoundForcePerFoot); + public QuantityValue PoundsForcePerFoot => this.As(ForcePerLengthUnit.PoundForcePerFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsForcePerInch => As(ForcePerLengthUnit.PoundForcePerInch); + public QuantityValue PoundsForcePerInch => this.As(ForcePerLengthUnit.PoundForcePerInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsForcePerYard => As(ForcePerLengthUnit.PoundForcePerYard); + public QuantityValue PoundsForcePerYard => this.As(ForcePerLengthUnit.PoundForcePerYard); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesForcePerCentimeter => As(ForcePerLengthUnit.TonneForcePerCentimeter); + public QuantityValue TonnesForcePerCentimeter => this.As(ForcePerLengthUnit.TonneForcePerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesForcePerMeter => As(ForcePerLengthUnit.TonneForcePerMeter); + public QuantityValue TonnesForcePerMeter => this.As(ForcePerLengthUnit.TonneForcePerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesForcePerMillimeter => As(ForcePerLengthUnit.TonneForcePerMillimeter); + public QuantityValue TonnesForcePerMillimeter => this.As(ForcePerLengthUnit.TonneForcePerMillimeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ForcePerLengthUnit -> BaseUnit - unitConverter.SetConversionFunction(ForcePerLengthUnit.CentinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.CentinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.CentinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.DecanewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.DecanewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.DecanewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.DecinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.DecinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.DecinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.KilogramForcePerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.KilogramForcePerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.KilogramForcePerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.KilonewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.KilonewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.KilonewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.KilopoundForcePerFoot, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.KilopoundForcePerInch, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MeganewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MeganewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MeganewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MicronewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MicronewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MicronewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MillinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MillinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.MillinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NanonewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NanonewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NanonewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.PoundForcePerFoot, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.PoundForcePerInch, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.PoundForcePerYard, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.TonneForcePerCentimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.TonneForcePerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.TonneForcePerMillimeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> ForcePerLengthUnit - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.CentinewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.CentinewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.CentinewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecanewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecanewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecanewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecinewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecinewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.DecinewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilogramForcePerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilogramForcePerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilogramForcePerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilonewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilonewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.KilonewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilopoundForcePerFoot, quantity => quantity.ToUnit(ForcePerLengthUnit.KilopoundForcePerFoot)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilopoundForcePerInch, quantity => quantity.ToUnit(ForcePerLengthUnit.KilopoundForcePerInch)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MeganewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MeganewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MeganewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MicronewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MicronewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MicronewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MillinewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MillinewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.MillinewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NanonewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NanonewtonPerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NanonewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NewtonPerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NewtonPerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.NewtonPerMillimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerFoot, quantity => quantity.ToUnit(ForcePerLengthUnit.PoundForcePerFoot)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerInch, quantity => quantity.ToUnit(ForcePerLengthUnit.PoundForcePerInch)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerYard, quantity => quantity.ToUnit(ForcePerLengthUnit.PoundForcePerYard)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerCentimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.TonneForcePerCentimeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerMeter, quantity => quantity.ToUnit(ForcePerLengthUnit.TonneForcePerMeter)); - unitConverter.SetConversionFunction(ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerMillimeter, quantity => quantity.ToUnit(ForcePerLengthUnit.TonneForcePerMillimeter)); - } - /// /// Get unit abbreviation string. /// @@ -585,7 +567,7 @@ public static string GetAbbreviation(ForcePerLengthUnit unit, IFormatProvider? p /// /// Creates a from . /// - public static ForcePerLength FromCentinewtonsPerCentimeter(double value) + public static ForcePerLength FromCentinewtonsPerCentimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerCentimeter); } @@ -593,7 +575,7 @@ public static ForcePerLength FromCentinewtonsPerCentimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromCentinewtonsPerMeter(double value) + public static ForcePerLength FromCentinewtonsPerMeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerMeter); } @@ -601,7 +583,7 @@ public static ForcePerLength FromCentinewtonsPerMeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromCentinewtonsPerMillimeter(double value) + public static ForcePerLength FromCentinewtonsPerMillimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.CentinewtonPerMillimeter); } @@ -609,7 +591,7 @@ public static ForcePerLength FromCentinewtonsPerMillimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromDecanewtonsPerCentimeter(double value) + public static ForcePerLength FromDecanewtonsPerCentimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.DecanewtonPerCentimeter); } @@ -617,7 +599,7 @@ public static ForcePerLength FromDecanewtonsPerCentimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromDecanewtonsPerMeter(double value) + public static ForcePerLength FromDecanewtonsPerMeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.DecanewtonPerMeter); } @@ -625,7 +607,7 @@ public static ForcePerLength FromDecanewtonsPerMeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromDecanewtonsPerMillimeter(double value) + public static ForcePerLength FromDecanewtonsPerMillimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.DecanewtonPerMillimeter); } @@ -633,7 +615,7 @@ public static ForcePerLength FromDecanewtonsPerMillimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromDecinewtonsPerCentimeter(double value) + public static ForcePerLength FromDecinewtonsPerCentimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerCentimeter); } @@ -641,7 +623,7 @@ public static ForcePerLength FromDecinewtonsPerCentimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromDecinewtonsPerMeter(double value) + public static ForcePerLength FromDecinewtonsPerMeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerMeter); } @@ -649,7 +631,7 @@ public static ForcePerLength FromDecinewtonsPerMeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromDecinewtonsPerMillimeter(double value) + public static ForcePerLength FromDecinewtonsPerMillimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.DecinewtonPerMillimeter); } @@ -657,7 +639,7 @@ public static ForcePerLength FromDecinewtonsPerMillimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromKilogramsForcePerCentimeter(double value) + public static ForcePerLength FromKilogramsForcePerCentimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerCentimeter); } @@ -665,7 +647,7 @@ public static ForcePerLength FromKilogramsForcePerCentimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromKilogramsForcePerMeter(double value) + public static ForcePerLength FromKilogramsForcePerMeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerMeter); } @@ -673,7 +655,7 @@ public static ForcePerLength FromKilogramsForcePerMeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromKilogramsForcePerMillimeter(double value) + public static ForcePerLength FromKilogramsForcePerMillimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.KilogramForcePerMillimeter); } @@ -681,7 +663,7 @@ public static ForcePerLength FromKilogramsForcePerMillimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromKilonewtonsPerCentimeter(double value) + public static ForcePerLength FromKilonewtonsPerCentimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerCentimeter); } @@ -689,7 +671,7 @@ public static ForcePerLength FromKilonewtonsPerCentimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromKilonewtonsPerMeter(double value) + public static ForcePerLength FromKilonewtonsPerMeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerMeter); } @@ -697,7 +679,7 @@ public static ForcePerLength FromKilonewtonsPerMeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromKilonewtonsPerMillimeter(double value) + public static ForcePerLength FromKilonewtonsPerMillimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.KilonewtonPerMillimeter); } @@ -705,7 +687,7 @@ public static ForcePerLength FromKilonewtonsPerMillimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromKilopoundsForcePerFoot(double value) + public static ForcePerLength FromKilopoundsForcePerFoot(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.KilopoundForcePerFoot); } @@ -713,7 +695,7 @@ public static ForcePerLength FromKilopoundsForcePerFoot(double value) /// /// Creates a from . /// - public static ForcePerLength FromKilopoundsForcePerInch(double value) + public static ForcePerLength FromKilopoundsForcePerInch(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.KilopoundForcePerInch); } @@ -721,7 +703,7 @@ public static ForcePerLength FromKilopoundsForcePerInch(double value) /// /// Creates a from . /// - public static ForcePerLength FromMeganewtonsPerCentimeter(double value) + public static ForcePerLength FromMeganewtonsPerCentimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerCentimeter); } @@ -729,7 +711,7 @@ public static ForcePerLength FromMeganewtonsPerCentimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromMeganewtonsPerMeter(double value) + public static ForcePerLength FromMeganewtonsPerMeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerMeter); } @@ -737,7 +719,7 @@ public static ForcePerLength FromMeganewtonsPerMeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromMeganewtonsPerMillimeter(double value) + public static ForcePerLength FromMeganewtonsPerMillimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.MeganewtonPerMillimeter); } @@ -745,7 +727,7 @@ public static ForcePerLength FromMeganewtonsPerMillimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromMicronewtonsPerCentimeter(double value) + public static ForcePerLength FromMicronewtonsPerCentimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerCentimeter); } @@ -753,7 +735,7 @@ public static ForcePerLength FromMicronewtonsPerCentimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromMicronewtonsPerMeter(double value) + public static ForcePerLength FromMicronewtonsPerMeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerMeter); } @@ -761,7 +743,7 @@ public static ForcePerLength FromMicronewtonsPerMeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromMicronewtonsPerMillimeter(double value) + public static ForcePerLength FromMicronewtonsPerMillimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.MicronewtonPerMillimeter); } @@ -769,7 +751,7 @@ public static ForcePerLength FromMicronewtonsPerMillimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromMillinewtonsPerCentimeter(double value) + public static ForcePerLength FromMillinewtonsPerCentimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerCentimeter); } @@ -777,7 +759,7 @@ public static ForcePerLength FromMillinewtonsPerCentimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromMillinewtonsPerMeter(double value) + public static ForcePerLength FromMillinewtonsPerMeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerMeter); } @@ -785,7 +767,7 @@ public static ForcePerLength FromMillinewtonsPerMeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromMillinewtonsPerMillimeter(double value) + public static ForcePerLength FromMillinewtonsPerMillimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.MillinewtonPerMillimeter); } @@ -793,7 +775,7 @@ public static ForcePerLength FromMillinewtonsPerMillimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromNanonewtonsPerCentimeter(double value) + public static ForcePerLength FromNanonewtonsPerCentimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerCentimeter); } @@ -801,7 +783,7 @@ public static ForcePerLength FromNanonewtonsPerCentimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromNanonewtonsPerMeter(double value) + public static ForcePerLength FromNanonewtonsPerMeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerMeter); } @@ -809,7 +791,7 @@ public static ForcePerLength FromNanonewtonsPerMeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromNanonewtonsPerMillimeter(double value) + public static ForcePerLength FromNanonewtonsPerMillimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.NanonewtonPerMillimeter); } @@ -817,7 +799,7 @@ public static ForcePerLength FromNanonewtonsPerMillimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromNewtonsPerCentimeter(double value) + public static ForcePerLength FromNewtonsPerCentimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.NewtonPerCentimeter); } @@ -825,7 +807,7 @@ public static ForcePerLength FromNewtonsPerCentimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromNewtonsPerMeter(double value) + public static ForcePerLength FromNewtonsPerMeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.NewtonPerMeter); } @@ -833,7 +815,7 @@ public static ForcePerLength FromNewtonsPerMeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromNewtonsPerMillimeter(double value) + public static ForcePerLength FromNewtonsPerMillimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.NewtonPerMillimeter); } @@ -841,7 +823,7 @@ public static ForcePerLength FromNewtonsPerMillimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromPoundsForcePerFoot(double value) + public static ForcePerLength FromPoundsForcePerFoot(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.PoundForcePerFoot); } @@ -849,7 +831,7 @@ public static ForcePerLength FromPoundsForcePerFoot(double value) /// /// Creates a from . /// - public static ForcePerLength FromPoundsForcePerInch(double value) + public static ForcePerLength FromPoundsForcePerInch(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.PoundForcePerInch); } @@ -857,7 +839,7 @@ public static ForcePerLength FromPoundsForcePerInch(double value) /// /// Creates a from . /// - public static ForcePerLength FromPoundsForcePerYard(double value) + public static ForcePerLength FromPoundsForcePerYard(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.PoundForcePerYard); } @@ -865,7 +847,7 @@ public static ForcePerLength FromPoundsForcePerYard(double value) /// /// Creates a from . /// - public static ForcePerLength FromTonnesForcePerCentimeter(double value) + public static ForcePerLength FromTonnesForcePerCentimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.TonneForcePerCentimeter); } @@ -873,7 +855,7 @@ public static ForcePerLength FromTonnesForcePerCentimeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromTonnesForcePerMeter(double value) + public static ForcePerLength FromTonnesForcePerMeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.TonneForcePerMeter); } @@ -881,7 +863,7 @@ public static ForcePerLength FromTonnesForcePerMeter(double value) /// /// Creates a from . /// - public static ForcePerLength FromTonnesForcePerMillimeter(double value) + public static ForcePerLength FromTonnesForcePerMillimeter(QuantityValue value) { return new ForcePerLength(value, ForcePerLengthUnit.TonneForcePerMillimeter); } @@ -892,7 +874,7 @@ public static ForcePerLength FromTonnesForcePerMillimeter(double value) /// Value to convert from. /// Unit to convert from. /// ForcePerLength unit value. - public static ForcePerLength From(double value, ForcePerLengthUnit fromUnit) + public static ForcePerLength From(QuantityValue value, ForcePerLengthUnit fromUnit) { return new ForcePerLength(value, fromUnit); } @@ -953,10 +935,7 @@ public static ForcePerLength Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ForcePerLength Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -984,11 +963,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ForcePerLength r /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ForcePerLength result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -1009,7 +984,7 @@ public static ForcePerLengthUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -1020,7 +995,7 @@ public static ForcePerLengthUnit ParseUnit(string str, IFormatProvider? provider return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ForcePerLengthUnit unit) { return TryParseUnit(str, null, out unit); @@ -1035,7 +1010,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ForcePerLeng /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ForcePerLengthUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -1054,35 +1029,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ForcePerLength operator +(ForcePerLength left, ForcePerLength right) { - return new ForcePerLength(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ForcePerLength(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ForcePerLength operator -(ForcePerLength left, ForcePerLength right) { - return new ForcePerLength(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ForcePerLength(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -1152,97 +1127,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ForcePerLength left, ForcePerLength right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ForcePerLength left, ForcePerLength right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ForcePerLength left, ForcePerLength right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ForcePerLength left, ForcePerLength right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ForcePerLength other, ForcePerLength tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ForcePerLength left, ForcePerLength right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ForcePerLength other, ForcePerLength tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ForcePerLength left, ForcePerLength right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ForcePerLength other, ForcePerLength tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ForcePerLength otherQuantity)) + if (obj is not ForcePerLength otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ForcePerLength other, ForcePerLength tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ForcePerLength other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ForcePerLength. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ForcePerLength), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ForcePerLength otherQuantity)) throw new ArgumentException("Expected type ForcePerLength.", nameof(obj)); + if (obj is not ForcePerLength otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1254,220 +1214,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ForcePerLength other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ForcePerLengthUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this ForcePerLength to another ForcePerLength with the unit representation . - /// - /// The unit to convert to. - /// A ForcePerLength with the specified unit. - public ForcePerLength ToUnit(ForcePerLengthUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ForcePerLength with the specified unit. - public ForcePerLength ToUnit(ForcePerLengthUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ForcePerLength), Unit, typeof(ForcePerLength), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ForcePerLength)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ForcePerLengthUnit unit, [NotNullWhen(true)] out ForcePerLength? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ForcePerLength? convertedOrNull = (Unit, unit) switch - { - // ForcePerLengthUnit -> BaseUnit - (ForcePerLengthUnit.CentinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e2) * 1e-2d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.CentinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value) * 1e-2d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.CentinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e3) * 1e-2d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.DecanewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e2) * 1e1d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.DecanewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value) * 1e1d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.DecanewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e3) * 1e1d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.DecinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e2) * 1e-1d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.DecinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value) * 1e-1d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.DecinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e3) * 1e-1d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.KilogramForcePerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 980.665, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.KilogramForcePerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 9.80665, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.KilogramForcePerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 9.80665e3, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.KilonewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e2) * 1e3d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.KilonewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value) * 1e3d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.KilonewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e3) * 1e3d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.KilopoundForcePerFoot, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 4.4482216152605 / 0.3048e-3, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.KilopoundForcePerInch, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 4.4482216152605 / 2.54e-5, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.MeganewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e2) * 1e6d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.MeganewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value) * 1e6d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.MeganewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e3) * 1e6d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.MicronewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e2) * 1e-6d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.MicronewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value) * 1e-6d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.MicronewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e3) * 1e-6d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.MillinewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e2) * 1e-3d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.MillinewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value) * 1e-3d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.MillinewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e3) * 1e-3d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.NanonewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e2) * 1e-9d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.NanonewtonPerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value) * 1e-9d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.NanonewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength((_value * 1e3) * 1e-9d, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.NewtonPerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 1e2, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.NewtonPerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 1e3, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.PoundForcePerFoot, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 4.4482216152605 / 0.3048, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.PoundForcePerInch, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 4.4482216152605 / 2.54e-2, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.PoundForcePerYard, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 4.4482216152605 / 0.9144, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.TonneForcePerCentimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 9.80665e5, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.TonneForcePerMeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 9.80665e3, ForcePerLengthUnit.NewtonPerMeter), - (ForcePerLengthUnit.TonneForcePerMillimeter, ForcePerLengthUnit.NewtonPerMeter) => new ForcePerLength(_value * 9.80665e6, ForcePerLengthUnit.NewtonPerMeter), - - // BaseUnit -> ForcePerLengthUnit - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerCentimeter) => new ForcePerLength((_value / 1e2) / 1e-2d, ForcePerLengthUnit.CentinewtonPerCentimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerMeter) => new ForcePerLength((_value) / 1e-2d, ForcePerLengthUnit.CentinewtonPerMeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.CentinewtonPerMillimeter) => new ForcePerLength((_value / 1e3) / 1e-2d, ForcePerLengthUnit.CentinewtonPerMillimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerCentimeter) => new ForcePerLength((_value / 1e2) / 1e1d, ForcePerLengthUnit.DecanewtonPerCentimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerMeter) => new ForcePerLength((_value) / 1e1d, ForcePerLengthUnit.DecanewtonPerMeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecanewtonPerMillimeter) => new ForcePerLength((_value / 1e3) / 1e1d, ForcePerLengthUnit.DecanewtonPerMillimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerCentimeter) => new ForcePerLength((_value / 1e2) / 1e-1d, ForcePerLengthUnit.DecinewtonPerCentimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerMeter) => new ForcePerLength((_value) / 1e-1d, ForcePerLengthUnit.DecinewtonPerMeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.DecinewtonPerMillimeter) => new ForcePerLength((_value / 1e3) / 1e-1d, ForcePerLengthUnit.DecinewtonPerMillimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerCentimeter) => new ForcePerLength(_value / 980.665, ForcePerLengthUnit.KilogramForcePerCentimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerMeter) => new ForcePerLength(_value / 9.80665, ForcePerLengthUnit.KilogramForcePerMeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilogramForcePerMillimeter) => new ForcePerLength(_value / 9.80665e3, ForcePerLengthUnit.KilogramForcePerMillimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerCentimeter) => new ForcePerLength((_value / 1e2) / 1e3d, ForcePerLengthUnit.KilonewtonPerCentimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerMeter) => new ForcePerLength((_value) / 1e3d, ForcePerLengthUnit.KilonewtonPerMeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilonewtonPerMillimeter) => new ForcePerLength((_value / 1e3) / 1e3d, ForcePerLengthUnit.KilonewtonPerMillimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilopoundForcePerFoot) => new ForcePerLength(_value * 0.3048e-3 / 4.4482216152605, ForcePerLengthUnit.KilopoundForcePerFoot), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.KilopoundForcePerInch) => new ForcePerLength(_value * 2.54e-5 / 4.4482216152605, ForcePerLengthUnit.KilopoundForcePerInch), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerCentimeter) => new ForcePerLength((_value / 1e2) / 1e6d, ForcePerLengthUnit.MeganewtonPerCentimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerMeter) => new ForcePerLength((_value) / 1e6d, ForcePerLengthUnit.MeganewtonPerMeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MeganewtonPerMillimeter) => new ForcePerLength((_value / 1e3) / 1e6d, ForcePerLengthUnit.MeganewtonPerMillimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerCentimeter) => new ForcePerLength((_value / 1e2) / 1e-6d, ForcePerLengthUnit.MicronewtonPerCentimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerMeter) => new ForcePerLength((_value) / 1e-6d, ForcePerLengthUnit.MicronewtonPerMeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MicronewtonPerMillimeter) => new ForcePerLength((_value / 1e3) / 1e-6d, ForcePerLengthUnit.MicronewtonPerMillimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerCentimeter) => new ForcePerLength((_value / 1e2) / 1e-3d, ForcePerLengthUnit.MillinewtonPerCentimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerMeter) => new ForcePerLength((_value) / 1e-3d, ForcePerLengthUnit.MillinewtonPerMeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.MillinewtonPerMillimeter) => new ForcePerLength((_value / 1e3) / 1e-3d, ForcePerLengthUnit.MillinewtonPerMillimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerCentimeter) => new ForcePerLength((_value / 1e2) / 1e-9d, ForcePerLengthUnit.NanonewtonPerCentimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerMeter) => new ForcePerLength((_value) / 1e-9d, ForcePerLengthUnit.NanonewtonPerMeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NanonewtonPerMillimeter) => new ForcePerLength((_value / 1e3) / 1e-9d, ForcePerLengthUnit.NanonewtonPerMillimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NewtonPerCentimeter) => new ForcePerLength(_value / 1e2, ForcePerLengthUnit.NewtonPerCentimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.NewtonPerMillimeter) => new ForcePerLength(_value / 1e3, ForcePerLengthUnit.NewtonPerMillimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerFoot) => new ForcePerLength(_value * 0.3048 / 4.4482216152605, ForcePerLengthUnit.PoundForcePerFoot), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerInch) => new ForcePerLength(_value * 2.54e-2 / 4.4482216152605, ForcePerLengthUnit.PoundForcePerInch), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.PoundForcePerYard) => new ForcePerLength(_value * 0.9144 / 4.4482216152605, ForcePerLengthUnit.PoundForcePerYard), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerCentimeter) => new ForcePerLength(_value / 9.80665e5, ForcePerLengthUnit.TonneForcePerCentimeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerMeter) => new ForcePerLength(_value / 9.80665e3, ForcePerLengthUnit.TonneForcePerMeter), - (ForcePerLengthUnit.NewtonPerMeter, ForcePerLengthUnit.TonneForcePerMillimeter) => new ForcePerLength(_value / 9.80665e6, ForcePerLengthUnit.TonneForcePerMillimeter), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ForcePerLength ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ForcePerLengthUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ForcePerLengthUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ForcePerLengthUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ForcePerLengthUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1482,7 +1246,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs b/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs index 0fafe817fc..d187768861 100644 --- a/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Frequency.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// The number of occurrences of a repeating event per unit time. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Frequency : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly FrequencyUnit? _unit; /// @@ -104,7 +103,7 @@ public static FrequencyInfo CreateDefault(Func - /// The for is [T^-1]. + /// The for is T^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); @@ -119,26 +118,46 @@ public static FrequencyInfo CreateDefault(FuncAn of representing the default unit mappings for Frequency. public static IEnumerable> GetDefaultMappings() { - yield return new (FrequencyUnit.BeatPerMinute, "BeatPerMinute", "BeatsPerMinute", new BaseUnits(time: DurationUnit.Minute)); - yield return new (FrequencyUnit.CyclePerHour, "CyclePerHour", "CyclesPerHour", new BaseUnits(time: DurationUnit.Hour)); - yield return new (FrequencyUnit.CyclePerMinute, "CyclePerMinute", "CyclesPerMinute", new BaseUnits(time: DurationUnit.Minute)); - yield return new (FrequencyUnit.Gigahertz, "Gigahertz", "Gigahertz", new BaseUnits(time: DurationUnit.Nanosecond)); + yield return new (FrequencyUnit.BeatPerMinute, "BeatPerMinute", "BeatsPerMinute", new BaseUnits(time: DurationUnit.Minute), + 60 + ); + yield return new (FrequencyUnit.CyclePerHour, "CyclePerHour", "CyclesPerHour", new BaseUnits(time: DurationUnit.Hour), + 3600 + ); + yield return new (FrequencyUnit.CyclePerMinute, "CyclePerMinute", "CyclesPerMinute", new BaseUnits(time: DurationUnit.Minute), + 60 + ); + yield return new (FrequencyUnit.Gigahertz, "Gigahertz", "Gigahertz", new BaseUnits(time: DurationUnit.Nanosecond), + new QuantityValue(1, 1000000000) + ); yield return new (FrequencyUnit.Hertz, "Hertz", "Hertz", new BaseUnits(time: DurationUnit.Second)); - yield return new (FrequencyUnit.Kilohertz, "Kilohertz", "Kilohertz", new BaseUnits(time: DurationUnit.Millisecond)); - yield return new (FrequencyUnit.Megahertz, "Megahertz", "Megahertz", new BaseUnits(time: DurationUnit.Microsecond)); - yield return new (FrequencyUnit.Microhertz, "Microhertz", "Microhertz", BaseUnits.Undefined); - yield return new (FrequencyUnit.Millihertz, "Millihertz", "Millihertz", BaseUnits.Undefined); - yield return new (FrequencyUnit.PerSecond, "PerSecond", "PerSecond", new BaseUnits(time: DurationUnit.Second)); - yield return new (FrequencyUnit.RadianPerSecond, "RadianPerSecond", "RadiansPerSecond", BaseUnits.Undefined); - yield return new (FrequencyUnit.Terahertz, "Terahertz", "Terahertz", new BaseUnits(time: DurationUnit.Picosecond)); + yield return new (FrequencyUnit.Kilohertz, "Kilohertz", "Kilohertz", new BaseUnits(time: DurationUnit.Millisecond), + new QuantityValue(1, 1000) + ); + yield return new (FrequencyUnit.Megahertz, "Megahertz", "Megahertz", new BaseUnits(time: DurationUnit.Microsecond), + new QuantityValue(1, 1000000) + ); + yield return new (FrequencyUnit.Microhertz, "Microhertz", "Microhertz", BaseUnits.Undefined, + 1000000 + ); + yield return new (FrequencyUnit.Millihertz, "Millihertz", "Millihertz", BaseUnits.Undefined, + 1000 + ); + yield return new (FrequencyUnit.PerSecond, "PerSecond", "PerSecond", new BaseUnits(time: DurationUnit.Second), + 1 + ); + yield return new (FrequencyUnit.RadianPerSecond, "RadianPerSecond", "RadiansPerSecond", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 500000000000000) + ); + yield return new (FrequencyUnit.Terahertz, "Terahertz", "Terahertz", new BaseUnits(time: DurationUnit.Picosecond), + new QuantityValue(1, 1000000000000) + ); } } static Frequency() { - Info = FrequencyInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(FrequencyInfo.CreateDefault); } /// @@ -146,7 +165,7 @@ static Frequency() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Frequency(double value, FrequencyUnit unit) + public Frequency(QuantityValue value, FrequencyUnit unit) { _value = value; _unit = unit; @@ -160,7 +179,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -171,7 +190,8 @@ public Frequency(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -200,10 +220,8 @@ public Frequency(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public FrequencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -242,105 +260,69 @@ public Frequency(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BeatsPerMinute => As(FrequencyUnit.BeatPerMinute); + public QuantityValue BeatsPerMinute => this.As(FrequencyUnit.BeatPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CyclesPerHour => As(FrequencyUnit.CyclePerHour); + public QuantityValue CyclesPerHour => this.As(FrequencyUnit.CyclePerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CyclesPerMinute => As(FrequencyUnit.CyclePerMinute); + public QuantityValue CyclesPerMinute => this.As(FrequencyUnit.CyclePerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigahertz => As(FrequencyUnit.Gigahertz); + public QuantityValue Gigahertz => this.As(FrequencyUnit.Gigahertz); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Hertz => As(FrequencyUnit.Hertz); + public QuantityValue Hertz => this.As(FrequencyUnit.Hertz); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilohertz => As(FrequencyUnit.Kilohertz); + public QuantityValue Kilohertz => this.As(FrequencyUnit.Kilohertz); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megahertz => As(FrequencyUnit.Megahertz); + public QuantityValue Megahertz => this.As(FrequencyUnit.Megahertz); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microhertz => As(FrequencyUnit.Microhertz); + public QuantityValue Microhertz => this.As(FrequencyUnit.Microhertz); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millihertz => As(FrequencyUnit.Millihertz); + public QuantityValue Millihertz => this.As(FrequencyUnit.Millihertz); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PerSecond => As(FrequencyUnit.PerSecond); + public QuantityValue PerSecond => this.As(FrequencyUnit.PerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double RadiansPerSecond => As(FrequencyUnit.RadianPerSecond); + public QuantityValue RadiansPerSecond => this.As(FrequencyUnit.RadianPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Terahertz => As(FrequencyUnit.Terahertz); + public QuantityValue Terahertz => this.As(FrequencyUnit.Terahertz); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: FrequencyUnit -> BaseUnit - unitConverter.SetConversionFunction(FrequencyUnit.BeatPerMinute, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); - unitConverter.SetConversionFunction(FrequencyUnit.CyclePerHour, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); - unitConverter.SetConversionFunction(FrequencyUnit.CyclePerMinute, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); - unitConverter.SetConversionFunction(FrequencyUnit.Gigahertz, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); - unitConverter.SetConversionFunction(FrequencyUnit.Kilohertz, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); - unitConverter.SetConversionFunction(FrequencyUnit.Megahertz, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); - unitConverter.SetConversionFunction(FrequencyUnit.Microhertz, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); - unitConverter.SetConversionFunction(FrequencyUnit.Millihertz, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); - unitConverter.SetConversionFunction(FrequencyUnit.PerSecond, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); - unitConverter.SetConversionFunction(FrequencyUnit.RadianPerSecond, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); - unitConverter.SetConversionFunction(FrequencyUnit.Terahertz, FrequencyUnit.Hertz, quantity => quantity.ToUnit(FrequencyUnit.Hertz)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.Hertz, quantity => quantity); - - // Register in unit converter: BaseUnit -> FrequencyUnit - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.BeatPerMinute, quantity => quantity.ToUnit(FrequencyUnit.BeatPerMinute)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.CyclePerHour, quantity => quantity.ToUnit(FrequencyUnit.CyclePerHour)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.CyclePerMinute, quantity => quantity.ToUnit(FrequencyUnit.CyclePerMinute)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.Gigahertz, quantity => quantity.ToUnit(FrequencyUnit.Gigahertz)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.Kilohertz, quantity => quantity.ToUnit(FrequencyUnit.Kilohertz)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.Megahertz, quantity => quantity.ToUnit(FrequencyUnit.Megahertz)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.Microhertz, quantity => quantity.ToUnit(FrequencyUnit.Microhertz)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.Millihertz, quantity => quantity.ToUnit(FrequencyUnit.Millihertz)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.PerSecond, quantity => quantity.ToUnit(FrequencyUnit.PerSecond)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.RadianPerSecond, quantity => quantity.ToUnit(FrequencyUnit.RadianPerSecond)); - unitConverter.SetConversionFunction(FrequencyUnit.Hertz, FrequencyUnit.Terahertz, quantity => quantity.ToUnit(FrequencyUnit.Terahertz)); - } - /// /// Get unit abbreviation string. /// @@ -369,7 +351,7 @@ public static string GetAbbreviation(FrequencyUnit unit, IFormatProvider? provid /// /// Creates a from . /// - public static Frequency FromBeatsPerMinute(double value) + public static Frequency FromBeatsPerMinute(QuantityValue value) { return new Frequency(value, FrequencyUnit.BeatPerMinute); } @@ -377,7 +359,7 @@ public static Frequency FromBeatsPerMinute(double value) /// /// Creates a from . /// - public static Frequency FromCyclesPerHour(double value) + public static Frequency FromCyclesPerHour(QuantityValue value) { return new Frequency(value, FrequencyUnit.CyclePerHour); } @@ -385,7 +367,7 @@ public static Frequency FromCyclesPerHour(double value) /// /// Creates a from . /// - public static Frequency FromCyclesPerMinute(double value) + public static Frequency FromCyclesPerMinute(QuantityValue value) { return new Frequency(value, FrequencyUnit.CyclePerMinute); } @@ -393,7 +375,7 @@ public static Frequency FromCyclesPerMinute(double value) /// /// Creates a from . /// - public static Frequency FromGigahertz(double value) + public static Frequency FromGigahertz(QuantityValue value) { return new Frequency(value, FrequencyUnit.Gigahertz); } @@ -401,7 +383,7 @@ public static Frequency FromGigahertz(double value) /// /// Creates a from . /// - public static Frequency FromHertz(double value) + public static Frequency FromHertz(QuantityValue value) { return new Frequency(value, FrequencyUnit.Hertz); } @@ -409,7 +391,7 @@ public static Frequency FromHertz(double value) /// /// Creates a from . /// - public static Frequency FromKilohertz(double value) + public static Frequency FromKilohertz(QuantityValue value) { return new Frequency(value, FrequencyUnit.Kilohertz); } @@ -417,7 +399,7 @@ public static Frequency FromKilohertz(double value) /// /// Creates a from . /// - public static Frequency FromMegahertz(double value) + public static Frequency FromMegahertz(QuantityValue value) { return new Frequency(value, FrequencyUnit.Megahertz); } @@ -425,7 +407,7 @@ public static Frequency FromMegahertz(double value) /// /// Creates a from . /// - public static Frequency FromMicrohertz(double value) + public static Frequency FromMicrohertz(QuantityValue value) { return new Frequency(value, FrequencyUnit.Microhertz); } @@ -433,7 +415,7 @@ public static Frequency FromMicrohertz(double value) /// /// Creates a from . /// - public static Frequency FromMillihertz(double value) + public static Frequency FromMillihertz(QuantityValue value) { return new Frequency(value, FrequencyUnit.Millihertz); } @@ -441,7 +423,7 @@ public static Frequency FromMillihertz(double value) /// /// Creates a from . /// - public static Frequency FromPerSecond(double value) + public static Frequency FromPerSecond(QuantityValue value) { return new Frequency(value, FrequencyUnit.PerSecond); } @@ -449,7 +431,7 @@ public static Frequency FromPerSecond(double value) /// /// Creates a from . /// - public static Frequency FromRadiansPerSecond(double value) + public static Frequency FromRadiansPerSecond(QuantityValue value) { return new Frequency(value, FrequencyUnit.RadianPerSecond); } @@ -457,7 +439,7 @@ public static Frequency FromRadiansPerSecond(double value) /// /// Creates a from . /// - public static Frequency FromTerahertz(double value) + public static Frequency FromTerahertz(QuantityValue value) { return new Frequency(value, FrequencyUnit.Terahertz); } @@ -468,7 +450,7 @@ public static Frequency FromTerahertz(double value) /// Value to convert from. /// Unit to convert from. /// Frequency unit value. - public static Frequency From(double value, FrequencyUnit fromUnit) + public static Frequency From(QuantityValue value, FrequencyUnit fromUnit) { return new Frequency(value, fromUnit); } @@ -529,10 +511,7 @@ public static Frequency Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Frequency Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -560,11 +539,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Frequency result /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Frequency result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -585,7 +560,7 @@ public static FrequencyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -596,7 +571,7 @@ public static FrequencyUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out FrequencyUnit unit) { return TryParseUnit(str, null, out unit); @@ -611,7 +586,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out FrequencyUni /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out FrequencyUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -630,35 +605,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Frequency operator +(Frequency left, Frequency right) { - return new Frequency(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Frequency(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Frequency operator -(Frequency left, Frequency right) { - return new Frequency(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Frequency(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -680,97 +655,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Frequency left, Frequency right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Frequency left, Frequency right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Frequency left, Frequency right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Frequency left, Frequency right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Frequency other, Frequency tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Frequency left, Frequency right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Frequency other, Frequency tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Frequency left, Frequency right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Frequency other, Frequency tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Frequency otherQuantity)) + if (obj is not Frequency otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Frequency other, Frequency tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Frequency other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Frequency. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Frequency), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Frequency otherQuantity)) throw new ArgumentException("Expected type Frequency.", nameof(obj)); + if (obj is not Frequency otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -782,168 +742,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Frequency other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(FrequencyUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Frequency to another Frequency with the unit representation . - /// - /// The unit to convert to. - /// A Frequency with the specified unit. - public Frequency ToUnit(FrequencyUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Frequency with the specified unit. - public Frequency ToUnit(FrequencyUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Frequency), Unit, typeof(Frequency), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Frequency)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(FrequencyUnit unit, [NotNullWhen(true)] out Frequency? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Frequency? convertedOrNull = (Unit, unit) switch - { - // FrequencyUnit -> BaseUnit - (FrequencyUnit.BeatPerMinute, FrequencyUnit.Hertz) => new Frequency(_value / 60, FrequencyUnit.Hertz), - (FrequencyUnit.CyclePerHour, FrequencyUnit.Hertz) => new Frequency(_value / 3600, FrequencyUnit.Hertz), - (FrequencyUnit.CyclePerMinute, FrequencyUnit.Hertz) => new Frequency(_value / 60, FrequencyUnit.Hertz), - (FrequencyUnit.Gigahertz, FrequencyUnit.Hertz) => new Frequency((_value) * 1e9d, FrequencyUnit.Hertz), - (FrequencyUnit.Kilohertz, FrequencyUnit.Hertz) => new Frequency((_value) * 1e3d, FrequencyUnit.Hertz), - (FrequencyUnit.Megahertz, FrequencyUnit.Hertz) => new Frequency((_value) * 1e6d, FrequencyUnit.Hertz), - (FrequencyUnit.Microhertz, FrequencyUnit.Hertz) => new Frequency((_value) * 1e-6d, FrequencyUnit.Hertz), - (FrequencyUnit.Millihertz, FrequencyUnit.Hertz) => new Frequency((_value) * 1e-3d, FrequencyUnit.Hertz), - (FrequencyUnit.PerSecond, FrequencyUnit.Hertz) => new Frequency(_value, FrequencyUnit.Hertz), - (FrequencyUnit.RadianPerSecond, FrequencyUnit.Hertz) => new Frequency(_value / (2 * Math.PI), FrequencyUnit.Hertz), - (FrequencyUnit.Terahertz, FrequencyUnit.Hertz) => new Frequency((_value) * 1e12d, FrequencyUnit.Hertz), - - // BaseUnit -> FrequencyUnit - (FrequencyUnit.Hertz, FrequencyUnit.BeatPerMinute) => new Frequency(_value * 60, FrequencyUnit.BeatPerMinute), - (FrequencyUnit.Hertz, FrequencyUnit.CyclePerHour) => new Frequency(_value * 3600, FrequencyUnit.CyclePerHour), - (FrequencyUnit.Hertz, FrequencyUnit.CyclePerMinute) => new Frequency(_value * 60, FrequencyUnit.CyclePerMinute), - (FrequencyUnit.Hertz, FrequencyUnit.Gigahertz) => new Frequency((_value) / 1e9d, FrequencyUnit.Gigahertz), - (FrequencyUnit.Hertz, FrequencyUnit.Kilohertz) => new Frequency((_value) / 1e3d, FrequencyUnit.Kilohertz), - (FrequencyUnit.Hertz, FrequencyUnit.Megahertz) => new Frequency((_value) / 1e6d, FrequencyUnit.Megahertz), - (FrequencyUnit.Hertz, FrequencyUnit.Microhertz) => new Frequency((_value) / 1e-6d, FrequencyUnit.Microhertz), - (FrequencyUnit.Hertz, FrequencyUnit.Millihertz) => new Frequency((_value) / 1e-3d, FrequencyUnit.Millihertz), - (FrequencyUnit.Hertz, FrequencyUnit.PerSecond) => new Frequency(_value, FrequencyUnit.PerSecond), - (FrequencyUnit.Hertz, FrequencyUnit.RadianPerSecond) => new Frequency(_value * (2 * Math.PI), FrequencyUnit.RadianPerSecond), - (FrequencyUnit.Hertz, FrequencyUnit.Terahertz) => new Frequency((_value) / 1e12d, FrequencyUnit.Terahertz), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Frequency ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not FrequencyUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FrequencyUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(FrequencyUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(FrequencyUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -958,7 +774,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs b/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs index 7c334103a9..7d2c083beb 100644 --- a/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/FuelEfficiency.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Fuel_efficiency /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct FuelEfficiency : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly FuelEfficiencyUnit? _unit; /// @@ -104,7 +103,7 @@ public static FuelEfficiencyInfo CreateDefault(Func - /// The for is [L^-2]. + /// The for is L^-2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 0, 0, 0, 0, 0, 0); @@ -120,17 +119,22 @@ public static FuelEfficiencyInfo CreateDefault(Func> GetDefaultMappings() { yield return new (FuelEfficiencyUnit.KilometerPerLiter, "KilometerPerLiter", "KilometersPerLiter", BaseUnits.Undefined); - yield return new (FuelEfficiencyUnit.LiterPer100Kilometers, "LiterPer100Kilometers", "LitersPer100Kilometers", BaseUnits.Undefined); - yield return new (FuelEfficiencyUnit.MilePerUkGallon, "MilePerUkGallon", "MilesPerUkGallon", BaseUnits.Undefined); - yield return new (FuelEfficiencyUnit.MilePerUsGallon, "MilePerUsGallon", "MilesPerUsGallon", BaseUnits.Undefined); + yield return new (FuelEfficiencyUnit.LiterPer100Kilometers, "LiterPer100Kilometers", "LitersPer100Kilometers", BaseUnits.Undefined, + new ConversionExpression(100, null, -1), + new ConversionExpression(100, null, -1) + ); + yield return new (FuelEfficiencyUnit.MilePerUkGallon, "MilePerUkGallon", "MilesPerUkGallon", BaseUnits.Undefined, + new QuantityValue(2273045, 804672) + ); + yield return new (FuelEfficiencyUnit.MilePerUsGallon, "MilePerUsGallon", "MilesPerUsGallon", BaseUnits.Undefined, + new QuantityValue(112903, 48000) + ); } } static FuelEfficiency() { - Info = FuelEfficiencyInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(FuelEfficiencyInfo.CreateDefault); } /// @@ -138,7 +142,7 @@ static FuelEfficiency() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public FuelEfficiency(double value, FuelEfficiencyUnit unit) + public FuelEfficiency(QuantityValue value, FuelEfficiencyUnit unit) { _value = value; _unit = unit; @@ -152,7 +156,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -163,7 +167,8 @@ public FuelEfficiency(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -192,10 +197,8 @@ public FuelEfficiency(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public FuelEfficiencyUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -234,49 +237,29 @@ public FuelEfficiency(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilometersPerLiter => As(FuelEfficiencyUnit.KilometerPerLiter); + public QuantityValue KilometersPerLiter => this.As(FuelEfficiencyUnit.KilometerPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double LitersPer100Kilometers => As(FuelEfficiencyUnit.LiterPer100Kilometers); + public QuantityValue LitersPer100Kilometers => this.As(FuelEfficiencyUnit.LiterPer100Kilometers); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilesPerUkGallon => As(FuelEfficiencyUnit.MilePerUkGallon); + public QuantityValue MilesPerUkGallon => this.As(FuelEfficiencyUnit.MilePerUkGallon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilesPerUsGallon => As(FuelEfficiencyUnit.MilePerUsGallon); + public QuantityValue MilesPerUsGallon => this.As(FuelEfficiencyUnit.MilePerUsGallon); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: FuelEfficiencyUnit -> BaseUnit - unitConverter.SetConversionFunction(FuelEfficiencyUnit.LiterPer100Kilometers, FuelEfficiencyUnit.KilometerPerLiter, quantity => quantity.ToUnit(FuelEfficiencyUnit.KilometerPerLiter)); - unitConverter.SetConversionFunction(FuelEfficiencyUnit.MilePerUkGallon, FuelEfficiencyUnit.KilometerPerLiter, quantity => quantity.ToUnit(FuelEfficiencyUnit.KilometerPerLiter)); - unitConverter.SetConversionFunction(FuelEfficiencyUnit.MilePerUsGallon, FuelEfficiencyUnit.KilometerPerLiter, quantity => quantity.ToUnit(FuelEfficiencyUnit.KilometerPerLiter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(FuelEfficiencyUnit.KilometerPerLiter, FuelEfficiencyUnit.KilometerPerLiter, quantity => quantity); - - // Register in unit converter: BaseUnit -> FuelEfficiencyUnit - unitConverter.SetConversionFunction(FuelEfficiencyUnit.KilometerPerLiter, FuelEfficiencyUnit.LiterPer100Kilometers, quantity => quantity.ToUnit(FuelEfficiencyUnit.LiterPer100Kilometers)); - unitConverter.SetConversionFunction(FuelEfficiencyUnit.KilometerPerLiter, FuelEfficiencyUnit.MilePerUkGallon, quantity => quantity.ToUnit(FuelEfficiencyUnit.MilePerUkGallon)); - unitConverter.SetConversionFunction(FuelEfficiencyUnit.KilometerPerLiter, FuelEfficiencyUnit.MilePerUsGallon, quantity => quantity.ToUnit(FuelEfficiencyUnit.MilePerUsGallon)); - } - /// /// Get unit abbreviation string. /// @@ -305,7 +288,7 @@ public static string GetAbbreviation(FuelEfficiencyUnit unit, IFormatProvider? p /// /// Creates a from . /// - public static FuelEfficiency FromKilometersPerLiter(double value) + public static FuelEfficiency FromKilometersPerLiter(QuantityValue value) { return new FuelEfficiency(value, FuelEfficiencyUnit.KilometerPerLiter); } @@ -313,7 +296,7 @@ public static FuelEfficiency FromKilometersPerLiter(double value) /// /// Creates a from . /// - public static FuelEfficiency FromLitersPer100Kilometers(double value) + public static FuelEfficiency FromLitersPer100Kilometers(QuantityValue value) { return new FuelEfficiency(value, FuelEfficiencyUnit.LiterPer100Kilometers); } @@ -321,7 +304,7 @@ public static FuelEfficiency FromLitersPer100Kilometers(double value) /// /// Creates a from . /// - public static FuelEfficiency FromMilesPerUkGallon(double value) + public static FuelEfficiency FromMilesPerUkGallon(QuantityValue value) { return new FuelEfficiency(value, FuelEfficiencyUnit.MilePerUkGallon); } @@ -329,7 +312,7 @@ public static FuelEfficiency FromMilesPerUkGallon(double value) /// /// Creates a from . /// - public static FuelEfficiency FromMilesPerUsGallon(double value) + public static FuelEfficiency FromMilesPerUsGallon(QuantityValue value) { return new FuelEfficiency(value, FuelEfficiencyUnit.MilePerUsGallon); } @@ -340,7 +323,7 @@ public static FuelEfficiency FromMilesPerUsGallon(double value) /// Value to convert from. /// Unit to convert from. /// FuelEfficiency unit value. - public static FuelEfficiency From(double value, FuelEfficiencyUnit fromUnit) + public static FuelEfficiency From(QuantityValue value, FuelEfficiencyUnit fromUnit) { return new FuelEfficiency(value, fromUnit); } @@ -401,10 +384,7 @@ public static FuelEfficiency Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static FuelEfficiency Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -432,11 +412,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out FuelEfficiency r /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out FuelEfficiency result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -457,7 +433,7 @@ public static FuelEfficiencyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -468,7 +444,7 @@ public static FuelEfficiencyUnit ParseUnit(string str, IFormatProvider? provider return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out FuelEfficiencyUnit unit) { return TryParseUnit(str, null, out unit); @@ -483,7 +459,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out FuelEfficien /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out FuelEfficiencyUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -502,35 +478,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static FuelEfficiency operator +(FuelEfficiency left, FuelEfficiency right) { - return new FuelEfficiency(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new FuelEfficiency(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static FuelEfficiency operator -(FuelEfficiency left, FuelEfficiency right) { - return new FuelEfficiency(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new FuelEfficiency(left.Value - right.As(left.Unit), left.Unit); } /// 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.KilometersPerLiter / right.KilometersPerLiter; } @@ -542,97 +518,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(FuelEfficiency left, FuelEfficiency right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(FuelEfficiency left, FuelEfficiency right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(FuelEfficiency left, FuelEfficiency right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(FuelEfficiency left, FuelEfficiency right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(FuelEfficiency other, FuelEfficiency tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(FuelEfficiency left, FuelEfficiency right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(FuelEfficiency other, FuelEfficiency tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(FuelEfficiency left, FuelEfficiency right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(FuelEfficiency other, FuelEfficiency tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is FuelEfficiency otherQuantity)) + if (obj is not FuelEfficiency otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(FuelEfficiency other, FuelEfficiency tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(FuelEfficiency other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current FuelEfficiency. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(FuelEfficiency), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is FuelEfficiency otherQuantity)) throw new ArgumentException("Expected type FuelEfficiency.", nameof(obj)); + if (obj is not FuelEfficiency otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -644,152 +605,24 @@ public int CompareTo(object? obj) /// public int CompareTo(FuelEfficiency other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(FuelEfficiencyUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this FuelEfficiency to another FuelEfficiency with the unit representation . - /// - /// The unit to convert to. - /// A FuelEfficiency with the specified unit. - public FuelEfficiency ToUnit(FuelEfficiencyUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A FuelEfficiency with the specified unit. - public FuelEfficiency ToUnit(FuelEfficiencyUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(FuelEfficiency), Unit, typeof(FuelEfficiency), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (FuelEfficiency)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(FuelEfficiencyUnit unit, [NotNullWhen(true)] out FuelEfficiency? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - FuelEfficiency? convertedOrNull = (Unit, unit) switch - { - // FuelEfficiencyUnit -> BaseUnit - (FuelEfficiencyUnit.LiterPer100Kilometers, FuelEfficiencyUnit.KilometerPerLiter) => new FuelEfficiency(100 / _value, FuelEfficiencyUnit.KilometerPerLiter), - (FuelEfficiencyUnit.MilePerUkGallon, FuelEfficiencyUnit.KilometerPerLiter) => new FuelEfficiency(_value * 1.609344 / 4.54609, FuelEfficiencyUnit.KilometerPerLiter), - (FuelEfficiencyUnit.MilePerUsGallon, FuelEfficiencyUnit.KilometerPerLiter) => new FuelEfficiency(_value * 1.609344 / 3.785411784, FuelEfficiencyUnit.KilometerPerLiter), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> FuelEfficiencyUnit - (FuelEfficiencyUnit.KilometerPerLiter, FuelEfficiencyUnit.LiterPer100Kilometers) => new FuelEfficiency(100 / _value, FuelEfficiencyUnit.LiterPer100Kilometers), - (FuelEfficiencyUnit.KilometerPerLiter, FuelEfficiencyUnit.MilePerUkGallon) => new FuelEfficiency(_value * 4.54609 / 1.609344, FuelEfficiencyUnit.MilePerUkGallon), - (FuelEfficiencyUnit.KilometerPerLiter, FuelEfficiencyUnit.MilePerUsGallon) => new FuelEfficiency(_value * 3.785411784 / 1.609344, FuelEfficiencyUnit.MilePerUsGallon), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public FuelEfficiency ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not FuelEfficiencyUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FuelEfficiencyUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is FuelEfficiencyUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(FuelEfficiencyUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(FuelEfficiencyUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(FuelEfficiencyUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -804,7 +637,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs index 8631b86a9b..b61f289d1e 100644 --- a/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/HeatFlux.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// Heat flux is the flow of energy per unit of area per unit of time /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct HeatFlux : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly HeatFluxUnit? _unit; /// @@ -104,7 +103,7 @@ public static HeatFluxInfo CreateDefault(Func - /// The for is [T^-3][M]. + /// The for is T^-3M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); @@ -119,32 +118,64 @@ public static HeatFluxInfo CreateDefault(FuncAn of representing the default unit mappings for HeatFlux. public static IEnumerable> GetDefaultMappings() { - yield return new (HeatFluxUnit.BtuPerHourSquareFoot, "BtuPerHourSquareFoot", "BtusPerHourSquareFoot", BaseUnits.Undefined); - yield return new (HeatFluxUnit.BtuPerMinuteSquareFoot, "BtuPerMinuteSquareFoot", "BtusPerMinuteSquareFoot", BaseUnits.Undefined); - yield return new (HeatFluxUnit.BtuPerSecondSquareFoot, "BtuPerSecondSquareFoot", "BtusPerSecondSquareFoot", BaseUnits.Undefined); - yield return new (HeatFluxUnit.BtuPerSecondSquareInch, "BtuPerSecondSquareInch", "BtusPerSecondSquareInch", BaseUnits.Undefined); - yield return new (HeatFluxUnit.CaloriePerSecondSquareCentimeter, "CaloriePerSecondSquareCentimeter", "CaloriesPerSecondSquareCentimeter", BaseUnits.Undefined); - yield return new (HeatFluxUnit.CentiwattPerSquareMeter, "CentiwattPerSquareMeter", "CentiwattsPerSquareMeter", new BaseUnits(mass: MassUnit.Decagram, time: DurationUnit.Second)); - yield return new (HeatFluxUnit.DeciwattPerSquareMeter, "DeciwattPerSquareMeter", "DeciwattsPerSquareMeter", new BaseUnits(mass: MassUnit.Hectogram, time: DurationUnit.Second)); - yield return new (HeatFluxUnit.KilocaloriePerHourSquareMeter, "KilocaloriePerHourSquareMeter", "KilocaloriesPerHourSquareMeter", BaseUnits.Undefined); - yield return new (HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, "KilocaloriePerSecondSquareCentimeter", "KilocaloriesPerSecondSquareCentimeter", BaseUnits.Undefined); - yield return new (HeatFluxUnit.KilowattPerSquareMeter, "KilowattPerSquareMeter", "KilowattsPerSquareMeter", BaseUnits.Undefined); - yield return new (HeatFluxUnit.MicrowattPerSquareMeter, "MicrowattPerSquareMeter", "MicrowattsPerSquareMeter", new BaseUnits(mass: MassUnit.Milligram, time: DurationUnit.Second)); - yield return new (HeatFluxUnit.MilliwattPerSquareMeter, "MilliwattPerSquareMeter", "MilliwattsPerSquareMeter", new BaseUnits(mass: MassUnit.Gram, time: DurationUnit.Second)); - yield return new (HeatFluxUnit.NanowattPerSquareMeter, "NanowattPerSquareMeter", "NanowattsPerSquareMeter", new BaseUnits(mass: MassUnit.Microgram, time: DurationUnit.Second)); - yield return new (HeatFluxUnit.PoundForcePerFootSecond, "PoundForcePerFootSecond", "PoundsForcePerFootSecond", BaseUnits.Undefined); - yield return new (HeatFluxUnit.PoundPerSecondCubed, "PoundPerSecondCubed", "PoundsPerSecondCubed", BaseUnits.Undefined); - yield return new (HeatFluxUnit.WattPerSquareFoot, "WattPerSquareFoot", "WattsPerSquareFoot", BaseUnits.Undefined); - yield return new (HeatFluxUnit.WattPerSquareInch, "WattPerSquareInch", "WattsPerSquareInch", BaseUnits.Undefined); + yield return new (HeatFluxUnit.BtuPerHourSquareFoot, "BtuPerHourSquareFoot", "BtusPerHourSquareFoot", BaseUnits.Undefined, + new QuantityValue(16722547200, 52752792631) + ); + yield return new (HeatFluxUnit.BtuPerMinuteSquareFoot, "BtuPerMinuteSquareFoot", "BtusPerMinuteSquareFoot", BaseUnits.Undefined, + new QuantityValue(278709120, 52752792631) + ); + yield return new (HeatFluxUnit.BtuPerSecondSquareFoot, "BtuPerSecondSquareFoot", "BtusPerSecondSquareFoot", BaseUnits.Undefined, + new QuantityValue(4645152, 52752792631) + ); + yield return new (HeatFluxUnit.BtuPerSecondSquareInch, "BtuPerSecondSquareInch", "BtusPerSecondSquareInch", BaseUnits.Undefined, + new QuantityValue(32258, 52752792631) + ); + yield return new (HeatFluxUnit.CaloriePerSecondSquareCentimeter, "CaloriePerSecondSquareCentimeter", "CaloriesPerSecondSquareCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 41840) + ); + yield return new (HeatFluxUnit.CentiwattPerSquareMeter, "CentiwattPerSquareMeter", "CentiwattsPerSquareMeter", new BaseUnits(mass: MassUnit.Decagram, time: DurationUnit.Second), + 100 + ); + yield return new (HeatFluxUnit.DeciwattPerSquareMeter, "DeciwattPerSquareMeter", "DeciwattsPerSquareMeter", new BaseUnits(mass: MassUnit.Hectogram, time: DurationUnit.Second), + 10 + ); + yield return new (HeatFluxUnit.KilocaloriePerHourSquareMeter, "KilocaloriePerHourSquareMeter", "KilocaloriesPerHourSquareMeter", BaseUnits.Undefined, + new QuantityValue(450, 523) + ); + yield return new (HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, "KilocaloriePerSecondSquareCentimeter", "KilocaloriesPerSecondSquareCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 41840000) + ); + yield return new (HeatFluxUnit.KilowattPerSquareMeter, "KilowattPerSquareMeter", "KilowattsPerSquareMeter", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (HeatFluxUnit.MicrowattPerSquareMeter, "MicrowattPerSquareMeter", "MicrowattsPerSquareMeter", new BaseUnits(mass: MassUnit.Milligram, time: DurationUnit.Second), + 1000000 + ); + yield return new (HeatFluxUnit.MilliwattPerSquareMeter, "MilliwattPerSquareMeter", "MilliwattsPerSquareMeter", new BaseUnits(mass: MassUnit.Gram, time: DurationUnit.Second), + 1000 + ); + yield return new (HeatFluxUnit.NanowattPerSquareMeter, "NanowattPerSquareMeter", "NanowattsPerSquareMeter", new BaseUnits(mass: MassUnit.Microgram, time: DurationUnit.Second), + 1000000000 + ); + yield return new (HeatFluxUnit.PoundForcePerFootSecond, "PoundForcePerFootSecond", "PoundsForcePerFootSecond", BaseUnits.Undefined, + new QuantityValue(609600000000, 8896443230521) + ); + yield return new (HeatFluxUnit.PoundPerSecondCubed, "PoundPerSecondCubed", "PoundsPerSecondCubed", BaseUnits.Undefined, + new QuantityValue(100000000, 45359237) + ); + yield return new (HeatFluxUnit.WattPerSquareFoot, "WattPerSquareFoot", "WattsPerSquareFoot", BaseUnits.Undefined, + new QuantityValue(145161, 1562500) + ); + yield return new (HeatFluxUnit.WattPerSquareInch, "WattPerSquareInch", "WattsPerSquareInch", BaseUnits.Undefined, + new QuantityValue(16129, 25000000) + ); yield return new (HeatFluxUnit.WattPerSquareMeter, "WattPerSquareMeter", "WattsPerSquareMeter", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second)); } } static HeatFlux() { - Info = HeatFluxInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(HeatFluxInfo.CreateDefault); } /// @@ -152,7 +183,7 @@ static HeatFlux() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public HeatFlux(double value, HeatFluxUnit unit) + public HeatFlux(QuantityValue value, HeatFluxUnit unit) { _value = value; _unit = unit; @@ -166,7 +197,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -177,7 +208,8 @@ public HeatFlux(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -206,10 +238,8 @@ public HeatFlux(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public HeatFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -248,147 +278,99 @@ public HeatFlux(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BtusPerHourSquareFoot => As(HeatFluxUnit.BtuPerHourSquareFoot); + public QuantityValue BtusPerHourSquareFoot => this.As(HeatFluxUnit.BtuPerHourSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BtusPerMinuteSquareFoot => As(HeatFluxUnit.BtuPerMinuteSquareFoot); + public QuantityValue BtusPerMinuteSquareFoot => this.As(HeatFluxUnit.BtuPerMinuteSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BtusPerSecondSquareFoot => As(HeatFluxUnit.BtuPerSecondSquareFoot); + public QuantityValue BtusPerSecondSquareFoot => this.As(HeatFluxUnit.BtuPerSecondSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BtusPerSecondSquareInch => As(HeatFluxUnit.BtuPerSecondSquareInch); + public QuantityValue BtusPerSecondSquareInch => this.As(HeatFluxUnit.BtuPerSecondSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.CaloriePerSecondSquareCentimeter); + public QuantityValue CaloriesPerSecondSquareCentimeter => this.As(HeatFluxUnit.CaloriePerSecondSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentiwattsPerSquareMeter => As(HeatFluxUnit.CentiwattPerSquareMeter); + public QuantityValue CentiwattsPerSquareMeter => this.As(HeatFluxUnit.CentiwattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DeciwattsPerSquareMeter => As(HeatFluxUnit.DeciwattPerSquareMeter); + public QuantityValue DeciwattsPerSquareMeter => this.As(HeatFluxUnit.DeciwattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilocaloriesPerHourSquareMeter => As(HeatFluxUnit.KilocaloriePerHourSquareMeter); + public QuantityValue KilocaloriesPerHourSquareMeter => this.As(HeatFluxUnit.KilocaloriePerHourSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilocaloriesPerSecondSquareCentimeter => As(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); + public QuantityValue KilocaloriesPerSecondSquareCentimeter => this.As(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattsPerSquareMeter => As(HeatFluxUnit.KilowattPerSquareMeter); + public QuantityValue KilowattsPerSquareMeter => this.As(HeatFluxUnit.KilowattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrowattsPerSquareMeter => As(HeatFluxUnit.MicrowattPerSquareMeter); + public QuantityValue MicrowattsPerSquareMeter => this.As(HeatFluxUnit.MicrowattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliwattsPerSquareMeter => As(HeatFluxUnit.MilliwattPerSquareMeter); + public QuantityValue MilliwattsPerSquareMeter => this.As(HeatFluxUnit.MilliwattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanowattsPerSquareMeter => As(HeatFluxUnit.NanowattPerSquareMeter); + public QuantityValue NanowattsPerSquareMeter => this.As(HeatFluxUnit.NanowattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsForcePerFootSecond => As(HeatFluxUnit.PoundForcePerFootSecond); + public QuantityValue PoundsForcePerFootSecond => this.As(HeatFluxUnit.PoundForcePerFootSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerSecondCubed => As(HeatFluxUnit.PoundPerSecondCubed); + public QuantityValue PoundsPerSecondCubed => this.As(HeatFluxUnit.PoundPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattsPerSquareFoot => As(HeatFluxUnit.WattPerSquareFoot); + public QuantityValue WattsPerSquareFoot => this.As(HeatFluxUnit.WattPerSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattsPerSquareInch => As(HeatFluxUnit.WattPerSquareInch); + public QuantityValue WattsPerSquareInch => this.As(HeatFluxUnit.WattPerSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattsPerSquareMeter => As(HeatFluxUnit.WattPerSquareMeter); + public QuantityValue WattsPerSquareMeter => this.As(HeatFluxUnit.WattPerSquareMeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: HeatFluxUnit -> BaseUnit - unitConverter.SetConversionFunction(HeatFluxUnit.BtuPerHourSquareFoot, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.BtuPerMinuteSquareFoot, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.BtuPerSecondSquareFoot, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.BtuPerSecondSquareInch, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.CaloriePerSecondSquareCentimeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.CentiwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.DeciwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.KilocaloriePerHourSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.KilowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.MicrowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.MilliwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.NanowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.PoundForcePerFootSecond, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.PoundPerSecondCubed, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareFoot, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareInch, HeatFluxUnit.WattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> HeatFluxUnit - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerHourSquareFoot, quantity => quantity.ToUnit(HeatFluxUnit.BtuPerHourSquareFoot)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerMinuteSquareFoot, quantity => quantity.ToUnit(HeatFluxUnit.BtuPerMinuteSquareFoot)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerSecondSquareFoot, quantity => quantity.ToUnit(HeatFluxUnit.BtuPerSecondSquareFoot)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerSecondSquareInch, quantity => quantity.ToUnit(HeatFluxUnit.BtuPerSecondSquareInch)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.CaloriePerSecondSquareCentimeter, quantity => quantity.ToUnit(HeatFluxUnit.CaloriePerSecondSquareCentimeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.CentiwattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.CentiwattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.DeciwattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.DeciwattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilocaloriePerHourSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.KilocaloriePerHourSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, quantity => quantity.ToUnit(HeatFluxUnit.KilocaloriePerSecondSquareCentimeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilowattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.KilowattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.MicrowattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.MicrowattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.MilliwattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.MilliwattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.NanowattPerSquareMeter, quantity => quantity.ToUnit(HeatFluxUnit.NanowattPerSquareMeter)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.PoundForcePerFootSecond, quantity => quantity.ToUnit(HeatFluxUnit.PoundForcePerFootSecond)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.PoundPerSecondCubed, quantity => quantity.ToUnit(HeatFluxUnit.PoundPerSecondCubed)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.WattPerSquareFoot, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareFoot)); - unitConverter.SetConversionFunction(HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.WattPerSquareInch, quantity => quantity.ToUnit(HeatFluxUnit.WattPerSquareInch)); - } - /// /// Get unit abbreviation string. /// @@ -417,7 +399,7 @@ public static string GetAbbreviation(HeatFluxUnit unit, IFormatProvider? provide /// /// Creates a from . /// - public static HeatFlux FromBtusPerHourSquareFoot(double value) + public static HeatFlux FromBtusPerHourSquareFoot(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.BtuPerHourSquareFoot); } @@ -425,7 +407,7 @@ public static HeatFlux FromBtusPerHourSquareFoot(double value) /// /// Creates a from . /// - public static HeatFlux FromBtusPerMinuteSquareFoot(double value) + public static HeatFlux FromBtusPerMinuteSquareFoot(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.BtuPerMinuteSquareFoot); } @@ -433,7 +415,7 @@ public static HeatFlux FromBtusPerMinuteSquareFoot(double value) /// /// Creates a from . /// - public static HeatFlux FromBtusPerSecondSquareFoot(double value) + public static HeatFlux FromBtusPerSecondSquareFoot(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareFoot); } @@ -441,7 +423,7 @@ public static HeatFlux FromBtusPerSecondSquareFoot(double value) /// /// Creates a from . /// - public static HeatFlux FromBtusPerSecondSquareInch(double value) + public static HeatFlux FromBtusPerSecondSquareInch(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.BtuPerSecondSquareInch); } @@ -449,7 +431,7 @@ public static HeatFlux FromBtusPerSecondSquareInch(double value) /// /// Creates a from . /// - public static HeatFlux FromCaloriesPerSecondSquareCentimeter(double value) + public static HeatFlux FromCaloriesPerSecondSquareCentimeter(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.CaloriePerSecondSquareCentimeter); } @@ -457,7 +439,7 @@ public static HeatFlux FromCaloriesPerSecondSquareCentimeter(double value) /// /// Creates a from . /// - public static HeatFlux FromCentiwattsPerSquareMeter(double value) + public static HeatFlux FromCentiwattsPerSquareMeter(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.CentiwattPerSquareMeter); } @@ -465,7 +447,7 @@ public static HeatFlux FromCentiwattsPerSquareMeter(double value) /// /// Creates a from . /// - public static HeatFlux FromDeciwattsPerSquareMeter(double value) + public static HeatFlux FromDeciwattsPerSquareMeter(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.DeciwattPerSquareMeter); } @@ -473,7 +455,7 @@ public static HeatFlux FromDeciwattsPerSquareMeter(double value) /// /// Creates a from . /// - public static HeatFlux FromKilocaloriesPerHourSquareMeter(double value) + public static HeatFlux FromKilocaloriesPerHourSquareMeter(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.KilocaloriePerHourSquareMeter); } @@ -481,7 +463,7 @@ public static HeatFlux FromKilocaloriesPerHourSquareMeter(double value) /// /// Creates a from . /// - public static HeatFlux FromKilocaloriesPerSecondSquareCentimeter(double value) + public static HeatFlux FromKilocaloriesPerSecondSquareCentimeter(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter); } @@ -489,7 +471,7 @@ public static HeatFlux FromKilocaloriesPerSecondSquareCentimeter(double value) /// /// Creates a from . /// - public static HeatFlux FromKilowattsPerSquareMeter(double value) + public static HeatFlux FromKilowattsPerSquareMeter(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.KilowattPerSquareMeter); } @@ -497,7 +479,7 @@ public static HeatFlux FromKilowattsPerSquareMeter(double value) /// /// Creates a from . /// - public static HeatFlux FromMicrowattsPerSquareMeter(double value) + public static HeatFlux FromMicrowattsPerSquareMeter(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.MicrowattPerSquareMeter); } @@ -505,7 +487,7 @@ public static HeatFlux FromMicrowattsPerSquareMeter(double value) /// /// Creates a from . /// - public static HeatFlux FromMilliwattsPerSquareMeter(double value) + public static HeatFlux FromMilliwattsPerSquareMeter(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.MilliwattPerSquareMeter); } @@ -513,7 +495,7 @@ public static HeatFlux FromMilliwattsPerSquareMeter(double value) /// /// Creates a from . /// - public static HeatFlux FromNanowattsPerSquareMeter(double value) + public static HeatFlux FromNanowattsPerSquareMeter(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.NanowattPerSquareMeter); } @@ -521,7 +503,7 @@ public static HeatFlux FromNanowattsPerSquareMeter(double value) /// /// Creates a from . /// - public static HeatFlux FromPoundsForcePerFootSecond(double value) + public static HeatFlux FromPoundsForcePerFootSecond(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.PoundForcePerFootSecond); } @@ -529,7 +511,7 @@ public static HeatFlux FromPoundsForcePerFootSecond(double value) /// /// Creates a from . /// - public static HeatFlux FromPoundsPerSecondCubed(double value) + public static HeatFlux FromPoundsPerSecondCubed(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.PoundPerSecondCubed); } @@ -537,7 +519,7 @@ public static HeatFlux FromPoundsPerSecondCubed(double value) /// /// Creates a from . /// - public static HeatFlux FromWattsPerSquareFoot(double value) + public static HeatFlux FromWattsPerSquareFoot(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.WattPerSquareFoot); } @@ -545,7 +527,7 @@ public static HeatFlux FromWattsPerSquareFoot(double value) /// /// Creates a from . /// - public static HeatFlux FromWattsPerSquareInch(double value) + public static HeatFlux FromWattsPerSquareInch(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.WattPerSquareInch); } @@ -553,7 +535,7 @@ public static HeatFlux FromWattsPerSquareInch(double value) /// /// Creates a from . /// - public static HeatFlux FromWattsPerSquareMeter(double value) + public static HeatFlux FromWattsPerSquareMeter(QuantityValue value) { return new HeatFlux(value, HeatFluxUnit.WattPerSquareMeter); } @@ -564,7 +546,7 @@ public static HeatFlux FromWattsPerSquareMeter(double value) /// Value to convert from. /// Unit to convert from. /// HeatFlux unit value. - public static HeatFlux From(double value, HeatFluxUnit fromUnit) + public static HeatFlux From(QuantityValue value, HeatFluxUnit fromUnit) { return new HeatFlux(value, fromUnit); } @@ -625,10 +607,7 @@ public static HeatFlux Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static HeatFlux Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -656,11 +635,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out HeatFlux result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out HeatFlux result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -681,7 +656,7 @@ public static HeatFluxUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -692,7 +667,7 @@ public static HeatFluxUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out HeatFluxUnit unit) { return TryParseUnit(str, null, out unit); @@ -707,7 +682,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out HeatFluxUnit /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out HeatFluxUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -726,35 +701,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static HeatFlux operator +(HeatFlux left, HeatFlux right) { - return new HeatFlux(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new HeatFlux(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static HeatFlux operator -(HeatFlux left, HeatFlux right) { - return new HeatFlux(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new HeatFlux(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -776,97 +751,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(HeatFlux left, HeatFlux right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(HeatFlux left, HeatFlux right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(HeatFlux left, HeatFlux right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(HeatFlux left, HeatFlux right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(HeatFlux other, HeatFlux tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(HeatFlux left, HeatFlux right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(HeatFlux other, HeatFlux tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(HeatFlux left, HeatFlux right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(HeatFlux other, HeatFlux tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is HeatFlux otherQuantity)) + if (obj is not HeatFlux otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(HeatFlux other, HeatFlux tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(HeatFlux other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current HeatFlux. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(HeatFlux), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is HeatFlux otherQuantity)) throw new ArgumentException("Expected type HeatFlux.", nameof(obj)); + if (obj is not HeatFlux otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -878,180 +838,24 @@ public int CompareTo(object? obj) /// public int CompareTo(HeatFlux other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(HeatFluxUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this HeatFlux to another HeatFlux with the unit representation . - /// - /// The unit to convert to. - /// A HeatFlux with the specified unit. - public HeatFlux ToUnit(HeatFluxUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A HeatFlux with the specified unit. - public HeatFlux ToUnit(HeatFluxUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(HeatFlux), Unit, typeof(HeatFlux), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (HeatFlux)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(HeatFluxUnit unit, [NotNullWhen(true)] out HeatFlux? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - HeatFlux? convertedOrNull = (Unit, unit) switch - { - // HeatFluxUnit -> BaseUnit - (HeatFluxUnit.BtuPerHourSquareFoot, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 1055.05585262 / (0.3048 * 0.3048 * 3600), HeatFluxUnit.WattPerSquareMeter), - (HeatFluxUnit.BtuPerMinuteSquareFoot, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 1055.05585262 / (0.3048 * 0.3048 * 60), HeatFluxUnit.WattPerSquareMeter), - (HeatFluxUnit.BtuPerSecondSquareFoot, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 1055.05585262 / (0.3048 * 0.3048), HeatFluxUnit.WattPerSquareMeter), - (HeatFluxUnit.BtuPerSecondSquareInch, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 1055.05585262 / (2.54e-2 * 2.54e-2), HeatFluxUnit.WattPerSquareMeter), - (HeatFluxUnit.CaloriePerSecondSquareCentimeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 4.184e4, HeatFluxUnit.WattPerSquareMeter), - (HeatFluxUnit.CentiwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux((_value) * 1e-2d, HeatFluxUnit.WattPerSquareMeter), - (HeatFluxUnit.DeciwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux((_value) * 1e-1d, HeatFluxUnit.WattPerSquareMeter), - (HeatFluxUnit.KilocaloriePerHourSquareMeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 4.184e3 / 3600, HeatFluxUnit.WattPerSquareMeter), - (HeatFluxUnit.KilocaloriePerSecondSquareCentimeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux((_value * 4.184e4) * 1e3d, HeatFluxUnit.WattPerSquareMeter), - (HeatFluxUnit.KilowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux((_value) * 1e3d, HeatFluxUnit.WattPerSquareMeter), - (HeatFluxUnit.MicrowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux((_value) * 1e-6d, HeatFluxUnit.WattPerSquareMeter), - (HeatFluxUnit.MilliwattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux((_value) * 1e-3d, HeatFluxUnit.WattPerSquareMeter), - (HeatFluxUnit.NanowattPerSquareMeter, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux((_value) * 1e-9d, HeatFluxUnit.WattPerSquareMeter), - (HeatFluxUnit.PoundForcePerFootSecond, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 1.3558179483314004 / 9.290304e-2, HeatFluxUnit.WattPerSquareMeter), - (HeatFluxUnit.PoundPerSecondCubed, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value * 4.5359237e-1, HeatFluxUnit.WattPerSquareMeter), - (HeatFluxUnit.WattPerSquareFoot, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value / (0.3048 * 0.3048), HeatFluxUnit.WattPerSquareMeter), - (HeatFluxUnit.WattPerSquareInch, HeatFluxUnit.WattPerSquareMeter) => new HeatFlux(_value / (2.54e-2 * 2.54e-2), HeatFluxUnit.WattPerSquareMeter), - - // BaseUnit -> HeatFluxUnit - (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerHourSquareFoot) => new HeatFlux(_value * (0.3048 * 0.3048 * 3600) / 1055.05585262, HeatFluxUnit.BtuPerHourSquareFoot), - (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerMinuteSquareFoot) => new HeatFlux(_value * (0.3048 * 0.3048 * 60) / 1055.05585262, HeatFluxUnit.BtuPerMinuteSquareFoot), - (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerSecondSquareFoot) => new HeatFlux(_value * (0.3048 * 0.3048) / 1055.05585262, HeatFluxUnit.BtuPerSecondSquareFoot), - (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.BtuPerSecondSquareInch) => new HeatFlux(_value * (2.54e-2 * 2.54e-2) / 1055.05585262, HeatFluxUnit.BtuPerSecondSquareInch), - (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.CaloriePerSecondSquareCentimeter) => new HeatFlux(_value / 4.184e4, HeatFluxUnit.CaloriePerSecondSquareCentimeter), - (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.CentiwattPerSquareMeter) => new HeatFlux((_value) / 1e-2d, HeatFluxUnit.CentiwattPerSquareMeter), - (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.DeciwattPerSquareMeter) => new HeatFlux((_value) / 1e-1d, HeatFluxUnit.DeciwattPerSquareMeter), - (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilocaloriePerHourSquareMeter) => new HeatFlux(_value * 3600 / 4.184e3, HeatFluxUnit.KilocaloriePerHourSquareMeter), - (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter) => new HeatFlux((_value / 4.184e4) / 1e3d, HeatFluxUnit.KilocaloriePerSecondSquareCentimeter), - (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.KilowattPerSquareMeter) => new HeatFlux((_value) / 1e3d, HeatFluxUnit.KilowattPerSquareMeter), - (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.MicrowattPerSquareMeter) => new HeatFlux((_value) / 1e-6d, HeatFluxUnit.MicrowattPerSquareMeter), - (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.MilliwattPerSquareMeter) => new HeatFlux((_value) / 1e-3d, HeatFluxUnit.MilliwattPerSquareMeter), - (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.NanowattPerSquareMeter) => new HeatFlux((_value) / 1e-9d, HeatFluxUnit.NanowattPerSquareMeter), - (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.PoundForcePerFootSecond) => new HeatFlux(_value * 9.290304e-2 / 1.3558179483314004, HeatFluxUnit.PoundForcePerFootSecond), - (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.PoundPerSecondCubed) => new HeatFlux(_value / 4.5359237e-1, HeatFluxUnit.PoundPerSecondCubed), - (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.WattPerSquareFoot) => new HeatFlux(_value * (0.3048 * 0.3048), HeatFluxUnit.WattPerSquareFoot), - (HeatFluxUnit.WattPerSquareMeter, HeatFluxUnit.WattPerSquareInch) => new HeatFlux(_value * (2.54e-2 * 2.54e-2), HeatFluxUnit.WattPerSquareInch), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public HeatFlux ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not HeatFluxUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(HeatFluxUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(HeatFluxUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(HeatFluxUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1066,7 +870,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs b/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs index d12fe17f67..6c87ba4ee4 100644 --- a/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/HeatTransferCoefficient.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct HeatTransferCoefficient : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly HeatTransferCoefficientUnit? _unit; /// @@ -101,7 +100,7 @@ public static HeatTransferCoefficientInfo CreateDefault(Func - /// The for is [T^-3][M][Θ^-1]. + /// The for is T^-3MΘ^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, -3, 0, -1, 0, 0); @@ -116,19 +115,25 @@ public static HeatTransferCoefficientInfo CreateDefault(FuncAn of representing the default unit mappings for HeatTransferCoefficient. public static IEnumerable> GetDefaultMappings() { - yield return new (HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, "BtuPerHourSquareFootDegreeFahrenheit", "BtusPerHourSquareFootDegreeFahrenheit", BaseUnits.Undefined); - yield return new (HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, "CaloriePerHourSquareMeterDegreeCelsius", "CaloriesPerHourSquareMeterDegreeCelsius", BaseUnits.Undefined); - yield return new (HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, "KilocaloriePerHourSquareMeterDegreeCelsius", "KilocaloriesPerHourSquareMeterDegreeCelsius", BaseUnits.Undefined); - yield return new (HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, "WattPerSquareMeterCelsius", "WattsPerSquareMeterCelsius", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius)); + yield return new (HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, "BtuPerHourSquareFootDegreeFahrenheit", "BtusPerHourSquareFootDegreeFahrenheit", BaseUnits.Undefined, + new QuantityValue(9290304000, 52752792631) + ); + yield return new (HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, "CaloriePerHourSquareMeterDegreeCelsius", "CaloriesPerHourSquareMeterDegreeCelsius", BaseUnits.Undefined, + new QuantityValue(450000, 523) + ); + yield return new (HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, "KilocaloriePerHourSquareMeterDegreeCelsius", "KilocaloriesPerHourSquareMeterDegreeCelsius", BaseUnits.Undefined, + new QuantityValue(450, 523) + ); + yield return new (HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, "WattPerSquareMeterCelsius", "WattsPerSquareMeterCelsius", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), + 1 + ); yield return new (HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, "WattPerSquareMeterKelvin", "WattsPerSquareMeterKelvin", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin)); } } static HeatTransferCoefficient() { - Info = HeatTransferCoefficientInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(HeatTransferCoefficientInfo.CreateDefault); } /// @@ -136,7 +141,7 @@ static HeatTransferCoefficient() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public HeatTransferCoefficient(double value, HeatTransferCoefficientUnit unit) + public HeatTransferCoefficient(QuantityValue value, HeatTransferCoefficientUnit unit) { _value = value; _unit = unit; @@ -150,7 +155,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -161,7 +166,8 @@ public HeatTransferCoefficient(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -190,10 +196,8 @@ public HeatTransferCoefficient(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public HeatTransferCoefficientUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -232,56 +236,34 @@ public HeatTransferCoefficient(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BtusPerHourSquareFootDegreeFahrenheit => As(HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit); + public QuantityValue BtusPerHourSquareFootDegreeFahrenheit => this.As(HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CaloriesPerHourSquareMeterDegreeCelsius => As(HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius); + public QuantityValue CaloriesPerHourSquareMeterDegreeCelsius => this.As(HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilocaloriesPerHourSquareMeterDegreeCelsius => As(HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius); + public QuantityValue KilocaloriesPerHourSquareMeterDegreeCelsius => this.As(HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattsPerSquareMeterCelsius => As(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); + public QuantityValue WattsPerSquareMeterCelsius => this.As(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattsPerSquareMeterKelvin => As(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); + public QuantityValue WattsPerSquareMeterKelvin => this.As(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: HeatTransferCoefficientUnit -> BaseUnit - unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, quantity => quantity.ToUnit(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin)); - unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, quantity => quantity.ToUnit(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin)); - unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, quantity => quantity.ToUnit(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin)); - unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, quantity => quantity.ToUnit(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, quantity => quantity); - - // Register in unit converter: BaseUnit -> HeatTransferCoefficientUnit - unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, quantity => quantity.ToUnit(HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit)); - unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, quantity => quantity.ToUnit(HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius)); - unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, quantity => quantity.ToUnit(HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius)); - unitConverter.SetConversionFunction(HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, quantity => quantity.ToUnit(HeatTransferCoefficientUnit.WattPerSquareMeterCelsius)); - } - /// /// Get unit abbreviation string. /// @@ -310,7 +292,7 @@ public static string GetAbbreviation(HeatTransferCoefficientUnit unit, IFormatPr /// /// Creates a from . /// - public static HeatTransferCoefficient FromBtusPerHourSquareFootDegreeFahrenheit(double value) + public static HeatTransferCoefficient FromBtusPerHourSquareFootDegreeFahrenheit(QuantityValue value) { return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit); } @@ -318,7 +300,7 @@ public static HeatTransferCoefficient FromBtusPerHourSquareFootDegreeFahrenheit( /// /// Creates a from . /// - public static HeatTransferCoefficient FromCaloriesPerHourSquareMeterDegreeCelsius(double value) + public static HeatTransferCoefficient FromCaloriesPerHourSquareMeterDegreeCelsius(QuantityValue value) { return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius); } @@ -326,7 +308,7 @@ public static HeatTransferCoefficient FromCaloriesPerHourSquareMeterDegreeCelsiu /// /// Creates a from . /// - public static HeatTransferCoefficient FromKilocaloriesPerHourSquareMeterDegreeCelsius(double value) + public static HeatTransferCoefficient FromKilocaloriesPerHourSquareMeterDegreeCelsius(QuantityValue value) { return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius); } @@ -334,7 +316,7 @@ public static HeatTransferCoefficient FromKilocaloriesPerHourSquareMeterDegreeCe /// /// Creates a from . /// - public static HeatTransferCoefficient FromWattsPerSquareMeterCelsius(double value) + public static HeatTransferCoefficient FromWattsPerSquareMeterCelsius(QuantityValue value) { return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius); } @@ -342,7 +324,7 @@ public static HeatTransferCoefficient FromWattsPerSquareMeterCelsius(double valu /// /// Creates a from . /// - public static HeatTransferCoefficient FromWattsPerSquareMeterKelvin(double value) + public static HeatTransferCoefficient FromWattsPerSquareMeterKelvin(QuantityValue value) { return new HeatTransferCoefficient(value, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin); } @@ -353,7 +335,7 @@ public static HeatTransferCoefficient FromWattsPerSquareMeterKelvin(double value /// Value to convert from. /// Unit to convert from. /// HeatTransferCoefficient unit value. - public static HeatTransferCoefficient From(double value, HeatTransferCoefficientUnit fromUnit) + public static HeatTransferCoefficient From(QuantityValue value, HeatTransferCoefficientUnit fromUnit) { return new HeatTransferCoefficient(value, fromUnit); } @@ -414,10 +396,7 @@ public static HeatTransferCoefficient Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static HeatTransferCoefficient Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -445,11 +424,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out HeatTransferCoef /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out HeatTransferCoefficient result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -470,7 +445,7 @@ public static HeatTransferCoefficientUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -481,7 +456,7 @@ public static HeatTransferCoefficientUnit ParseUnit(string str, IFormatProvider? return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out HeatTransferCoefficientUnit unit) { return TryParseUnit(str, null, out unit); @@ -496,7 +471,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out HeatTransfer /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out HeatTransferCoefficientUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -515,35 +490,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static HeatTransferCoefficient operator +(HeatTransferCoefficient left, HeatTransferCoefficient right) { - return new HeatTransferCoefficient(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new HeatTransferCoefficient(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static HeatTransferCoefficient operator -(HeatTransferCoefficient left, HeatTransferCoefficient right) { - return new HeatTransferCoefficient(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new HeatTransferCoefficient(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -555,97 +530,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(HeatTransferCoefficient left, HeatTransferCoefficient right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(HeatTransferCoefficient left, HeatTransferCoefficient right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(HeatTransferCoefficient left, HeatTransferCoefficient right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(HeatTransferCoefficient left, HeatTransferCoefficient right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(HeatTransferCoefficient other, HeatTransferCoefficient tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(HeatTransferCoefficient left, HeatTransferCoefficient right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(HeatTransferCoefficient other, HeatTransferCoefficient tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(HeatTransferCoefficient left, HeatTransferCoefficient right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(HeatTransferCoefficient other, HeatTransferCoefficient tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is HeatTransferCoefficient otherQuantity)) + if (obj is not HeatTransferCoefficient otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(HeatTransferCoefficient other, HeatTransferCoefficient tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(HeatTransferCoefficient other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current HeatTransferCoefficient. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(HeatTransferCoefficient), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is HeatTransferCoefficient otherQuantity)) throw new ArgumentException("Expected type HeatTransferCoefficient.", nameof(obj)); + if (obj is not HeatTransferCoefficient otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -657,154 +617,24 @@ public int CompareTo(object? obj) /// public int CompareTo(HeatTransferCoefficient other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(HeatTransferCoefficientUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this HeatTransferCoefficient to another HeatTransferCoefficient with the unit representation . - /// - /// The unit to convert to. - /// A HeatTransferCoefficient with the specified unit. - public HeatTransferCoefficient ToUnit(HeatTransferCoefficientUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A HeatTransferCoefficient with the specified unit. - public HeatTransferCoefficient ToUnit(HeatTransferCoefficientUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(HeatTransferCoefficient), Unit, typeof(HeatTransferCoefficient), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (HeatTransferCoefficient)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(HeatTransferCoefficientUnit unit, [NotNullWhen(true)] out HeatTransferCoefficient? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - HeatTransferCoefficient? convertedOrNull = (Unit, unit) switch - { - // HeatTransferCoefficientUnit -> BaseUnit - (HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin) => new HeatTransferCoefficient(_value * ((1055.05585262 / (0.3048 * 0.3048 * 3600)) * 1.8), HeatTransferCoefficientUnit.WattPerSquareMeterKelvin), - (HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin) => new HeatTransferCoefficient((_value * 4.184) / 3600, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin), - (HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin) => new HeatTransferCoefficient(((_value * 4.184) / 3600) * 1e3d, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin), - (HeatTransferCoefficientUnit.WattPerSquareMeterCelsius, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin) => new HeatTransferCoefficient(_value, HeatTransferCoefficientUnit.WattPerSquareMeterKelvin), - - // BaseUnit -> HeatTransferCoefficientUnit - (HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit) => new HeatTransferCoefficient(_value / ((1055.05585262 / (0.3048 * 0.3048 * 3600)) * 1.8), HeatTransferCoefficientUnit.BtuPerHourSquareFootDegreeFahrenheit), - (HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius) => new HeatTransferCoefficient((_value / 4.184) * 3600, HeatTransferCoefficientUnit.CaloriePerHourSquareMeterDegreeCelsius), - (HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius) => new HeatTransferCoefficient(((_value / 4.184) * 3600) / 1e3d, HeatTransferCoefficientUnit.KilocaloriePerHourSquareMeterDegreeCelsius), - (HeatTransferCoefficientUnit.WattPerSquareMeterKelvin, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius) => new HeatTransferCoefficient(_value, HeatTransferCoefficientUnit.WattPerSquareMeterCelsius), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public HeatTransferCoefficient ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not HeatTransferCoefficientUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(HeatTransferCoefficientUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(HeatTransferCoefficientUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(HeatTransferCoefficientUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -819,7 +649,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs b/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs index 9ee5838445..95f868be6d 100644 --- a/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Illuminance.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Illuminance /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Illuminance : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -56,13 +55,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly IlluminanceUnit? _unit; /// @@ -107,7 +106,7 @@ public static IlluminanceInfo CreateDefault(Func - /// The for is [L^-2][J]. + /// The for is L^-2J. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 0, 0, 0, 0, 0, 1); @@ -122,18 +121,22 @@ public static IlluminanceInfo CreateDefault(FuncAn of representing the default unit mappings for Illuminance. public static IEnumerable> GetDefaultMappings() { - yield return new (IlluminanceUnit.Kilolux, "Kilolux", "Kilolux", BaseUnits.Undefined); + yield return new (IlluminanceUnit.Kilolux, "Kilolux", "Kilolux", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); yield return new (IlluminanceUnit.Lux, "Lux", "Lux", new BaseUnits(length: LengthUnit.Meter, luminousIntensity: LuminousIntensityUnit.Candela)); - yield return new (IlluminanceUnit.Megalux, "Megalux", "Megalux", new BaseUnits(length: LengthUnit.Millimeter, luminousIntensity: LuminousIntensityUnit.Candela)); - yield return new (IlluminanceUnit.Millilux, "Millilux", "Millilux", BaseUnits.Undefined); + yield return new (IlluminanceUnit.Megalux, "Megalux", "Megalux", new BaseUnits(length: LengthUnit.Millimeter, luminousIntensity: LuminousIntensityUnit.Candela), + new QuantityValue(1, 1000000) + ); + yield return new (IlluminanceUnit.Millilux, "Millilux", "Millilux", BaseUnits.Undefined, + 1000 + ); } } static Illuminance() { - Info = IlluminanceInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(IlluminanceInfo.CreateDefault); } /// @@ -141,7 +144,7 @@ static Illuminance() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Illuminance(double value, IlluminanceUnit unit) + public Illuminance(QuantityValue value, IlluminanceUnit unit) { _value = value; _unit = unit; @@ -155,7 +158,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -166,7 +169,8 @@ public Illuminance(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -195,10 +199,8 @@ public Illuminance(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public IlluminanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -237,49 +239,29 @@ public Illuminance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilolux => As(IlluminanceUnit.Kilolux); + public QuantityValue Kilolux => this.As(IlluminanceUnit.Kilolux); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Lux => As(IlluminanceUnit.Lux); + public QuantityValue Lux => this.As(IlluminanceUnit.Lux); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megalux => As(IlluminanceUnit.Megalux); + public QuantityValue Megalux => this.As(IlluminanceUnit.Megalux); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millilux => As(IlluminanceUnit.Millilux); + public QuantityValue Millilux => this.As(IlluminanceUnit.Millilux); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: IlluminanceUnit -> BaseUnit - unitConverter.SetConversionFunction(IlluminanceUnit.Kilolux, IlluminanceUnit.Lux, quantity => quantity.ToUnit(IlluminanceUnit.Lux)); - unitConverter.SetConversionFunction(IlluminanceUnit.Megalux, IlluminanceUnit.Lux, quantity => quantity.ToUnit(IlluminanceUnit.Lux)); - unitConverter.SetConversionFunction(IlluminanceUnit.Millilux, IlluminanceUnit.Lux, quantity => quantity.ToUnit(IlluminanceUnit.Lux)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(IlluminanceUnit.Lux, IlluminanceUnit.Lux, quantity => quantity); - - // Register in unit converter: BaseUnit -> IlluminanceUnit - unitConverter.SetConversionFunction(IlluminanceUnit.Lux, IlluminanceUnit.Kilolux, quantity => quantity.ToUnit(IlluminanceUnit.Kilolux)); - unitConverter.SetConversionFunction(IlluminanceUnit.Lux, IlluminanceUnit.Megalux, quantity => quantity.ToUnit(IlluminanceUnit.Megalux)); - unitConverter.SetConversionFunction(IlluminanceUnit.Lux, IlluminanceUnit.Millilux, quantity => quantity.ToUnit(IlluminanceUnit.Millilux)); - } - /// /// Get unit abbreviation string. /// @@ -308,7 +290,7 @@ public static string GetAbbreviation(IlluminanceUnit unit, IFormatProvider? prov /// /// Creates a from . /// - public static Illuminance FromKilolux(double value) + public static Illuminance FromKilolux(QuantityValue value) { return new Illuminance(value, IlluminanceUnit.Kilolux); } @@ -316,7 +298,7 @@ public static Illuminance FromKilolux(double value) /// /// Creates a from . /// - public static Illuminance FromLux(double value) + public static Illuminance FromLux(QuantityValue value) { return new Illuminance(value, IlluminanceUnit.Lux); } @@ -324,7 +306,7 @@ public static Illuminance FromLux(double value) /// /// Creates a from . /// - public static Illuminance FromMegalux(double value) + public static Illuminance FromMegalux(QuantityValue value) { return new Illuminance(value, IlluminanceUnit.Megalux); } @@ -332,7 +314,7 @@ public static Illuminance FromMegalux(double value) /// /// Creates a from . /// - public static Illuminance FromMillilux(double value) + public static Illuminance FromMillilux(QuantityValue value) { return new Illuminance(value, IlluminanceUnit.Millilux); } @@ -343,7 +325,7 @@ public static Illuminance FromMillilux(double value) /// Value to convert from. /// Unit to convert from. /// Illuminance unit value. - public static Illuminance From(double value, IlluminanceUnit fromUnit) + public static Illuminance From(QuantityValue value, IlluminanceUnit fromUnit) { return new Illuminance(value, fromUnit); } @@ -404,10 +386,7 @@ public static Illuminance Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Illuminance Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -435,11 +414,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Illuminance resu /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Illuminance result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -460,7 +435,7 @@ public static IlluminanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -471,7 +446,7 @@ public static IlluminanceUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out IlluminanceUnit unit) { return TryParseUnit(str, null, out unit); @@ -486,7 +461,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out IlluminanceU /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out IlluminanceUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -505,35 +480,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Illuminance operator +(Illuminance left, Illuminance right) { - return new Illuminance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Illuminance(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Illuminance operator -(Illuminance left, Illuminance right) { - return new Illuminance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Illuminance(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -555,97 +530,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Illuminance left, Illuminance right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Illuminance left, Illuminance right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Illuminance left, Illuminance right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Illuminance left, Illuminance right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Illuminance other, Illuminance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Illuminance left, Illuminance right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Illuminance other, Illuminance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Illuminance left, Illuminance right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Illuminance other, Illuminance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Illuminance otherQuantity)) + if (obj is not Illuminance otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Illuminance other, Illuminance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Illuminance other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Illuminance. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Illuminance), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Illuminance otherQuantity)) throw new ArgumentException("Expected type Illuminance.", nameof(obj)); + if (obj is not Illuminance otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -657,152 +617,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Illuminance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(IlluminanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this Illuminance to another Illuminance with the unit representation . - /// - /// The unit to convert to. - /// A Illuminance with the specified unit. - public Illuminance ToUnit(IlluminanceUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Illuminance with the specified unit. - public Illuminance ToUnit(IlluminanceUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Illuminance), Unit, typeof(Illuminance), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Illuminance)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(IlluminanceUnit unit, [NotNullWhen(true)] out Illuminance? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Illuminance? convertedOrNull = (Unit, unit) switch - { - // IlluminanceUnit -> BaseUnit - (IlluminanceUnit.Kilolux, IlluminanceUnit.Lux) => new Illuminance((_value) * 1e3d, IlluminanceUnit.Lux), - (IlluminanceUnit.Megalux, IlluminanceUnit.Lux) => new Illuminance((_value) * 1e6d, IlluminanceUnit.Lux), - (IlluminanceUnit.Millilux, IlluminanceUnit.Lux) => new Illuminance((_value) * 1e-3d, IlluminanceUnit.Lux), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> IlluminanceUnit - (IlluminanceUnit.Lux, IlluminanceUnit.Kilolux) => new Illuminance((_value) / 1e3d, IlluminanceUnit.Kilolux), - (IlluminanceUnit.Lux, IlluminanceUnit.Megalux) => new Illuminance((_value) / 1e6d, IlluminanceUnit.Megalux), - (IlluminanceUnit.Lux, IlluminanceUnit.Millilux) => new Illuminance((_value) / 1e-3d, IlluminanceUnit.Millilux), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Illuminance ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not IlluminanceUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IlluminanceUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is IlluminanceUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IlluminanceUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(IlluminanceUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(IlluminanceUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -817,7 +649,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Impulse.g.cs b/UnitsNet/GeneratedCode/Quantities/Impulse.g.cs index 5af1def28a..589b7ff0f9 100644 --- a/UnitsNet/GeneratedCode/Quantities/Impulse.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Impulse.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// In classical mechanics, impulse is the integral of a force, F, over the time interval, t, for which it acts. Impulse applied to an object produces an equivalent vector change in its linear momentum, also in the resultant direction. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Impulse : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ImpulseUnit? _unit; /// @@ -101,7 +100,7 @@ public static ImpulseInfo CreateDefault(Func - /// The for is [T^-1][L][M]. + /// The for is T^-1LM. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 1, -1, 0, 0, 0, 0); @@ -116,27 +115,49 @@ public static ImpulseInfo CreateDefault(FuncAn of representing the default unit mappings for Impulse. public static IEnumerable> GetDefaultMappings() { - yield return new (ImpulseUnit.CentinewtonSecond, "CentinewtonSecond", "CentinewtonSeconds", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ImpulseUnit.DecanewtonSecond, "DecanewtonSecond", "DecanewtonSeconds", new BaseUnits(length: LengthUnit.Decameter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ImpulseUnit.DecinewtonSecond, "DecinewtonSecond", "DecinewtonSeconds", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ImpulseUnit.KilogramMeterPerSecond, "KilogramMeterPerSecond", "KilogramMetersPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ImpulseUnit.KilonewtonSecond, "KilonewtonSecond", "KilonewtonSeconds", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ImpulseUnit.MeganewtonSecond, "MeganewtonSecond", "MeganewtonSeconds", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ImpulseUnit.MicronewtonSecond, "MicronewtonSecond", "MicronewtonSeconds", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ImpulseUnit.MillinewtonSecond, "MillinewtonSecond", "MillinewtonSeconds", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ImpulseUnit.NanonewtonSecond, "NanonewtonSecond", "NanonewtonSeconds", new BaseUnits(length: LengthUnit.Nanometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); + yield return new (ImpulseUnit.CentinewtonSecond, "CentinewtonSecond", "CentinewtonSeconds", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + 100 + ); + yield return new (ImpulseUnit.DecanewtonSecond, "DecanewtonSecond", "DecanewtonSeconds", new BaseUnits(length: LengthUnit.Decameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 10) + ); + yield return new (ImpulseUnit.DecinewtonSecond, "DecinewtonSecond", "DecinewtonSeconds", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + 10 + ); + yield return new (ImpulseUnit.KilogramMeterPerSecond, "KilogramMeterPerSecond", "KilogramMetersPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + 1 + ); + yield return new (ImpulseUnit.KilonewtonSecond, "KilonewtonSecond", "KilonewtonSeconds", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000) + ); + yield return new (ImpulseUnit.MeganewtonSecond, "MeganewtonSecond", "MeganewtonSeconds", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (ImpulseUnit.MicronewtonSecond, "MicronewtonSecond", "MicronewtonSeconds", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + 1000000 + ); + yield return new (ImpulseUnit.MillinewtonSecond, "MillinewtonSecond", "MillinewtonSeconds", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + 1000 + ); + yield return new (ImpulseUnit.NanonewtonSecond, "NanonewtonSecond", "NanonewtonSeconds", new BaseUnits(length: LengthUnit.Nanometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + 1000000000 + ); yield return new (ImpulseUnit.NewtonSecond, "NewtonSecond", "NewtonSeconds", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (ImpulseUnit.PoundFootPerSecond, "PoundFootPerSecond", "PoundFeetPerSecond", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound, time: DurationUnit.Second)); - yield return new (ImpulseUnit.PoundForceSecond, "PoundForceSecond", "PoundForceSeconds", BaseUnits.Undefined); - yield return new (ImpulseUnit.SlugFootPerSecond, "SlugFootPerSecond", "SlugFeetPerSecond", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Slug, time: DurationUnit.Second)); + yield return new (ImpulseUnit.PoundFootPerSecond, "PoundFootPerSecond", "PoundFeetPerSecond", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound, time: DurationUnit.Second), + new QuantityValue(125000000000, 17281869297) + ); + yield return new (ImpulseUnit.PoundForceSecond, "PoundForceSecond", "PoundForceSeconds", BaseUnits.Undefined, + new QuantityValue(2000000000000, 8896443230521) + ); + yield return new (ImpulseUnit.SlugFootPerSecond, "SlugFootPerSecond", "SlugFeetPerSecond", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Slug, time: DurationUnit.Second), + new QuantityValue(2000000000000, 8896443230521) + ); } } static Impulse() { - Info = ImpulseInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ImpulseInfo.CreateDefault); } /// @@ -144,7 +165,7 @@ static Impulse() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Impulse(double value, ImpulseUnit unit) + public Impulse(QuantityValue value, ImpulseUnit unit) { _value = value; _unit = unit; @@ -158,7 +179,7 @@ public Impulse(double value, ImpulseUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Impulse(double value, UnitSystem unitSystem) + public Impulse(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -169,7 +190,8 @@ public Impulse(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -198,10 +220,8 @@ public Impulse(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ImpulseUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -240,112 +260,74 @@ public Impulse(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentinewtonSeconds => As(ImpulseUnit.CentinewtonSecond); + public QuantityValue CentinewtonSeconds => this.As(ImpulseUnit.CentinewtonSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecanewtonSeconds => As(ImpulseUnit.DecanewtonSecond); + public QuantityValue DecanewtonSeconds => this.As(ImpulseUnit.DecanewtonSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecinewtonSeconds => As(ImpulseUnit.DecinewtonSecond); + public QuantityValue DecinewtonSeconds => this.As(ImpulseUnit.DecinewtonSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramMetersPerSecond => As(ImpulseUnit.KilogramMeterPerSecond); + public QuantityValue KilogramMetersPerSecond => this.As(ImpulseUnit.KilogramMeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonSeconds => As(ImpulseUnit.KilonewtonSecond); + public QuantityValue KilonewtonSeconds => this.As(ImpulseUnit.KilonewtonSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MeganewtonSeconds => As(ImpulseUnit.MeganewtonSecond); + public QuantityValue MeganewtonSeconds => this.As(ImpulseUnit.MeganewtonSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicronewtonSeconds => As(ImpulseUnit.MicronewtonSecond); + public QuantityValue MicronewtonSeconds => this.As(ImpulseUnit.MicronewtonSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillinewtonSeconds => As(ImpulseUnit.MillinewtonSecond); + public QuantityValue MillinewtonSeconds => this.As(ImpulseUnit.MillinewtonSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanonewtonSeconds => As(ImpulseUnit.NanonewtonSecond); + public QuantityValue NanonewtonSeconds => this.As(ImpulseUnit.NanonewtonSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonSeconds => As(ImpulseUnit.NewtonSecond); + public QuantityValue NewtonSeconds => this.As(ImpulseUnit.NewtonSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundFeetPerSecond => As(ImpulseUnit.PoundFootPerSecond); + public QuantityValue PoundFeetPerSecond => this.As(ImpulseUnit.PoundFootPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundForceSeconds => As(ImpulseUnit.PoundForceSecond); + public QuantityValue PoundForceSeconds => this.As(ImpulseUnit.PoundForceSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SlugFeetPerSecond => As(ImpulseUnit.SlugFootPerSecond); + public QuantityValue SlugFeetPerSecond => this.As(ImpulseUnit.SlugFootPerSecond); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ImpulseUnit -> BaseUnit - unitConverter.SetConversionFunction(ImpulseUnit.CentinewtonSecond, ImpulseUnit.NewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.NewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.DecanewtonSecond, ImpulseUnit.NewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.NewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.DecinewtonSecond, ImpulseUnit.NewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.NewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.KilogramMeterPerSecond, ImpulseUnit.NewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.NewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.KilonewtonSecond, ImpulseUnit.NewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.NewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.MeganewtonSecond, ImpulseUnit.NewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.NewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.MicronewtonSecond, ImpulseUnit.NewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.NewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.MillinewtonSecond, ImpulseUnit.NewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.NewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.NanonewtonSecond, ImpulseUnit.NewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.NewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.PoundFootPerSecond, ImpulseUnit.NewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.NewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.PoundForceSecond, ImpulseUnit.NewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.NewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.SlugFootPerSecond, ImpulseUnit.NewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.NewtonSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ImpulseUnit.NewtonSecond, ImpulseUnit.NewtonSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> ImpulseUnit - unitConverter.SetConversionFunction(ImpulseUnit.NewtonSecond, ImpulseUnit.CentinewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.CentinewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.NewtonSecond, ImpulseUnit.DecanewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.DecanewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.NewtonSecond, ImpulseUnit.DecinewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.DecinewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.NewtonSecond, ImpulseUnit.KilogramMeterPerSecond, quantity => quantity.ToUnit(ImpulseUnit.KilogramMeterPerSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.NewtonSecond, ImpulseUnit.KilonewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.KilonewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.NewtonSecond, ImpulseUnit.MeganewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.MeganewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.NewtonSecond, ImpulseUnit.MicronewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.MicronewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.NewtonSecond, ImpulseUnit.MillinewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.MillinewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.NewtonSecond, ImpulseUnit.NanonewtonSecond, quantity => quantity.ToUnit(ImpulseUnit.NanonewtonSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.NewtonSecond, ImpulseUnit.PoundFootPerSecond, quantity => quantity.ToUnit(ImpulseUnit.PoundFootPerSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.NewtonSecond, ImpulseUnit.PoundForceSecond, quantity => quantity.ToUnit(ImpulseUnit.PoundForceSecond)); - unitConverter.SetConversionFunction(ImpulseUnit.NewtonSecond, ImpulseUnit.SlugFootPerSecond, quantity => quantity.ToUnit(ImpulseUnit.SlugFootPerSecond)); - } - /// /// Get unit abbreviation string. /// @@ -374,7 +356,7 @@ public static string GetAbbreviation(ImpulseUnit unit, IFormatProvider? provider /// /// Creates a from . /// - public static Impulse FromCentinewtonSeconds(double value) + public static Impulse FromCentinewtonSeconds(QuantityValue value) { return new Impulse(value, ImpulseUnit.CentinewtonSecond); } @@ -382,7 +364,7 @@ public static Impulse FromCentinewtonSeconds(double value) /// /// Creates a from . /// - public static Impulse FromDecanewtonSeconds(double value) + public static Impulse FromDecanewtonSeconds(QuantityValue value) { return new Impulse(value, ImpulseUnit.DecanewtonSecond); } @@ -390,7 +372,7 @@ public static Impulse FromDecanewtonSeconds(double value) /// /// Creates a from . /// - public static Impulse FromDecinewtonSeconds(double value) + public static Impulse FromDecinewtonSeconds(QuantityValue value) { return new Impulse(value, ImpulseUnit.DecinewtonSecond); } @@ -398,7 +380,7 @@ public static Impulse FromDecinewtonSeconds(double value) /// /// Creates a from . /// - public static Impulse FromKilogramMetersPerSecond(double value) + public static Impulse FromKilogramMetersPerSecond(QuantityValue value) { return new Impulse(value, ImpulseUnit.KilogramMeterPerSecond); } @@ -406,7 +388,7 @@ public static Impulse FromKilogramMetersPerSecond(double value) /// /// Creates a from . /// - public static Impulse FromKilonewtonSeconds(double value) + public static Impulse FromKilonewtonSeconds(QuantityValue value) { return new Impulse(value, ImpulseUnit.KilonewtonSecond); } @@ -414,7 +396,7 @@ public static Impulse FromKilonewtonSeconds(double value) /// /// Creates a from . /// - public static Impulse FromMeganewtonSeconds(double value) + public static Impulse FromMeganewtonSeconds(QuantityValue value) { return new Impulse(value, ImpulseUnit.MeganewtonSecond); } @@ -422,7 +404,7 @@ public static Impulse FromMeganewtonSeconds(double value) /// /// Creates a from . /// - public static Impulse FromMicronewtonSeconds(double value) + public static Impulse FromMicronewtonSeconds(QuantityValue value) { return new Impulse(value, ImpulseUnit.MicronewtonSecond); } @@ -430,7 +412,7 @@ public static Impulse FromMicronewtonSeconds(double value) /// /// Creates a from . /// - public static Impulse FromMillinewtonSeconds(double value) + public static Impulse FromMillinewtonSeconds(QuantityValue value) { return new Impulse(value, ImpulseUnit.MillinewtonSecond); } @@ -438,7 +420,7 @@ public static Impulse FromMillinewtonSeconds(double value) /// /// Creates a from . /// - public static Impulse FromNanonewtonSeconds(double value) + public static Impulse FromNanonewtonSeconds(QuantityValue value) { return new Impulse(value, ImpulseUnit.NanonewtonSecond); } @@ -446,7 +428,7 @@ public static Impulse FromNanonewtonSeconds(double value) /// /// Creates a from . /// - public static Impulse FromNewtonSeconds(double value) + public static Impulse FromNewtonSeconds(QuantityValue value) { return new Impulse(value, ImpulseUnit.NewtonSecond); } @@ -454,7 +436,7 @@ public static Impulse FromNewtonSeconds(double value) /// /// Creates a from . /// - public static Impulse FromPoundFeetPerSecond(double value) + public static Impulse FromPoundFeetPerSecond(QuantityValue value) { return new Impulse(value, ImpulseUnit.PoundFootPerSecond); } @@ -462,7 +444,7 @@ public static Impulse FromPoundFeetPerSecond(double value) /// /// Creates a from . /// - public static Impulse FromPoundForceSeconds(double value) + public static Impulse FromPoundForceSeconds(QuantityValue value) { return new Impulse(value, ImpulseUnit.PoundForceSecond); } @@ -470,7 +452,7 @@ public static Impulse FromPoundForceSeconds(double value) /// /// Creates a from . /// - public static Impulse FromSlugFeetPerSecond(double value) + public static Impulse FromSlugFeetPerSecond(QuantityValue value) { return new Impulse(value, ImpulseUnit.SlugFootPerSecond); } @@ -481,7 +463,7 @@ public static Impulse FromSlugFeetPerSecond(double value) /// Value to convert from. /// Unit to convert from. /// Impulse unit value. - public static Impulse From(double value, ImpulseUnit fromUnit) + public static Impulse From(QuantityValue value, ImpulseUnit fromUnit) { return new Impulse(value, fromUnit); } @@ -542,10 +524,7 @@ public static Impulse Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Impulse Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -573,11 +552,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Impulse result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Impulse result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -598,7 +573,7 @@ public static ImpulseUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -609,7 +584,7 @@ public static ImpulseUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ImpulseUnit unit) { return TryParseUnit(str, null, out unit); @@ -624,7 +599,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ImpulseUnit /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ImpulseUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -643,35 +618,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Impulse operator +(Impulse left, Impulse right) { - return new Impulse(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Impulse(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Impulse operator -(Impulse left, Impulse right) { - return new Impulse(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Impulse(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static Impulse operator *(double left, Impulse right) + public static Impulse operator *(QuantityValue left, Impulse right) { return new Impulse(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Impulse operator *(Impulse left, double right) + public static Impulse operator *(Impulse left, QuantityValue right) { return new Impulse(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Impulse operator /(Impulse left, double right) + public static Impulse operator /(Impulse left, QuantityValue right) { return new Impulse(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Impulse left, Impulse right) + public static QuantityValue operator /(Impulse left, Impulse right) { return left.NewtonSeconds / right.NewtonSeconds; } @@ -683,97 +658,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Impulse left, Impulse right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Impulse left, Impulse right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Impulse left, Impulse right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Impulse left, Impulse right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Impulse other, Impulse tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Impulse left, Impulse right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Impulse other, Impulse tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Impulse left, Impulse right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Impulse other, Impulse tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Impulse otherQuantity)) + if (obj is not Impulse otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Impulse other, Impulse tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Impulse other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Impulse. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Impulse), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Impulse otherQuantity)) throw new ArgumentException("Expected type Impulse.", nameof(obj)); + if (obj is not Impulse otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -785,170 +745,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Impulse other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ImpulseUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Impulse to another Impulse with the unit representation . - /// - /// The unit to convert to. - /// A Impulse with the specified unit. - public Impulse ToUnit(ImpulseUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Impulse with the specified unit. - public Impulse ToUnit(ImpulseUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Impulse), Unit, typeof(Impulse), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Impulse)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ImpulseUnit unit, [NotNullWhen(true)] out Impulse? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Impulse? convertedOrNull = (Unit, unit) switch - { - // ImpulseUnit -> BaseUnit - (ImpulseUnit.CentinewtonSecond, ImpulseUnit.NewtonSecond) => new Impulse((_value) * 1e-2d, ImpulseUnit.NewtonSecond), - (ImpulseUnit.DecanewtonSecond, ImpulseUnit.NewtonSecond) => new Impulse((_value) * 1e1d, ImpulseUnit.NewtonSecond), - (ImpulseUnit.DecinewtonSecond, ImpulseUnit.NewtonSecond) => new Impulse((_value) * 1e-1d, ImpulseUnit.NewtonSecond), - (ImpulseUnit.KilogramMeterPerSecond, ImpulseUnit.NewtonSecond) => new Impulse(_value, ImpulseUnit.NewtonSecond), - (ImpulseUnit.KilonewtonSecond, ImpulseUnit.NewtonSecond) => new Impulse((_value) * 1e3d, ImpulseUnit.NewtonSecond), - (ImpulseUnit.MeganewtonSecond, ImpulseUnit.NewtonSecond) => new Impulse((_value) * 1e6d, ImpulseUnit.NewtonSecond), - (ImpulseUnit.MicronewtonSecond, ImpulseUnit.NewtonSecond) => new Impulse((_value) * 1e-6d, ImpulseUnit.NewtonSecond), - (ImpulseUnit.MillinewtonSecond, ImpulseUnit.NewtonSecond) => new Impulse((_value) * 1e-3d, ImpulseUnit.NewtonSecond), - (ImpulseUnit.NanonewtonSecond, ImpulseUnit.NewtonSecond) => new Impulse((_value) * 1e-9d, ImpulseUnit.NewtonSecond), - (ImpulseUnit.PoundFootPerSecond, ImpulseUnit.NewtonSecond) => new Impulse(_value * (0.45359237 * 0.3048), ImpulseUnit.NewtonSecond), - (ImpulseUnit.PoundForceSecond, ImpulseUnit.NewtonSecond) => new Impulse(_value * 0.45359237 * 9.80665, ImpulseUnit.NewtonSecond), - (ImpulseUnit.SlugFootPerSecond, ImpulseUnit.NewtonSecond) => new Impulse(_value * (0.45359237 * 9.80665), ImpulseUnit.NewtonSecond), - - // BaseUnit -> ImpulseUnit - (ImpulseUnit.NewtonSecond, ImpulseUnit.CentinewtonSecond) => new Impulse((_value) / 1e-2d, ImpulseUnit.CentinewtonSecond), - (ImpulseUnit.NewtonSecond, ImpulseUnit.DecanewtonSecond) => new Impulse((_value) / 1e1d, ImpulseUnit.DecanewtonSecond), - (ImpulseUnit.NewtonSecond, ImpulseUnit.DecinewtonSecond) => new Impulse((_value) / 1e-1d, ImpulseUnit.DecinewtonSecond), - (ImpulseUnit.NewtonSecond, ImpulseUnit.KilogramMeterPerSecond) => new Impulse(_value, ImpulseUnit.KilogramMeterPerSecond), - (ImpulseUnit.NewtonSecond, ImpulseUnit.KilonewtonSecond) => new Impulse((_value) / 1e3d, ImpulseUnit.KilonewtonSecond), - (ImpulseUnit.NewtonSecond, ImpulseUnit.MeganewtonSecond) => new Impulse((_value) / 1e6d, ImpulseUnit.MeganewtonSecond), - (ImpulseUnit.NewtonSecond, ImpulseUnit.MicronewtonSecond) => new Impulse((_value) / 1e-6d, ImpulseUnit.MicronewtonSecond), - (ImpulseUnit.NewtonSecond, ImpulseUnit.MillinewtonSecond) => new Impulse((_value) / 1e-3d, ImpulseUnit.MillinewtonSecond), - (ImpulseUnit.NewtonSecond, ImpulseUnit.NanonewtonSecond) => new Impulse((_value) / 1e-9d, ImpulseUnit.NanonewtonSecond), - (ImpulseUnit.NewtonSecond, ImpulseUnit.PoundFootPerSecond) => new Impulse(_value / (0.45359237 * 0.3048), ImpulseUnit.PoundFootPerSecond), - (ImpulseUnit.NewtonSecond, ImpulseUnit.PoundForceSecond) => new Impulse(_value / (0.45359237 * 9.80665), ImpulseUnit.PoundForceSecond), - (ImpulseUnit.NewtonSecond, ImpulseUnit.SlugFootPerSecond) => new Impulse(_value / (0.45359237 * 9.80665), ImpulseUnit.SlugFootPerSecond), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Impulse ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ImpulseUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ImpulseUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ImpulseUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ImpulseUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ImpulseUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ImpulseUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -963,7 +777,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Information.g.cs b/UnitsNet/GeneratedCode/Quantities/Information.g.cs index dfc2c6d0b0..4398256f1f 100644 --- a/UnitsNet/GeneratedCode/Quantities/Information.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Information.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Information : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly InformationUnit? _unit; /// @@ -117,52 +116,126 @@ public static InformationInfo CreateDefault(Func> GetDefaultMappings() { yield return new (InformationUnit.Bit, "Bit", "Bits", BaseUnits.Undefined); - yield return new (InformationUnit.Byte, "Byte", "Bytes", BaseUnits.Undefined); - yield return new (InformationUnit.Exabit, "Exabit", "Exabits", BaseUnits.Undefined); - yield return new (InformationUnit.Exabyte, "Exabyte", "Exabytes", BaseUnits.Undefined); - yield return new (InformationUnit.Exaoctet, "Exaoctet", "Exaoctets", BaseUnits.Undefined); - yield return new (InformationUnit.Exbibit, "Exbibit", "Exbibits", BaseUnits.Undefined); - yield return new (InformationUnit.Exbibyte, "Exbibyte", "Exbibytes", BaseUnits.Undefined); - yield return new (InformationUnit.Exbioctet, "Exbioctet", "Exbioctets", BaseUnits.Undefined); - yield return new (InformationUnit.Gibibit, "Gibibit", "Gibibits", BaseUnits.Undefined); - yield return new (InformationUnit.Gibibyte, "Gibibyte", "Gibibytes", BaseUnits.Undefined); - yield return new (InformationUnit.Gibioctet, "Gibioctet", "Gibioctets", BaseUnits.Undefined); - yield return new (InformationUnit.Gigabit, "Gigabit", "Gigabits", BaseUnits.Undefined); - yield return new (InformationUnit.Gigabyte, "Gigabyte", "Gigabytes", BaseUnits.Undefined); - yield return new (InformationUnit.Gigaoctet, "Gigaoctet", "Gigaoctets", BaseUnits.Undefined); - yield return new (InformationUnit.Kibibit, "Kibibit", "Kibibits", BaseUnits.Undefined); - yield return new (InformationUnit.Kibibyte, "Kibibyte", "Kibibytes", BaseUnits.Undefined); - yield return new (InformationUnit.Kibioctet, "Kibioctet", "Kibioctets", BaseUnits.Undefined); - yield return new (InformationUnit.Kilobit, "Kilobit", "Kilobits", BaseUnits.Undefined); - yield return new (InformationUnit.Kilobyte, "Kilobyte", "Kilobytes", BaseUnits.Undefined); - yield return new (InformationUnit.Kilooctet, "Kilooctet", "Kilooctets", BaseUnits.Undefined); - yield return new (InformationUnit.Mebibit, "Mebibit", "Mebibits", BaseUnits.Undefined); - yield return new (InformationUnit.Mebibyte, "Mebibyte", "Mebibytes", BaseUnits.Undefined); - yield return new (InformationUnit.Mebioctet, "Mebioctet", "Mebioctets", BaseUnits.Undefined); - yield return new (InformationUnit.Megabit, "Megabit", "Megabits", BaseUnits.Undefined); - yield return new (InformationUnit.Megabyte, "Megabyte", "Megabytes", BaseUnits.Undefined); - yield return new (InformationUnit.Megaoctet, "Megaoctet", "Megaoctets", BaseUnits.Undefined); - yield return new (InformationUnit.Octet, "Octet", "Octets", BaseUnits.Undefined); - yield return new (InformationUnit.Pebibit, "Pebibit", "Pebibits", BaseUnits.Undefined); - yield return new (InformationUnit.Pebibyte, "Pebibyte", "Pebibytes", BaseUnits.Undefined); - yield return new (InformationUnit.Pebioctet, "Pebioctet", "Pebioctets", BaseUnits.Undefined); - yield return new (InformationUnit.Petabit, "Petabit", "Petabits", BaseUnits.Undefined); - yield return new (InformationUnit.Petabyte, "Petabyte", "Petabytes", BaseUnits.Undefined); - yield return new (InformationUnit.Petaoctet, "Petaoctet", "Petaoctets", BaseUnits.Undefined); - yield return new (InformationUnit.Tebibit, "Tebibit", "Tebibits", BaseUnits.Undefined); - yield return new (InformationUnit.Tebibyte, "Tebibyte", "Tebibytes", BaseUnits.Undefined); - yield return new (InformationUnit.Tebioctet, "Tebioctet", "Tebioctets", BaseUnits.Undefined); - yield return new (InformationUnit.Terabit, "Terabit", "Terabits", BaseUnits.Undefined); - yield return new (InformationUnit.Terabyte, "Terabyte", "Terabytes", BaseUnits.Undefined); - yield return new (InformationUnit.Teraoctet, "Teraoctet", "Teraoctets", BaseUnits.Undefined); + yield return new (InformationUnit.Byte, "Byte", "Bytes", BaseUnits.Undefined, + new QuantityValue(1, 8) + ); + yield return new (InformationUnit.Exabit, "Exabit", "Exabits", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000000000) + ); + yield return new (InformationUnit.Exabyte, "Exabyte", "Exabytes", BaseUnits.Undefined, + new QuantityValue(1, 8000000000000000000) + ); + yield return new (InformationUnit.Exaoctet, "Exaoctet", "Exaoctets", BaseUnits.Undefined, + new QuantityValue(1, 8000000000000000000) + ); + yield return new (InformationUnit.Exbibit, "Exbibit", "Exbibits", BaseUnits.Undefined, + new QuantityValue(1, 1152921504606846976) + ); + yield return new (InformationUnit.Exbibyte, "Exbibyte", "Exbibytes", BaseUnits.Undefined, + new QuantityValue(1, BigInteger.Pow(2, 63)) + ); + yield return new (InformationUnit.Exbioctet, "Exbioctet", "Exbioctets", BaseUnits.Undefined, + new QuantityValue(1, BigInteger.Pow(2, 63)) + ); + yield return new (InformationUnit.Gibibit, "Gibibit", "Gibibits", BaseUnits.Undefined, + new QuantityValue(1, 1073741824) + ); + yield return new (InformationUnit.Gibibyte, "Gibibyte", "Gibibytes", BaseUnits.Undefined, + new QuantityValue(1, 8589934592) + ); + yield return new (InformationUnit.Gibioctet, "Gibioctet", "Gibioctets", BaseUnits.Undefined, + new QuantityValue(1, 8589934592) + ); + yield return new (InformationUnit.Gigabit, "Gigabit", "Gigabits", BaseUnits.Undefined, + new QuantityValue(1, 1000000000) + ); + yield return new (InformationUnit.Gigabyte, "Gigabyte", "Gigabytes", BaseUnits.Undefined, + new QuantityValue(1, 8000000000) + ); + yield return new (InformationUnit.Gigaoctet, "Gigaoctet", "Gigaoctets", BaseUnits.Undefined, + new QuantityValue(1, 8000000000) + ); + yield return new (InformationUnit.Kibibit, "Kibibit", "Kibibits", BaseUnits.Undefined, + new QuantityValue(1, 1024) + ); + yield return new (InformationUnit.Kibibyte, "Kibibyte", "Kibibytes", BaseUnits.Undefined, + new QuantityValue(1, 8192) + ); + yield return new (InformationUnit.Kibioctet, "Kibioctet", "Kibioctets", BaseUnits.Undefined, + new QuantityValue(1, 8192) + ); + yield return new (InformationUnit.Kilobit, "Kilobit", "Kilobits", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (InformationUnit.Kilobyte, "Kilobyte", "Kilobytes", BaseUnits.Undefined, + new QuantityValue(1, 8000) + ); + yield return new (InformationUnit.Kilooctet, "Kilooctet", "Kilooctets", BaseUnits.Undefined, + new QuantityValue(1, 8000) + ); + yield return new (InformationUnit.Mebibit, "Mebibit", "Mebibits", BaseUnits.Undefined, + new QuantityValue(1, 1048576) + ); + yield return new (InformationUnit.Mebibyte, "Mebibyte", "Mebibytes", BaseUnits.Undefined, + new QuantityValue(1, 8388608) + ); + yield return new (InformationUnit.Mebioctet, "Mebioctet", "Mebioctets", BaseUnits.Undefined, + new QuantityValue(1, 8388608) + ); + yield return new (InformationUnit.Megabit, "Megabit", "Megabits", BaseUnits.Undefined, + new QuantityValue(1, 1000000) + ); + yield return new (InformationUnit.Megabyte, "Megabyte", "Megabytes", BaseUnits.Undefined, + new QuantityValue(1, 8000000) + ); + yield return new (InformationUnit.Megaoctet, "Megaoctet", "Megaoctets", BaseUnits.Undefined, + new QuantityValue(1, 8000000) + ); + yield return new (InformationUnit.Octet, "Octet", "Octets", BaseUnits.Undefined, + new QuantityValue(1, 8) + ); + yield return new (InformationUnit.Pebibit, "Pebibit", "Pebibits", BaseUnits.Undefined, + new QuantityValue(1, 1125899906842624) + ); + yield return new (InformationUnit.Pebibyte, "Pebibyte", "Pebibytes", BaseUnits.Undefined, + new QuantityValue(1, 9007199254740992) + ); + yield return new (InformationUnit.Pebioctet, "Pebioctet", "Pebioctets", BaseUnits.Undefined, + new QuantityValue(1, 9007199254740992) + ); + yield return new (InformationUnit.Petabit, "Petabit", "Petabits", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000000) + ); + yield return new (InformationUnit.Petabyte, "Petabyte", "Petabytes", BaseUnits.Undefined, + new QuantityValue(1, 8000000000000000) + ); + yield return new (InformationUnit.Petaoctet, "Petaoctet", "Petaoctets", BaseUnits.Undefined, + new QuantityValue(1, 8000000000000000) + ); + yield return new (InformationUnit.Tebibit, "Tebibit", "Tebibits", BaseUnits.Undefined, + new QuantityValue(1, 1099511627776) + ); + yield return new (InformationUnit.Tebibyte, "Tebibyte", "Tebibytes", BaseUnits.Undefined, + new QuantityValue(1, 8796093022208) + ); + yield return new (InformationUnit.Tebioctet, "Tebioctet", "Tebioctets", BaseUnits.Undefined, + new QuantityValue(1, 8796093022208) + ); + yield return new (InformationUnit.Terabit, "Terabit", "Terabits", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000) + ); + yield return new (InformationUnit.Terabyte, "Terabyte", "Terabytes", BaseUnits.Undefined, + new QuantityValue(1, 8000000000000) + ); + yield return new (InformationUnit.Teraoctet, "Teraoctet", "Teraoctets", BaseUnits.Undefined, + new QuantityValue(1, 8000000000000) + ); } } static Information() { - Info = InformationInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(InformationInfo.CreateDefault); } /// @@ -170,7 +243,7 @@ static Information() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Information(double value, InformationUnit unit) + public Information(QuantityValue value, InformationUnit unit) { _value = value; _unit = unit; @@ -181,7 +254,8 @@ public Information(double value, InformationUnit unit) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -210,10 +284,8 @@ public Information(double value, InformationUnit unit) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public InformationUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -252,294 +324,204 @@ public Information(double value, InformationUnit unit) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Bits => As(InformationUnit.Bit); + public QuantityValue Bits => this.As(InformationUnit.Bit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Bytes => As(InformationUnit.Byte); + public QuantityValue Bytes => this.As(InformationUnit.Byte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Exabits => As(InformationUnit.Exabit); + public QuantityValue Exabits => this.As(InformationUnit.Exabit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Exabytes => As(InformationUnit.Exabyte); + public QuantityValue Exabytes => this.As(InformationUnit.Exabyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Exaoctets => As(InformationUnit.Exaoctet); + public QuantityValue Exaoctets => this.As(InformationUnit.Exaoctet); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Exbibits => As(InformationUnit.Exbibit); + public QuantityValue Exbibits => this.As(InformationUnit.Exbibit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Exbibytes => As(InformationUnit.Exbibyte); + public QuantityValue Exbibytes => this.As(InformationUnit.Exbibyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Exbioctets => As(InformationUnit.Exbioctet); + public QuantityValue Exbioctets => this.As(InformationUnit.Exbioctet); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gibibits => As(InformationUnit.Gibibit); + public QuantityValue Gibibits => this.As(InformationUnit.Gibibit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gibibytes => As(InformationUnit.Gibibyte); + public QuantityValue Gibibytes => this.As(InformationUnit.Gibibyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gibioctets => As(InformationUnit.Gibioctet); + public QuantityValue Gibioctets => this.As(InformationUnit.Gibioctet); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigabits => As(InformationUnit.Gigabit); + public QuantityValue Gigabits => this.As(InformationUnit.Gigabit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigabytes => As(InformationUnit.Gigabyte); + public QuantityValue Gigabytes => this.As(InformationUnit.Gigabyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigaoctets => As(InformationUnit.Gigaoctet); + public QuantityValue Gigaoctets => this.As(InformationUnit.Gigaoctet); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kibibits => As(InformationUnit.Kibibit); + public QuantityValue Kibibits => this.As(InformationUnit.Kibibit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kibibytes => As(InformationUnit.Kibibyte); + public QuantityValue Kibibytes => this.As(InformationUnit.Kibibyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kibioctets => As(InformationUnit.Kibioctet); + public QuantityValue Kibioctets => this.As(InformationUnit.Kibioctet); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilobits => As(InformationUnit.Kilobit); + public QuantityValue Kilobits => this.As(InformationUnit.Kilobit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilobytes => As(InformationUnit.Kilobyte); + public QuantityValue Kilobytes => this.As(InformationUnit.Kilobyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilooctets => As(InformationUnit.Kilooctet); + public QuantityValue Kilooctets => this.As(InformationUnit.Kilooctet); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Mebibits => As(InformationUnit.Mebibit); + public QuantityValue Mebibits => this.As(InformationUnit.Mebibit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Mebibytes => As(InformationUnit.Mebibyte); + public QuantityValue Mebibytes => this.As(InformationUnit.Mebibyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Mebioctets => As(InformationUnit.Mebioctet); + public QuantityValue Mebioctets => this.As(InformationUnit.Mebioctet); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megabits => As(InformationUnit.Megabit); + public QuantityValue Megabits => this.As(InformationUnit.Megabit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megabytes => As(InformationUnit.Megabyte); + public QuantityValue Megabytes => this.As(InformationUnit.Megabyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megaoctets => As(InformationUnit.Megaoctet); + public QuantityValue Megaoctets => this.As(InformationUnit.Megaoctet); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Octets => As(InformationUnit.Octet); + public QuantityValue Octets => this.As(InformationUnit.Octet); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Pebibits => As(InformationUnit.Pebibit); + public QuantityValue Pebibits => this.As(InformationUnit.Pebibit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Pebibytes => As(InformationUnit.Pebibyte); + public QuantityValue Pebibytes => this.As(InformationUnit.Pebibyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Pebioctets => As(InformationUnit.Pebioctet); + public QuantityValue Pebioctets => this.As(InformationUnit.Pebioctet); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Petabits => As(InformationUnit.Petabit); + public QuantityValue Petabits => this.As(InformationUnit.Petabit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Petabytes => As(InformationUnit.Petabyte); + public QuantityValue Petabytes => this.As(InformationUnit.Petabyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Petaoctets => As(InformationUnit.Petaoctet); + public QuantityValue Petaoctets => this.As(InformationUnit.Petaoctet); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Tebibits => As(InformationUnit.Tebibit); + public QuantityValue Tebibits => this.As(InformationUnit.Tebibit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Tebibytes => As(InformationUnit.Tebibyte); + public QuantityValue Tebibytes => this.As(InformationUnit.Tebibyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Tebioctets => As(InformationUnit.Tebioctet); + public QuantityValue Tebioctets => this.As(InformationUnit.Tebioctet); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Terabits => As(InformationUnit.Terabit); + public QuantityValue Terabits => this.As(InformationUnit.Terabit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Terabytes => As(InformationUnit.Terabyte); + public QuantityValue Terabytes => this.As(InformationUnit.Terabyte); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Teraoctets => As(InformationUnit.Teraoctet); + public QuantityValue Teraoctets => this.As(InformationUnit.Teraoctet); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: InformationUnit -> BaseUnit - unitConverter.SetConversionFunction(InformationUnit.Byte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Exabit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Exabyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Exaoctet, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Exbibit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Exbibyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Exbioctet, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Gibibit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Gibibyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Gibioctet, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Gigabit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Gigabyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Gigaoctet, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Kibibit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Kibibyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Kibioctet, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Kilobit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Kilobyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Kilooctet, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Mebibit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Mebibyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Mebioctet, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Megabit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Megabyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Megaoctet, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Octet, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Pebibit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Pebibyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Pebioctet, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Petabit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Petabyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Petaoctet, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Tebibit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Tebibyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Tebioctet, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Terabit, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Terabyte, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - unitConverter.SetConversionFunction(InformationUnit.Teraoctet, InformationUnit.Bit, quantity => quantity.ToUnit(InformationUnit.Bit)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Bit, quantity => quantity); - - // Register in unit converter: BaseUnit -> InformationUnit - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Byte, quantity => quantity.ToUnit(InformationUnit.Byte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Exabit, quantity => quantity.ToUnit(InformationUnit.Exabit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Exabyte, quantity => quantity.ToUnit(InformationUnit.Exabyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Exaoctet, quantity => quantity.ToUnit(InformationUnit.Exaoctet)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Exbibit, quantity => quantity.ToUnit(InformationUnit.Exbibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Exbibyte, quantity => quantity.ToUnit(InformationUnit.Exbibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Exbioctet, quantity => quantity.ToUnit(InformationUnit.Exbioctet)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gibibit, quantity => quantity.ToUnit(InformationUnit.Gibibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gibibyte, quantity => quantity.ToUnit(InformationUnit.Gibibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gibioctet, quantity => quantity.ToUnit(InformationUnit.Gibioctet)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gigabit, quantity => quantity.ToUnit(InformationUnit.Gigabit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gigabyte, quantity => quantity.ToUnit(InformationUnit.Gigabyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Gigaoctet, quantity => quantity.ToUnit(InformationUnit.Gigaoctet)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kibibit, quantity => quantity.ToUnit(InformationUnit.Kibibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kibibyte, quantity => quantity.ToUnit(InformationUnit.Kibibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kibioctet, quantity => quantity.ToUnit(InformationUnit.Kibioctet)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kilobit, quantity => quantity.ToUnit(InformationUnit.Kilobit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kilobyte, quantity => quantity.ToUnit(InformationUnit.Kilobyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Kilooctet, quantity => quantity.ToUnit(InformationUnit.Kilooctet)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Mebibit, quantity => quantity.ToUnit(InformationUnit.Mebibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Mebibyte, quantity => quantity.ToUnit(InformationUnit.Mebibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Mebioctet, quantity => quantity.ToUnit(InformationUnit.Mebioctet)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Megabit, quantity => quantity.ToUnit(InformationUnit.Megabit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Megabyte, quantity => quantity.ToUnit(InformationUnit.Megabyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Megaoctet, quantity => quantity.ToUnit(InformationUnit.Megaoctet)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Octet, quantity => quantity.ToUnit(InformationUnit.Octet)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Pebibit, quantity => quantity.ToUnit(InformationUnit.Pebibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Pebibyte, quantity => quantity.ToUnit(InformationUnit.Pebibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Pebioctet, quantity => quantity.ToUnit(InformationUnit.Pebioctet)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Petabit, quantity => quantity.ToUnit(InformationUnit.Petabit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Petabyte, quantity => quantity.ToUnit(InformationUnit.Petabyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Petaoctet, quantity => quantity.ToUnit(InformationUnit.Petaoctet)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Tebibit, quantity => quantity.ToUnit(InformationUnit.Tebibit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Tebibyte, quantity => quantity.ToUnit(InformationUnit.Tebibyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Tebioctet, quantity => quantity.ToUnit(InformationUnit.Tebioctet)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Terabit, quantity => quantity.ToUnit(InformationUnit.Terabit)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Terabyte, quantity => quantity.ToUnit(InformationUnit.Terabyte)); - unitConverter.SetConversionFunction(InformationUnit.Bit, InformationUnit.Teraoctet, quantity => quantity.ToUnit(InformationUnit.Teraoctet)); - } - /// /// Get unit abbreviation string. /// @@ -568,7 +550,7 @@ public static string GetAbbreviation(InformationUnit unit, IFormatProvider? prov /// /// Creates a from . /// - public static Information FromBits(double value) + public static Information FromBits(QuantityValue value) { return new Information(value, InformationUnit.Bit); } @@ -576,7 +558,7 @@ public static Information FromBits(double value) /// /// Creates a from . /// - public static Information FromBytes(double value) + public static Information FromBytes(QuantityValue value) { return new Information(value, InformationUnit.Byte); } @@ -584,7 +566,7 @@ public static Information FromBytes(double value) /// /// Creates a from . /// - public static Information FromExabits(double value) + public static Information FromExabits(QuantityValue value) { return new Information(value, InformationUnit.Exabit); } @@ -592,7 +574,7 @@ public static Information FromExabits(double value) /// /// Creates a from . /// - public static Information FromExabytes(double value) + public static Information FromExabytes(QuantityValue value) { return new Information(value, InformationUnit.Exabyte); } @@ -600,7 +582,7 @@ public static Information FromExabytes(double value) /// /// Creates a from . /// - public static Information FromExaoctets(double value) + public static Information FromExaoctets(QuantityValue value) { return new Information(value, InformationUnit.Exaoctet); } @@ -608,7 +590,7 @@ public static Information FromExaoctets(double value) /// /// Creates a from . /// - public static Information FromExbibits(double value) + public static Information FromExbibits(QuantityValue value) { return new Information(value, InformationUnit.Exbibit); } @@ -616,7 +598,7 @@ public static Information FromExbibits(double value) /// /// Creates a from . /// - public static Information FromExbibytes(double value) + public static Information FromExbibytes(QuantityValue value) { return new Information(value, InformationUnit.Exbibyte); } @@ -624,7 +606,7 @@ public static Information FromExbibytes(double value) /// /// Creates a from . /// - public static Information FromExbioctets(double value) + public static Information FromExbioctets(QuantityValue value) { return new Information(value, InformationUnit.Exbioctet); } @@ -632,7 +614,7 @@ public static Information FromExbioctets(double value) /// /// Creates a from . /// - public static Information FromGibibits(double value) + public static Information FromGibibits(QuantityValue value) { return new Information(value, InformationUnit.Gibibit); } @@ -640,7 +622,7 @@ public static Information FromGibibits(double value) /// /// Creates a from . /// - public static Information FromGibibytes(double value) + public static Information FromGibibytes(QuantityValue value) { return new Information(value, InformationUnit.Gibibyte); } @@ -648,7 +630,7 @@ public static Information FromGibibytes(double value) /// /// Creates a from . /// - public static Information FromGibioctets(double value) + public static Information FromGibioctets(QuantityValue value) { return new Information(value, InformationUnit.Gibioctet); } @@ -656,7 +638,7 @@ public static Information FromGibioctets(double value) /// /// Creates a from . /// - public static Information FromGigabits(double value) + public static Information FromGigabits(QuantityValue value) { return new Information(value, InformationUnit.Gigabit); } @@ -664,7 +646,7 @@ public static Information FromGigabits(double value) /// /// Creates a from . /// - public static Information FromGigabytes(double value) + public static Information FromGigabytes(QuantityValue value) { return new Information(value, InformationUnit.Gigabyte); } @@ -672,7 +654,7 @@ public static Information FromGigabytes(double value) /// /// Creates a from . /// - public static Information FromGigaoctets(double value) + public static Information FromGigaoctets(QuantityValue value) { return new Information(value, InformationUnit.Gigaoctet); } @@ -680,7 +662,7 @@ public static Information FromGigaoctets(double value) /// /// Creates a from . /// - public static Information FromKibibits(double value) + public static Information FromKibibits(QuantityValue value) { return new Information(value, InformationUnit.Kibibit); } @@ -688,7 +670,7 @@ public static Information FromKibibits(double value) /// /// Creates a from . /// - public static Information FromKibibytes(double value) + public static Information FromKibibytes(QuantityValue value) { return new Information(value, InformationUnit.Kibibyte); } @@ -696,7 +678,7 @@ public static Information FromKibibytes(double value) /// /// Creates a from . /// - public static Information FromKibioctets(double value) + public static Information FromKibioctets(QuantityValue value) { return new Information(value, InformationUnit.Kibioctet); } @@ -704,7 +686,7 @@ public static Information FromKibioctets(double value) /// /// Creates a from . /// - public static Information FromKilobits(double value) + public static Information FromKilobits(QuantityValue value) { return new Information(value, InformationUnit.Kilobit); } @@ -712,7 +694,7 @@ public static Information FromKilobits(double value) /// /// Creates a from . /// - public static Information FromKilobytes(double value) + public static Information FromKilobytes(QuantityValue value) { return new Information(value, InformationUnit.Kilobyte); } @@ -720,7 +702,7 @@ public static Information FromKilobytes(double value) /// /// Creates a from . /// - public static Information FromKilooctets(double value) + public static Information FromKilooctets(QuantityValue value) { return new Information(value, InformationUnit.Kilooctet); } @@ -728,7 +710,7 @@ public static Information FromKilooctets(double value) /// /// Creates a from . /// - public static Information FromMebibits(double value) + public static Information FromMebibits(QuantityValue value) { return new Information(value, InformationUnit.Mebibit); } @@ -736,7 +718,7 @@ public static Information FromMebibits(double value) /// /// Creates a from . /// - public static Information FromMebibytes(double value) + public static Information FromMebibytes(QuantityValue value) { return new Information(value, InformationUnit.Mebibyte); } @@ -744,7 +726,7 @@ public static Information FromMebibytes(double value) /// /// Creates a from . /// - public static Information FromMebioctets(double value) + public static Information FromMebioctets(QuantityValue value) { return new Information(value, InformationUnit.Mebioctet); } @@ -752,7 +734,7 @@ public static Information FromMebioctets(double value) /// /// Creates a from . /// - public static Information FromMegabits(double value) + public static Information FromMegabits(QuantityValue value) { return new Information(value, InformationUnit.Megabit); } @@ -760,7 +742,7 @@ public static Information FromMegabits(double value) /// /// Creates a from . /// - public static Information FromMegabytes(double value) + public static Information FromMegabytes(QuantityValue value) { return new Information(value, InformationUnit.Megabyte); } @@ -768,7 +750,7 @@ public static Information FromMegabytes(double value) /// /// Creates a from . /// - public static Information FromMegaoctets(double value) + public static Information FromMegaoctets(QuantityValue value) { return new Information(value, InformationUnit.Megaoctet); } @@ -776,7 +758,7 @@ public static Information FromMegaoctets(double value) /// /// Creates a from . /// - public static Information FromOctets(double value) + public static Information FromOctets(QuantityValue value) { return new Information(value, InformationUnit.Octet); } @@ -784,7 +766,7 @@ public static Information FromOctets(double value) /// /// Creates a from . /// - public static Information FromPebibits(double value) + public static Information FromPebibits(QuantityValue value) { return new Information(value, InformationUnit.Pebibit); } @@ -792,7 +774,7 @@ public static Information FromPebibits(double value) /// /// Creates a from . /// - public static Information FromPebibytes(double value) + public static Information FromPebibytes(QuantityValue value) { return new Information(value, InformationUnit.Pebibyte); } @@ -800,7 +782,7 @@ public static Information FromPebibytes(double value) /// /// Creates a from . /// - public static Information FromPebioctets(double value) + public static Information FromPebioctets(QuantityValue value) { return new Information(value, InformationUnit.Pebioctet); } @@ -808,7 +790,7 @@ public static Information FromPebioctets(double value) /// /// Creates a from . /// - public static Information FromPetabits(double value) + public static Information FromPetabits(QuantityValue value) { return new Information(value, InformationUnit.Petabit); } @@ -816,7 +798,7 @@ public static Information FromPetabits(double value) /// /// Creates a from . /// - public static Information FromPetabytes(double value) + public static Information FromPetabytes(QuantityValue value) { return new Information(value, InformationUnit.Petabyte); } @@ -824,7 +806,7 @@ public static Information FromPetabytes(double value) /// /// Creates a from . /// - public static Information FromPetaoctets(double value) + public static Information FromPetaoctets(QuantityValue value) { return new Information(value, InformationUnit.Petaoctet); } @@ -832,7 +814,7 @@ public static Information FromPetaoctets(double value) /// /// Creates a from . /// - public static Information FromTebibits(double value) + public static Information FromTebibits(QuantityValue value) { return new Information(value, InformationUnit.Tebibit); } @@ -840,7 +822,7 @@ public static Information FromTebibits(double value) /// /// Creates a from . /// - public static Information FromTebibytes(double value) + public static Information FromTebibytes(QuantityValue value) { return new Information(value, InformationUnit.Tebibyte); } @@ -848,7 +830,7 @@ public static Information FromTebibytes(double value) /// /// Creates a from . /// - public static Information FromTebioctets(double value) + public static Information FromTebioctets(QuantityValue value) { return new Information(value, InformationUnit.Tebioctet); } @@ -856,7 +838,7 @@ public static Information FromTebioctets(double value) /// /// Creates a from . /// - public static Information FromTerabits(double value) + public static Information FromTerabits(QuantityValue value) { return new Information(value, InformationUnit.Terabit); } @@ -864,7 +846,7 @@ public static Information FromTerabits(double value) /// /// Creates a from . /// - public static Information FromTerabytes(double value) + public static Information FromTerabytes(QuantityValue value) { return new Information(value, InformationUnit.Terabyte); } @@ -872,7 +854,7 @@ public static Information FromTerabytes(double value) /// /// Creates a from . /// - public static Information FromTeraoctets(double value) + public static Information FromTeraoctets(QuantityValue value) { return new Information(value, InformationUnit.Teraoctet); } @@ -883,7 +865,7 @@ public static Information FromTeraoctets(double value) /// Value to convert from. /// Unit to convert from. /// Information unit value. - public static Information From(double value, InformationUnit fromUnit) + public static Information From(QuantityValue value, InformationUnit fromUnit) { return new Information(value, fromUnit); } @@ -944,10 +926,7 @@ public static Information Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Information Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -975,11 +954,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Information resu /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Information result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -1000,7 +975,7 @@ public static InformationUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -1011,7 +986,7 @@ public static InformationUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out InformationUnit unit) { return TryParseUnit(str, null, out unit); @@ -1026,7 +1001,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out InformationU /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out InformationUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -1045,35 +1020,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Information operator +(Information left, Information right) { - return new Information(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Information(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Information operator -(Information left, Information right) { - return new Information(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Information(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static Information operator *(double 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, double 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, double 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; } @@ -1085,97 +1060,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Information left, Information right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Information left, Information right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Information left, Information right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Information left, Information right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Information other, Information tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Information left, Information right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Information other, Information tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Information left, Information right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Information other, Information tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Information otherQuantity)) + if (obj is not Information otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Information other, Information tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Information other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Information. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Information), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Information otherQuantity)) throw new ArgumentException("Expected type Information.", nameof(obj)); + if (obj is not Information otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1187,222 +1147,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Information other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(InformationUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Information to another Information with the unit representation . - /// - /// The unit to convert to. - /// A Information with the specified unit. - public Information ToUnit(InformationUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Information with the specified unit. - public Information ToUnit(InformationUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Information), Unit, typeof(Information), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Information)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(InformationUnit unit, [NotNullWhen(true)] out Information? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Information? convertedOrNull = (Unit, unit) switch - { - // InformationUnit -> BaseUnit - (InformationUnit.Byte, InformationUnit.Bit) => new Information(_value * 8, InformationUnit.Bit), - (InformationUnit.Exabit, InformationUnit.Bit) => new Information((_value) * 1e18d, InformationUnit.Bit), - (InformationUnit.Exabyte, InformationUnit.Bit) => new Information((_value * 8) * 1e18d, InformationUnit.Bit), - (InformationUnit.Exaoctet, InformationUnit.Bit) => new Information((_value * 8) * 1e18d, InformationUnit.Bit), - (InformationUnit.Exbibit, InformationUnit.Bit) => new Information((_value) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024), InformationUnit.Bit), - (InformationUnit.Exbibyte, InformationUnit.Bit) => new Information((_value * 8) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024), InformationUnit.Bit), - (InformationUnit.Exbioctet, InformationUnit.Bit) => new Information((_value * 8) * (1024d * 1024 * 1024 * 1024 * 1024 * 1024), InformationUnit.Bit), - (InformationUnit.Gibibit, InformationUnit.Bit) => new Information((_value) * (1024d * 1024 * 1024), InformationUnit.Bit), - (InformationUnit.Gibibyte, InformationUnit.Bit) => new Information((_value * 8) * (1024d * 1024 * 1024), InformationUnit.Bit), - (InformationUnit.Gibioctet, InformationUnit.Bit) => new Information((_value * 8) * (1024d * 1024 * 1024), InformationUnit.Bit), - (InformationUnit.Gigabit, InformationUnit.Bit) => new Information((_value) * 1e9d, InformationUnit.Bit), - (InformationUnit.Gigabyte, InformationUnit.Bit) => new Information((_value * 8) * 1e9d, InformationUnit.Bit), - (InformationUnit.Gigaoctet, InformationUnit.Bit) => new Information((_value * 8) * 1e9d, InformationUnit.Bit), - (InformationUnit.Kibibit, InformationUnit.Bit) => new Information((_value) * 1024d, InformationUnit.Bit), - (InformationUnit.Kibibyte, InformationUnit.Bit) => new Information((_value * 8) * 1024d, InformationUnit.Bit), - (InformationUnit.Kibioctet, InformationUnit.Bit) => new Information((_value * 8) * 1024d, InformationUnit.Bit), - (InformationUnit.Kilobit, InformationUnit.Bit) => new Information((_value) * 1e3d, InformationUnit.Bit), - (InformationUnit.Kilobyte, InformationUnit.Bit) => new Information((_value * 8) * 1e3d, InformationUnit.Bit), - (InformationUnit.Kilooctet, InformationUnit.Bit) => new Information((_value * 8) * 1e3d, InformationUnit.Bit), - (InformationUnit.Mebibit, InformationUnit.Bit) => new Information((_value) * (1024d * 1024), InformationUnit.Bit), - (InformationUnit.Mebibyte, InformationUnit.Bit) => new Information((_value * 8) * (1024d * 1024), InformationUnit.Bit), - (InformationUnit.Mebioctet, InformationUnit.Bit) => new Information((_value * 8) * (1024d * 1024), InformationUnit.Bit), - (InformationUnit.Megabit, InformationUnit.Bit) => new Information((_value) * 1e6d, InformationUnit.Bit), - (InformationUnit.Megabyte, InformationUnit.Bit) => new Information((_value * 8) * 1e6d, InformationUnit.Bit), - (InformationUnit.Megaoctet, InformationUnit.Bit) => new Information((_value * 8) * 1e6d, InformationUnit.Bit), - (InformationUnit.Octet, InformationUnit.Bit) => new Information(_value * 8, InformationUnit.Bit), - (InformationUnit.Pebibit, InformationUnit.Bit) => new Information((_value) * (1024d * 1024 * 1024 * 1024 * 1024), InformationUnit.Bit), - (InformationUnit.Pebibyte, InformationUnit.Bit) => new Information((_value * 8) * (1024d * 1024 * 1024 * 1024 * 1024), InformationUnit.Bit), - (InformationUnit.Pebioctet, InformationUnit.Bit) => new Information((_value * 8) * (1024d * 1024 * 1024 * 1024 * 1024), InformationUnit.Bit), - (InformationUnit.Petabit, InformationUnit.Bit) => new Information((_value) * 1e15d, InformationUnit.Bit), - (InformationUnit.Petabyte, InformationUnit.Bit) => new Information((_value * 8) * 1e15d, InformationUnit.Bit), - (InformationUnit.Petaoctet, InformationUnit.Bit) => new Information((_value * 8) * 1e15d, InformationUnit.Bit), - (InformationUnit.Tebibit, InformationUnit.Bit) => new Information((_value) * (1024d * 1024 * 1024 * 1024), InformationUnit.Bit), - (InformationUnit.Tebibyte, InformationUnit.Bit) => new Information((_value * 8) * (1024d * 1024 * 1024 * 1024), InformationUnit.Bit), - (InformationUnit.Tebioctet, InformationUnit.Bit) => new Information((_value * 8) * (1024d * 1024 * 1024 * 1024), InformationUnit.Bit), - (InformationUnit.Terabit, InformationUnit.Bit) => new Information((_value) * 1e12d, InformationUnit.Bit), - (InformationUnit.Terabyte, InformationUnit.Bit) => new Information((_value * 8) * 1e12d, InformationUnit.Bit), - (InformationUnit.Teraoctet, InformationUnit.Bit) => new Information((_value * 8) * 1e12d, InformationUnit.Bit), - - // BaseUnit -> InformationUnit - (InformationUnit.Bit, InformationUnit.Byte) => new Information(_value / 8, InformationUnit.Byte), - (InformationUnit.Bit, InformationUnit.Exabit) => new Information((_value) / 1e18d, InformationUnit.Exabit), - (InformationUnit.Bit, InformationUnit.Exabyte) => new Information((_value / 8) / 1e18d, InformationUnit.Exabyte), - (InformationUnit.Bit, InformationUnit.Exaoctet) => new Information((_value / 8) / 1e18d, InformationUnit.Exaoctet), - (InformationUnit.Bit, InformationUnit.Exbibit) => new Information((_value) / (1024d * 1024 * 1024 * 1024 * 1024 * 1024), InformationUnit.Exbibit), - (InformationUnit.Bit, InformationUnit.Exbibyte) => new Information((_value / 8) / (1024d * 1024 * 1024 * 1024 * 1024 * 1024), InformationUnit.Exbibyte), - (InformationUnit.Bit, InformationUnit.Exbioctet) => new Information((_value / 8) / (1024d * 1024 * 1024 * 1024 * 1024 * 1024), InformationUnit.Exbioctet), - (InformationUnit.Bit, InformationUnit.Gibibit) => new Information((_value) / (1024d * 1024 * 1024), InformationUnit.Gibibit), - (InformationUnit.Bit, InformationUnit.Gibibyte) => new Information((_value / 8) / (1024d * 1024 * 1024), InformationUnit.Gibibyte), - (InformationUnit.Bit, InformationUnit.Gibioctet) => new Information((_value / 8) / (1024d * 1024 * 1024), InformationUnit.Gibioctet), - (InformationUnit.Bit, InformationUnit.Gigabit) => new Information((_value) / 1e9d, InformationUnit.Gigabit), - (InformationUnit.Bit, InformationUnit.Gigabyte) => new Information((_value / 8) / 1e9d, InformationUnit.Gigabyte), - (InformationUnit.Bit, InformationUnit.Gigaoctet) => new Information((_value / 8) / 1e9d, InformationUnit.Gigaoctet), - (InformationUnit.Bit, InformationUnit.Kibibit) => new Information((_value) / 1024d, InformationUnit.Kibibit), - (InformationUnit.Bit, InformationUnit.Kibibyte) => new Information((_value / 8) / 1024d, InformationUnit.Kibibyte), - (InformationUnit.Bit, InformationUnit.Kibioctet) => new Information((_value / 8) / 1024d, InformationUnit.Kibioctet), - (InformationUnit.Bit, InformationUnit.Kilobit) => new Information((_value) / 1e3d, InformationUnit.Kilobit), - (InformationUnit.Bit, InformationUnit.Kilobyte) => new Information((_value / 8) / 1e3d, InformationUnit.Kilobyte), - (InformationUnit.Bit, InformationUnit.Kilooctet) => new Information((_value / 8) / 1e3d, InformationUnit.Kilooctet), - (InformationUnit.Bit, InformationUnit.Mebibit) => new Information((_value) / (1024d * 1024), InformationUnit.Mebibit), - (InformationUnit.Bit, InformationUnit.Mebibyte) => new Information((_value / 8) / (1024d * 1024), InformationUnit.Mebibyte), - (InformationUnit.Bit, InformationUnit.Mebioctet) => new Information((_value / 8) / (1024d * 1024), InformationUnit.Mebioctet), - (InformationUnit.Bit, InformationUnit.Megabit) => new Information((_value) / 1e6d, InformationUnit.Megabit), - (InformationUnit.Bit, InformationUnit.Megabyte) => new Information((_value / 8) / 1e6d, InformationUnit.Megabyte), - (InformationUnit.Bit, InformationUnit.Megaoctet) => new Information((_value / 8) / 1e6d, InformationUnit.Megaoctet), - (InformationUnit.Bit, InformationUnit.Octet) => new Information(_value / 8, InformationUnit.Octet), - (InformationUnit.Bit, InformationUnit.Pebibit) => new Information((_value) / (1024d * 1024 * 1024 * 1024 * 1024), InformationUnit.Pebibit), - (InformationUnit.Bit, InformationUnit.Pebibyte) => new Information((_value / 8) / (1024d * 1024 * 1024 * 1024 * 1024), InformationUnit.Pebibyte), - (InformationUnit.Bit, InformationUnit.Pebioctet) => new Information((_value / 8) / (1024d * 1024 * 1024 * 1024 * 1024), InformationUnit.Pebioctet), - (InformationUnit.Bit, InformationUnit.Petabit) => new Information((_value) / 1e15d, InformationUnit.Petabit), - (InformationUnit.Bit, InformationUnit.Petabyte) => new Information((_value / 8) / 1e15d, InformationUnit.Petabyte), - (InformationUnit.Bit, InformationUnit.Petaoctet) => new Information((_value / 8) / 1e15d, InformationUnit.Petaoctet), - (InformationUnit.Bit, InformationUnit.Tebibit) => new Information((_value) / (1024d * 1024 * 1024 * 1024), InformationUnit.Tebibit), - (InformationUnit.Bit, InformationUnit.Tebibyte) => new Information((_value / 8) / (1024d * 1024 * 1024 * 1024), InformationUnit.Tebibyte), - (InformationUnit.Bit, InformationUnit.Tebioctet) => new Information((_value / 8) / (1024d * 1024 * 1024 * 1024), InformationUnit.Tebioctet), - (InformationUnit.Bit, InformationUnit.Terabit) => new Information((_value) / 1e12d, InformationUnit.Terabit), - (InformationUnit.Bit, InformationUnit.Terabyte) => new Information((_value / 8) / 1e12d, InformationUnit.Terabyte), - (InformationUnit.Bit, InformationUnit.Teraoctet) => new Information((_value / 8) / 1e12d, InformationUnit.Teraoctet), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Information ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not InformationUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(InformationUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(InformationUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(InformationUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1417,7 +1179,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs index f34428a664..3003f909a0 100644 --- a/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Irradiance.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// Irradiance is the intensity of ultraviolet (UV) or visible light incident on a surface. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Irradiance : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly IrradianceUnit? _unit; /// @@ -101,7 +100,7 @@ public static IrradianceInfo CreateDefault(Func - /// The for is [T^-3][M]. + /// The for is T^-3M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, -3, 0, 0, 0, 0); @@ -116,28 +115,52 @@ public static IrradianceInfo CreateDefault(FuncAn of representing the default unit mappings for Irradiance. public static IEnumerable> GetDefaultMappings() { - yield return new (IrradianceUnit.KilowattPerSquareCentimeter, "KilowattPerSquareCentimeter", "KilowattsPerSquareCentimeter", BaseUnits.Undefined); - yield return new (IrradianceUnit.KilowattPerSquareMeter, "KilowattPerSquareMeter", "KilowattsPerSquareMeter", BaseUnits.Undefined); - yield return new (IrradianceUnit.MegawattPerSquareCentimeter, "MegawattPerSquareCentimeter", "MegawattsPerSquareCentimeter", BaseUnits.Undefined); - yield return new (IrradianceUnit.MegawattPerSquareMeter, "MegawattPerSquareMeter", "MegawattsPerSquareMeter", BaseUnits.Undefined); - yield return new (IrradianceUnit.MicrowattPerSquareCentimeter, "MicrowattPerSquareCentimeter", "MicrowattsPerSquareCentimeter", BaseUnits.Undefined); - yield return new (IrradianceUnit.MicrowattPerSquareMeter, "MicrowattPerSquareMeter", "MicrowattsPerSquareMeter", new BaseUnits(mass: MassUnit.Milligram, time: DurationUnit.Second)); - yield return new (IrradianceUnit.MilliwattPerSquareCentimeter, "MilliwattPerSquareCentimeter", "MilliwattsPerSquareCentimeter", BaseUnits.Undefined); - yield return new (IrradianceUnit.MilliwattPerSquareMeter, "MilliwattPerSquareMeter", "MilliwattsPerSquareMeter", new BaseUnits(mass: MassUnit.Gram, time: DurationUnit.Second)); - yield return new (IrradianceUnit.NanowattPerSquareCentimeter, "NanowattPerSquareCentimeter", "NanowattsPerSquareCentimeter", BaseUnits.Undefined); - yield return new (IrradianceUnit.NanowattPerSquareMeter, "NanowattPerSquareMeter", "NanowattsPerSquareMeter", new BaseUnits(mass: MassUnit.Microgram, time: DurationUnit.Second)); - yield return new (IrradianceUnit.PicowattPerSquareCentimeter, "PicowattPerSquareCentimeter", "PicowattsPerSquareCentimeter", BaseUnits.Undefined); - yield return new (IrradianceUnit.PicowattPerSquareMeter, "PicowattPerSquareMeter", "PicowattsPerSquareMeter", new BaseUnits(mass: MassUnit.Nanogram, time: DurationUnit.Second)); - yield return new (IrradianceUnit.WattPerSquareCentimeter, "WattPerSquareCentimeter", "WattsPerSquareCentimeter", BaseUnits.Undefined); + yield return new (IrradianceUnit.KilowattPerSquareCentimeter, "KilowattPerSquareCentimeter", "KilowattsPerSquareCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 10000000) + ); + yield return new (IrradianceUnit.KilowattPerSquareMeter, "KilowattPerSquareMeter", "KilowattsPerSquareMeter", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (IrradianceUnit.MegawattPerSquareCentimeter, "MegawattPerSquareCentimeter", "MegawattsPerSquareCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 10000000000) + ); + yield return new (IrradianceUnit.MegawattPerSquareMeter, "MegawattPerSquareMeter", "MegawattsPerSquareMeter", BaseUnits.Undefined, + new QuantityValue(1, 1000000) + ); + yield return new (IrradianceUnit.MicrowattPerSquareCentimeter, "MicrowattPerSquareCentimeter", "MicrowattsPerSquareCentimeter", BaseUnits.Undefined, + 100 + ); + yield return new (IrradianceUnit.MicrowattPerSquareMeter, "MicrowattPerSquareMeter", "MicrowattsPerSquareMeter", new BaseUnits(mass: MassUnit.Milligram, time: DurationUnit.Second), + 1000000 + ); + yield return new (IrradianceUnit.MilliwattPerSquareCentimeter, "MilliwattPerSquareCentimeter", "MilliwattsPerSquareCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 10) + ); + yield return new (IrradianceUnit.MilliwattPerSquareMeter, "MilliwattPerSquareMeter", "MilliwattsPerSquareMeter", new BaseUnits(mass: MassUnit.Gram, time: DurationUnit.Second), + 1000 + ); + yield return new (IrradianceUnit.NanowattPerSquareCentimeter, "NanowattPerSquareCentimeter", "NanowattsPerSquareCentimeter", BaseUnits.Undefined, + 100000 + ); + yield return new (IrradianceUnit.NanowattPerSquareMeter, "NanowattPerSquareMeter", "NanowattsPerSquareMeter", new BaseUnits(mass: MassUnit.Microgram, time: DurationUnit.Second), + 1000000000 + ); + yield return new (IrradianceUnit.PicowattPerSquareCentimeter, "PicowattPerSquareCentimeter", "PicowattsPerSquareCentimeter", BaseUnits.Undefined, + 100000000 + ); + yield return new (IrradianceUnit.PicowattPerSquareMeter, "PicowattPerSquareMeter", "PicowattsPerSquareMeter", new BaseUnits(mass: MassUnit.Nanogram, time: DurationUnit.Second), + 1000000000000 + ); + yield return new (IrradianceUnit.WattPerSquareCentimeter, "WattPerSquareCentimeter", "WattsPerSquareCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 10000) + ); yield return new (IrradianceUnit.WattPerSquareMeter, "WattPerSquareMeter", "WattsPerSquareMeter", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second)); } } static Irradiance() { - Info = IrradianceInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(IrradianceInfo.CreateDefault); } /// @@ -145,7 +168,7 @@ static Irradiance() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Irradiance(double value, IrradianceUnit unit) + public Irradiance(QuantityValue value, IrradianceUnit unit) { _value = value; _unit = unit; @@ -159,7 +182,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -170,7 +193,8 @@ public Irradiance(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -199,10 +223,8 @@ public Irradiance(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public IrradianceUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -241,119 +263,79 @@ public Irradiance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattsPerSquareCentimeter => As(IrradianceUnit.KilowattPerSquareCentimeter); + public QuantityValue KilowattsPerSquareCentimeter => this.As(IrradianceUnit.KilowattPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattsPerSquareMeter => As(IrradianceUnit.KilowattPerSquareMeter); + public QuantityValue KilowattsPerSquareMeter => this.As(IrradianceUnit.KilowattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattsPerSquareCentimeter => As(IrradianceUnit.MegawattPerSquareCentimeter); + public QuantityValue MegawattsPerSquareCentimeter => this.As(IrradianceUnit.MegawattPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattsPerSquareMeter => As(IrradianceUnit.MegawattPerSquareMeter); + public QuantityValue MegawattsPerSquareMeter => this.As(IrradianceUnit.MegawattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrowattsPerSquareCentimeter => As(IrradianceUnit.MicrowattPerSquareCentimeter); + public QuantityValue MicrowattsPerSquareCentimeter => this.As(IrradianceUnit.MicrowattPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrowattsPerSquareMeter => As(IrradianceUnit.MicrowattPerSquareMeter); + public QuantityValue MicrowattsPerSquareMeter => this.As(IrradianceUnit.MicrowattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliwattsPerSquareCentimeter => As(IrradianceUnit.MilliwattPerSquareCentimeter); + public QuantityValue MilliwattsPerSquareCentimeter => this.As(IrradianceUnit.MilliwattPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliwattsPerSquareMeter => As(IrradianceUnit.MilliwattPerSquareMeter); + public QuantityValue MilliwattsPerSquareMeter => this.As(IrradianceUnit.MilliwattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanowattsPerSquareCentimeter => As(IrradianceUnit.NanowattPerSquareCentimeter); + public QuantityValue NanowattsPerSquareCentimeter => this.As(IrradianceUnit.NanowattPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanowattsPerSquareMeter => As(IrradianceUnit.NanowattPerSquareMeter); + public QuantityValue NanowattsPerSquareMeter => this.As(IrradianceUnit.NanowattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicowattsPerSquareCentimeter => As(IrradianceUnit.PicowattPerSquareCentimeter); + public QuantityValue PicowattsPerSquareCentimeter => this.As(IrradianceUnit.PicowattPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicowattsPerSquareMeter => As(IrradianceUnit.PicowattPerSquareMeter); + public QuantityValue PicowattsPerSquareMeter => this.As(IrradianceUnit.PicowattPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattsPerSquareCentimeter => As(IrradianceUnit.WattPerSquareCentimeter); + public QuantityValue WattsPerSquareCentimeter => this.As(IrradianceUnit.WattPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattsPerSquareMeter => As(IrradianceUnit.WattPerSquareMeter); + public QuantityValue WattsPerSquareMeter => this.As(IrradianceUnit.WattPerSquareMeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: IrradianceUnit -> BaseUnit - unitConverter.SetConversionFunction(IrradianceUnit.KilowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.KilowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.MegawattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.MegawattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.MicrowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.MicrowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.MilliwattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.MilliwattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.NanowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.NanowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.PicowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.PicowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.WattPerSquareMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> IrradianceUnit - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.KilowattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.KilowattPerSquareCentimeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.KilowattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.KilowattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MegawattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.MegawattPerSquareCentimeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MegawattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.MegawattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MicrowattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.MicrowattPerSquareCentimeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MicrowattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.MicrowattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MilliwattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.MilliwattPerSquareCentimeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MilliwattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.MilliwattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.NanowattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.NanowattPerSquareCentimeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.NanowattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.NanowattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.PicowattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.PicowattPerSquareCentimeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.PicowattPerSquareMeter, quantity => quantity.ToUnit(IrradianceUnit.PicowattPerSquareMeter)); - unitConverter.SetConversionFunction(IrradianceUnit.WattPerSquareMeter, IrradianceUnit.WattPerSquareCentimeter, quantity => quantity.ToUnit(IrradianceUnit.WattPerSquareCentimeter)); - } - /// /// Get unit abbreviation string. /// @@ -382,7 +364,7 @@ public static string GetAbbreviation(IrradianceUnit unit, IFormatProvider? provi /// /// Creates a from . /// - public static Irradiance FromKilowattsPerSquareCentimeter(double value) + public static Irradiance FromKilowattsPerSquareCentimeter(QuantityValue value) { return new Irradiance(value, IrradianceUnit.KilowattPerSquareCentimeter); } @@ -390,7 +372,7 @@ public static Irradiance FromKilowattsPerSquareCentimeter(double value) /// /// Creates a from . /// - public static Irradiance FromKilowattsPerSquareMeter(double value) + public static Irradiance FromKilowattsPerSquareMeter(QuantityValue value) { return new Irradiance(value, IrradianceUnit.KilowattPerSquareMeter); } @@ -398,7 +380,7 @@ public static Irradiance FromKilowattsPerSquareMeter(double value) /// /// Creates a from . /// - public static Irradiance FromMegawattsPerSquareCentimeter(double value) + public static Irradiance FromMegawattsPerSquareCentimeter(QuantityValue value) { return new Irradiance(value, IrradianceUnit.MegawattPerSquareCentimeter); } @@ -406,7 +388,7 @@ public static Irradiance FromMegawattsPerSquareCentimeter(double value) /// /// Creates a from . /// - public static Irradiance FromMegawattsPerSquareMeter(double value) + public static Irradiance FromMegawattsPerSquareMeter(QuantityValue value) { return new Irradiance(value, IrradianceUnit.MegawattPerSquareMeter); } @@ -414,7 +396,7 @@ public static Irradiance FromMegawattsPerSquareMeter(double value) /// /// Creates a from . /// - public static Irradiance FromMicrowattsPerSquareCentimeter(double value) + public static Irradiance FromMicrowattsPerSquareCentimeter(QuantityValue value) { return new Irradiance(value, IrradianceUnit.MicrowattPerSquareCentimeter); } @@ -422,7 +404,7 @@ public static Irradiance FromMicrowattsPerSquareCentimeter(double value) /// /// Creates a from . /// - public static Irradiance FromMicrowattsPerSquareMeter(double value) + public static Irradiance FromMicrowattsPerSquareMeter(QuantityValue value) { return new Irradiance(value, IrradianceUnit.MicrowattPerSquareMeter); } @@ -430,7 +412,7 @@ public static Irradiance FromMicrowattsPerSquareMeter(double value) /// /// Creates a from . /// - public static Irradiance FromMilliwattsPerSquareCentimeter(double value) + public static Irradiance FromMilliwattsPerSquareCentimeter(QuantityValue value) { return new Irradiance(value, IrradianceUnit.MilliwattPerSquareCentimeter); } @@ -438,7 +420,7 @@ public static Irradiance FromMilliwattsPerSquareCentimeter(double value) /// /// Creates a from . /// - public static Irradiance FromMilliwattsPerSquareMeter(double value) + public static Irradiance FromMilliwattsPerSquareMeter(QuantityValue value) { return new Irradiance(value, IrradianceUnit.MilliwattPerSquareMeter); } @@ -446,7 +428,7 @@ public static Irradiance FromMilliwattsPerSquareMeter(double value) /// /// Creates a from . /// - public static Irradiance FromNanowattsPerSquareCentimeter(double value) + public static Irradiance FromNanowattsPerSquareCentimeter(QuantityValue value) { return new Irradiance(value, IrradianceUnit.NanowattPerSquareCentimeter); } @@ -454,7 +436,7 @@ public static Irradiance FromNanowattsPerSquareCentimeter(double value) /// /// Creates a from . /// - public static Irradiance FromNanowattsPerSquareMeter(double value) + public static Irradiance FromNanowattsPerSquareMeter(QuantityValue value) { return new Irradiance(value, IrradianceUnit.NanowattPerSquareMeter); } @@ -462,7 +444,7 @@ public static Irradiance FromNanowattsPerSquareMeter(double value) /// /// Creates a from . /// - public static Irradiance FromPicowattsPerSquareCentimeter(double value) + public static Irradiance FromPicowattsPerSquareCentimeter(QuantityValue value) { return new Irradiance(value, IrradianceUnit.PicowattPerSquareCentimeter); } @@ -470,7 +452,7 @@ public static Irradiance FromPicowattsPerSquareCentimeter(double value) /// /// Creates a from . /// - public static Irradiance FromPicowattsPerSquareMeter(double value) + public static Irradiance FromPicowattsPerSquareMeter(QuantityValue value) { return new Irradiance(value, IrradianceUnit.PicowattPerSquareMeter); } @@ -478,7 +460,7 @@ public static Irradiance FromPicowattsPerSquareMeter(double value) /// /// Creates a from . /// - public static Irradiance FromWattsPerSquareCentimeter(double value) + public static Irradiance FromWattsPerSquareCentimeter(QuantityValue value) { return new Irradiance(value, IrradianceUnit.WattPerSquareCentimeter); } @@ -486,7 +468,7 @@ public static Irradiance FromWattsPerSquareCentimeter(double value) /// /// Creates a from . /// - public static Irradiance FromWattsPerSquareMeter(double value) + public static Irradiance FromWattsPerSquareMeter(QuantityValue value) { return new Irradiance(value, IrradianceUnit.WattPerSquareMeter); } @@ -497,7 +479,7 @@ public static Irradiance FromWattsPerSquareMeter(double value) /// Value to convert from. /// Unit to convert from. /// Irradiance unit value. - public static Irradiance From(double value, IrradianceUnit fromUnit) + public static Irradiance From(QuantityValue value, IrradianceUnit fromUnit) { return new Irradiance(value, fromUnit); } @@ -558,10 +540,7 @@ public static Irradiance Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Irradiance Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -589,11 +568,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Irradiance resul /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Irradiance result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -614,7 +589,7 @@ public static IrradianceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -625,7 +600,7 @@ public static IrradianceUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out IrradianceUnit unit) { return TryParseUnit(str, null, out unit); @@ -640,7 +615,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out IrradianceUn /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out IrradianceUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -659,35 +634,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Irradiance operator +(Irradiance left, Irradiance right) { - return new Irradiance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Irradiance(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Irradiance operator -(Irradiance left, Irradiance right) { - return new Irradiance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Irradiance(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -699,97 +674,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Irradiance left, Irradiance right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Irradiance left, Irradiance right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Irradiance left, Irradiance right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Irradiance left, Irradiance right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Irradiance other, Irradiance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Irradiance left, Irradiance right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Irradiance other, Irradiance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Irradiance left, Irradiance right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Irradiance other, Irradiance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Irradiance otherQuantity)) + if (obj is not Irradiance otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Irradiance other, Irradiance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Irradiance other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Irradiance. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Irradiance), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Irradiance otherQuantity)) throw new ArgumentException("Expected type Irradiance.", nameof(obj)); + if (obj is not Irradiance otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -801,172 +761,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Irradiance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(IrradianceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Irradiance to another Irradiance with the unit representation . - /// - /// The unit to convert to. - /// A Irradiance with the specified unit. - public Irradiance ToUnit(IrradianceUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Irradiance with the specified unit. - public Irradiance ToUnit(IrradianceUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Irradiance), Unit, typeof(Irradiance), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Irradiance)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(IrradianceUnit unit, [NotNullWhen(true)] out Irradiance? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Irradiance? convertedOrNull = (Unit, unit) switch - { - // IrradianceUnit -> BaseUnit - (IrradianceUnit.KilowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value * 10000) * 1e3d, IrradianceUnit.WattPerSquareMeter), - (IrradianceUnit.KilowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value) * 1e3d, IrradianceUnit.WattPerSquareMeter), - (IrradianceUnit.MegawattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value * 10000) * 1e6d, IrradianceUnit.WattPerSquareMeter), - (IrradianceUnit.MegawattPerSquareMeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value) * 1e6d, IrradianceUnit.WattPerSquareMeter), - (IrradianceUnit.MicrowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value * 10000) * 1e-6d, IrradianceUnit.WattPerSquareMeter), - (IrradianceUnit.MicrowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value) * 1e-6d, IrradianceUnit.WattPerSquareMeter), - (IrradianceUnit.MilliwattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value * 10000) * 1e-3d, IrradianceUnit.WattPerSquareMeter), - (IrradianceUnit.MilliwattPerSquareMeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value) * 1e-3d, IrradianceUnit.WattPerSquareMeter), - (IrradianceUnit.NanowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value * 10000) * 1e-9d, IrradianceUnit.WattPerSquareMeter), - (IrradianceUnit.NanowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value) * 1e-9d, IrradianceUnit.WattPerSquareMeter), - (IrradianceUnit.PicowattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value * 10000) * 1e-12d, IrradianceUnit.WattPerSquareMeter), - (IrradianceUnit.PicowattPerSquareMeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance((_value) * 1e-12d, IrradianceUnit.WattPerSquareMeter), - (IrradianceUnit.WattPerSquareCentimeter, IrradianceUnit.WattPerSquareMeter) => new Irradiance(_value * 10000, IrradianceUnit.WattPerSquareMeter), - - // BaseUnit -> IrradianceUnit - (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.KilowattPerSquareCentimeter) => new Irradiance((_value * 0.0001) / 1e3d, IrradianceUnit.KilowattPerSquareCentimeter), - (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.KilowattPerSquareMeter) => new Irradiance((_value) / 1e3d, IrradianceUnit.KilowattPerSquareMeter), - (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MegawattPerSquareCentimeter) => new Irradiance((_value * 0.0001) / 1e6d, IrradianceUnit.MegawattPerSquareCentimeter), - (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MegawattPerSquareMeter) => new Irradiance((_value) / 1e6d, IrradianceUnit.MegawattPerSquareMeter), - (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MicrowattPerSquareCentimeter) => new Irradiance((_value * 0.0001) / 1e-6d, IrradianceUnit.MicrowattPerSquareCentimeter), - (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MicrowattPerSquareMeter) => new Irradiance((_value) / 1e-6d, IrradianceUnit.MicrowattPerSquareMeter), - (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MilliwattPerSquareCentimeter) => new Irradiance((_value * 0.0001) / 1e-3d, IrradianceUnit.MilliwattPerSquareCentimeter), - (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.MilliwattPerSquareMeter) => new Irradiance((_value) / 1e-3d, IrradianceUnit.MilliwattPerSquareMeter), - (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.NanowattPerSquareCentimeter) => new Irradiance((_value * 0.0001) / 1e-9d, IrradianceUnit.NanowattPerSquareCentimeter), - (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.NanowattPerSquareMeter) => new Irradiance((_value) / 1e-9d, IrradianceUnit.NanowattPerSquareMeter), - (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.PicowattPerSquareCentimeter) => new Irradiance((_value * 0.0001) / 1e-12d, IrradianceUnit.PicowattPerSquareCentimeter), - (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.PicowattPerSquareMeter) => new Irradiance((_value) / 1e-12d, IrradianceUnit.PicowattPerSquareMeter), - (IrradianceUnit.WattPerSquareMeter, IrradianceUnit.WattPerSquareCentimeter) => new Irradiance(_value * 0.0001, IrradianceUnit.WattPerSquareCentimeter), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Irradiance ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not IrradianceUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IrradianceUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(IrradianceUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(IrradianceUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -981,7 +793,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs b/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs index c541e7e6f2..c3963750c6 100644 --- a/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Irradiation.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Irradiation /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Irradiation : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly IrradiationUnit? _unit; /// @@ -104,7 +103,7 @@ public static IrradiationInfo CreateDefault(Func - /// The for is [T^-2][M]. + /// The for is T^-2M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, -2, 0, 0, 0, 0); @@ -119,23 +118,37 @@ public static IrradiationInfo CreateDefault(FuncAn of representing the default unit mappings for Irradiation. public static IEnumerable> GetDefaultMappings() { - yield return new (IrradiationUnit.BtuPerSquareFoot, "BtuPerSquareFoot", "BtusPerSquareFoot", BaseUnits.Undefined); - yield return new (IrradiationUnit.JoulePerSquareCentimeter, "JoulePerSquareCentimeter", "JoulesPerSquareCentimeter", BaseUnits.Undefined); + yield return new (IrradiationUnit.BtuPerSquareFoot, "BtuPerSquareFoot", "BtusPerSquareFoot", BaseUnits.Undefined, + new QuantityValue(4645152, 52752792631) + ); + yield return new (IrradiationUnit.JoulePerSquareCentimeter, "JoulePerSquareCentimeter", "JoulesPerSquareCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 10000) + ); yield return new (IrradiationUnit.JoulePerSquareMeter, "JoulePerSquareMeter", "JoulesPerSquareMeter", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (IrradiationUnit.JoulePerSquareMillimeter, "JoulePerSquareMillimeter", "JoulesPerSquareMillimeter", BaseUnits.Undefined); - yield return new (IrradiationUnit.KilobtuPerSquareFoot, "KilobtuPerSquareFoot", "KilobtusPerSquareFoot", BaseUnits.Undefined); - yield return new (IrradiationUnit.KilojoulePerSquareMeter, "KilojoulePerSquareMeter", "KilojoulesPerSquareMeter", BaseUnits.Undefined); - yield return new (IrradiationUnit.KilowattHourPerSquareMeter, "KilowattHourPerSquareMeter", "KilowattHoursPerSquareMeter", BaseUnits.Undefined); - yield return new (IrradiationUnit.MillijoulePerSquareCentimeter, "MillijoulePerSquareCentimeter", "MillijoulesPerSquareCentimeter", BaseUnits.Undefined); - yield return new (IrradiationUnit.WattHourPerSquareMeter, "WattHourPerSquareMeter", "WattHoursPerSquareMeter", BaseUnits.Undefined); + yield return new (IrradiationUnit.JoulePerSquareMillimeter, "JoulePerSquareMillimeter", "JoulesPerSquareMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 1000000) + ); + yield return new (IrradiationUnit.KilobtuPerSquareFoot, "KilobtuPerSquareFoot", "KilobtusPerSquareFoot", BaseUnits.Undefined, + new QuantityValue(580644, 6594099078875) + ); + yield return new (IrradiationUnit.KilojoulePerSquareMeter, "KilojoulePerSquareMeter", "KilojoulesPerSquareMeter", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (IrradiationUnit.KilowattHourPerSquareMeter, "KilowattHourPerSquareMeter", "KilowattHoursPerSquareMeter", BaseUnits.Undefined, + new QuantityValue(1, 3600000) + ); + yield return new (IrradiationUnit.MillijoulePerSquareCentimeter, "MillijoulePerSquareCentimeter", "MillijoulesPerSquareCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 10) + ); + yield return new (IrradiationUnit.WattHourPerSquareMeter, "WattHourPerSquareMeter", "WattHoursPerSquareMeter", BaseUnits.Undefined, + new QuantityValue(1, 3600) + ); } } static Irradiation() { - Info = IrradiationInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(IrradiationInfo.CreateDefault); } /// @@ -143,7 +156,7 @@ static Irradiation() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Irradiation(double value, IrradiationUnit unit) + public Irradiation(QuantityValue value, IrradiationUnit unit) { _value = value; _unit = unit; @@ -157,7 +170,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -168,7 +181,8 @@ public Irradiation(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -197,10 +211,8 @@ public Irradiation(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public IrradiationUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -239,84 +251,54 @@ public Irradiation(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BtusPerSquareFoot => As(IrradiationUnit.BtuPerSquareFoot); + public QuantityValue BtusPerSquareFoot => this.As(IrradiationUnit.BtuPerSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double JoulesPerSquareCentimeter => As(IrradiationUnit.JoulePerSquareCentimeter); + public QuantityValue JoulesPerSquareCentimeter => this.As(IrradiationUnit.JoulePerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double JoulesPerSquareMeter => As(IrradiationUnit.JoulePerSquareMeter); + public QuantityValue JoulesPerSquareMeter => this.As(IrradiationUnit.JoulePerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double JoulesPerSquareMillimeter => As(IrradiationUnit.JoulePerSquareMillimeter); + public QuantityValue JoulesPerSquareMillimeter => this.As(IrradiationUnit.JoulePerSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilobtusPerSquareFoot => As(IrradiationUnit.KilobtuPerSquareFoot); + public QuantityValue KilobtusPerSquareFoot => this.As(IrradiationUnit.KilobtuPerSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilojoulesPerSquareMeter => As(IrradiationUnit.KilojoulePerSquareMeter); + public QuantityValue KilojoulesPerSquareMeter => this.As(IrradiationUnit.KilojoulePerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattHoursPerSquareMeter => As(IrradiationUnit.KilowattHourPerSquareMeter); + public QuantityValue KilowattHoursPerSquareMeter => this.As(IrradiationUnit.KilowattHourPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillijoulesPerSquareCentimeter => As(IrradiationUnit.MillijoulePerSquareCentimeter); + public QuantityValue MillijoulesPerSquareCentimeter => this.As(IrradiationUnit.MillijoulePerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattHoursPerSquareMeter => As(IrradiationUnit.WattHourPerSquareMeter); + public QuantityValue WattHoursPerSquareMeter => this.As(IrradiationUnit.WattHourPerSquareMeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: IrradiationUnit -> BaseUnit - unitConverter.SetConversionFunction(IrradiationUnit.BtuPerSquareFoot, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareMeter)); - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareCentimeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareMeter)); - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMillimeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareMeter)); - unitConverter.SetConversionFunction(IrradiationUnit.KilobtuPerSquareFoot, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareMeter)); - unitConverter.SetConversionFunction(IrradiationUnit.KilojoulePerSquareMeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareMeter)); - unitConverter.SetConversionFunction(IrradiationUnit.KilowattHourPerSquareMeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareMeter)); - unitConverter.SetConversionFunction(IrradiationUnit.MillijoulePerSquareCentimeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareMeter)); - unitConverter.SetConversionFunction(IrradiationUnit.WattHourPerSquareMeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.JoulePerSquareMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> IrradiationUnit - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.BtuPerSquareFoot, quantity => quantity.ToUnit(IrradiationUnit.BtuPerSquareFoot)); - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.JoulePerSquareCentimeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareCentimeter)); - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.JoulePerSquareMillimeter, quantity => quantity.ToUnit(IrradiationUnit.JoulePerSquareMillimeter)); - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.KilobtuPerSquareFoot, quantity => quantity.ToUnit(IrradiationUnit.KilobtuPerSquareFoot)); - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.KilojoulePerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.KilojoulePerSquareMeter)); - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.KilowattHourPerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.KilowattHourPerSquareMeter)); - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.MillijoulePerSquareCentimeter, quantity => quantity.ToUnit(IrradiationUnit.MillijoulePerSquareCentimeter)); - unitConverter.SetConversionFunction(IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.WattHourPerSquareMeter, quantity => quantity.ToUnit(IrradiationUnit.WattHourPerSquareMeter)); - } - /// /// Get unit abbreviation string. /// @@ -345,7 +327,7 @@ public static string GetAbbreviation(IrradiationUnit unit, IFormatProvider? prov /// /// Creates a from . /// - public static Irradiation FromBtusPerSquareFoot(double value) + public static Irradiation FromBtusPerSquareFoot(QuantityValue value) { return new Irradiation(value, IrradiationUnit.BtuPerSquareFoot); } @@ -353,7 +335,7 @@ public static Irradiation FromBtusPerSquareFoot(double value) /// /// Creates a from . /// - public static Irradiation FromJoulesPerSquareCentimeter(double value) + public static Irradiation FromJoulesPerSquareCentimeter(QuantityValue value) { return new Irradiation(value, IrradiationUnit.JoulePerSquareCentimeter); } @@ -361,7 +343,7 @@ public static Irradiation FromJoulesPerSquareCentimeter(double value) /// /// Creates a from . /// - public static Irradiation FromJoulesPerSquareMeter(double value) + public static Irradiation FromJoulesPerSquareMeter(QuantityValue value) { return new Irradiation(value, IrradiationUnit.JoulePerSquareMeter); } @@ -369,7 +351,7 @@ public static Irradiation FromJoulesPerSquareMeter(double value) /// /// Creates a from . /// - public static Irradiation FromJoulesPerSquareMillimeter(double value) + public static Irradiation FromJoulesPerSquareMillimeter(QuantityValue value) { return new Irradiation(value, IrradiationUnit.JoulePerSquareMillimeter); } @@ -377,7 +359,7 @@ public static Irradiation FromJoulesPerSquareMillimeter(double value) /// /// Creates a from . /// - public static Irradiation FromKilobtusPerSquareFoot(double value) + public static Irradiation FromKilobtusPerSquareFoot(QuantityValue value) { return new Irradiation(value, IrradiationUnit.KilobtuPerSquareFoot); } @@ -385,7 +367,7 @@ public static Irradiation FromKilobtusPerSquareFoot(double value) /// /// Creates a from . /// - public static Irradiation FromKilojoulesPerSquareMeter(double value) + public static Irradiation FromKilojoulesPerSquareMeter(QuantityValue value) { return new Irradiation(value, IrradiationUnit.KilojoulePerSquareMeter); } @@ -393,7 +375,7 @@ public static Irradiation FromKilojoulesPerSquareMeter(double value) /// /// Creates a from . /// - public static Irradiation FromKilowattHoursPerSquareMeter(double value) + public static Irradiation FromKilowattHoursPerSquareMeter(QuantityValue value) { return new Irradiation(value, IrradiationUnit.KilowattHourPerSquareMeter); } @@ -401,7 +383,7 @@ public static Irradiation FromKilowattHoursPerSquareMeter(double value) /// /// Creates a from . /// - public static Irradiation FromMillijoulesPerSquareCentimeter(double value) + public static Irradiation FromMillijoulesPerSquareCentimeter(QuantityValue value) { return new Irradiation(value, IrradiationUnit.MillijoulePerSquareCentimeter); } @@ -409,7 +391,7 @@ public static Irradiation FromMillijoulesPerSquareCentimeter(double value) /// /// Creates a from . /// - public static Irradiation FromWattHoursPerSquareMeter(double value) + public static Irradiation FromWattHoursPerSquareMeter(QuantityValue value) { return new Irradiation(value, IrradiationUnit.WattHourPerSquareMeter); } @@ -420,7 +402,7 @@ public static Irradiation FromWattHoursPerSquareMeter(double value) /// Value to convert from. /// Unit to convert from. /// Irradiation unit value. - public static Irradiation From(double value, IrradiationUnit fromUnit) + public static Irradiation From(QuantityValue value, IrradiationUnit fromUnit) { return new Irradiation(value, fromUnit); } @@ -481,10 +463,7 @@ public static Irradiation Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Irradiation Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -512,11 +491,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Irradiation resu /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Irradiation result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -537,7 +512,7 @@ public static IrradiationUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -548,7 +523,7 @@ public static IrradiationUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out IrradiationUnit unit) { return TryParseUnit(str, null, out unit); @@ -563,7 +538,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out IrradiationU /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out IrradiationUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -582,35 +557,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Irradiation operator +(Irradiation left, Irradiation right) { - return new Irradiation(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Irradiation(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Irradiation operator -(Irradiation left, Irradiation right) { - return new Irradiation(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Irradiation(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -622,97 +597,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Irradiation left, Irradiation right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Irradiation left, Irradiation right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Irradiation left, Irradiation right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Irradiation left, Irradiation right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Irradiation other, Irradiation tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Irradiation left, Irradiation right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Irradiation other, Irradiation tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Irradiation left, Irradiation right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Irradiation other, Irradiation tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Irradiation otherQuantity)) + if (obj is not Irradiation otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Irradiation other, Irradiation tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Irradiation other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Irradiation. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Irradiation), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Irradiation otherQuantity)) throw new ArgumentException("Expected type Irradiation.", nameof(obj)); + if (obj is not Irradiation otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -724,162 +684,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Irradiation other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(IrradiationUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Irradiation to another Irradiation with the unit representation . - /// - /// The unit to convert to. - /// A Irradiation with the specified unit. - public Irradiation ToUnit(IrradiationUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Irradiation with the specified unit. - public Irradiation ToUnit(IrradiationUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Irradiation), Unit, typeof(Irradiation), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Irradiation)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(IrradiationUnit unit, [NotNullWhen(true)] out Irradiation? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Irradiation? convertedOrNull = (Unit, unit) switch - { - // IrradiationUnit -> BaseUnit - (IrradiationUnit.BtuPerSquareFoot, IrradiationUnit.JoulePerSquareMeter) => new Irradiation(_value * 1055.05585262 / 9.290304e-2, IrradiationUnit.JoulePerSquareMeter), - (IrradiationUnit.JoulePerSquareCentimeter, IrradiationUnit.JoulePerSquareMeter) => new Irradiation(_value * 1e4, IrradiationUnit.JoulePerSquareMeter), - (IrradiationUnit.JoulePerSquareMillimeter, IrradiationUnit.JoulePerSquareMeter) => new Irradiation(_value * 1e6, IrradiationUnit.JoulePerSquareMeter), - (IrradiationUnit.KilobtuPerSquareFoot, IrradiationUnit.JoulePerSquareMeter) => new Irradiation((_value * 1055.05585262 / 9.290304e-2) * 1e3d, IrradiationUnit.JoulePerSquareMeter), - (IrradiationUnit.KilojoulePerSquareMeter, IrradiationUnit.JoulePerSquareMeter) => new Irradiation((_value) * 1e3d, IrradiationUnit.JoulePerSquareMeter), - (IrradiationUnit.KilowattHourPerSquareMeter, IrradiationUnit.JoulePerSquareMeter) => new Irradiation((_value * 3600d) * 1e3d, IrradiationUnit.JoulePerSquareMeter), - (IrradiationUnit.MillijoulePerSquareCentimeter, IrradiationUnit.JoulePerSquareMeter) => new Irradiation((_value * 1e4) * 1e-3d, IrradiationUnit.JoulePerSquareMeter), - (IrradiationUnit.WattHourPerSquareMeter, IrradiationUnit.JoulePerSquareMeter) => new Irradiation(_value * 3600d, IrradiationUnit.JoulePerSquareMeter), - - // BaseUnit -> IrradiationUnit - (IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.BtuPerSquareFoot) => new Irradiation(_value * 9.290304e-2 / 1055.05585262, IrradiationUnit.BtuPerSquareFoot), - (IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.JoulePerSquareCentimeter) => new Irradiation(_value / 1e4, IrradiationUnit.JoulePerSquareCentimeter), - (IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.JoulePerSquareMillimeter) => new Irradiation(_value / 1e6, IrradiationUnit.JoulePerSquareMillimeter), - (IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.KilobtuPerSquareFoot) => new Irradiation((_value * 9.290304e-2 / 1055.05585262) / 1e3d, IrradiationUnit.KilobtuPerSquareFoot), - (IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.KilojoulePerSquareMeter) => new Irradiation((_value) / 1e3d, IrradiationUnit.KilojoulePerSquareMeter), - (IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.KilowattHourPerSquareMeter) => new Irradiation((_value / 3600d) / 1e3d, IrradiationUnit.KilowattHourPerSquareMeter), - (IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.MillijoulePerSquareCentimeter) => new Irradiation((_value / 1e4) / 1e-3d, IrradiationUnit.MillijoulePerSquareCentimeter), - (IrradiationUnit.JoulePerSquareMeter, IrradiationUnit.WattHourPerSquareMeter) => new Irradiation(_value / 3600d, IrradiationUnit.WattHourPerSquareMeter), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Irradiation ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not IrradiationUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(IrradiationUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(IrradiationUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(IrradiationUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -894,7 +716,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs b/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs index 27aad7836e..a8432838e9 100644 --- a/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Jerk.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Jerk : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly JerkUnit? _unit; /// @@ -104,7 +103,7 @@ public static JerkInfo CreateDefault(Func>, } /// - /// The for is [T^-3][L]. + /// The for is T^-3L. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 0, -3, 0, 0, 0, 0); @@ -119,25 +118,43 @@ public static JerkInfo CreateDefault(Func>, /// An of representing the default unit mappings for Jerk. public static IEnumerable> GetDefaultMappings() { - yield return new (JerkUnit.CentimeterPerSecondCubed, "CentimeterPerSecondCubed", "CentimetersPerSecondCubed", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Second)); - yield return new (JerkUnit.DecimeterPerSecondCubed, "DecimeterPerSecondCubed", "DecimetersPerSecondCubed", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Second)); - yield return new (JerkUnit.FootPerSecondCubed, "FootPerSecondCubed", "FeetPerSecondCubed", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second)); - yield return new (JerkUnit.InchPerSecondCubed, "InchPerSecondCubed", "InchesPerSecondCubed", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Second)); - yield return new (JerkUnit.KilometerPerSecondCubed, "KilometerPerSecondCubed", "KilometersPerSecondCubed", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second)); + yield return new (JerkUnit.CentimeterPerSecondCubed, "CentimeterPerSecondCubed", "CentimetersPerSecondCubed", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Second), + 100 + ); + yield return new (JerkUnit.DecimeterPerSecondCubed, "DecimeterPerSecondCubed", "DecimetersPerSecondCubed", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Second), + 10 + ); + yield return new (JerkUnit.FootPerSecondCubed, "FootPerSecondCubed", "FeetPerSecondCubed", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second), + new QuantityValue(1250, 381) + ); + yield return new (JerkUnit.InchPerSecondCubed, "InchPerSecondCubed", "InchesPerSecondCubed", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Second), + new QuantityValue(5000, 127) + ); + yield return new (JerkUnit.KilometerPerSecondCubed, "KilometerPerSecondCubed", "KilometersPerSecondCubed", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second), + new QuantityValue(1, 1000) + ); yield return new (JerkUnit.MeterPerSecondCubed, "MeterPerSecondCubed", "MetersPerSecondCubed", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)); - yield return new (JerkUnit.MicrometerPerSecondCubed, "MicrometerPerSecondCubed", "MicrometersPerSecondCubed", new BaseUnits(length: LengthUnit.Micrometer, time: DurationUnit.Second)); - yield return new (JerkUnit.MillimeterPerSecondCubed, "MillimeterPerSecondCubed", "MillimetersPerSecondCubed", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second)); - yield return new (JerkUnit.MillistandardGravitiesPerSecond, "MillistandardGravitiesPerSecond", "MillistandardGravitiesPerSecond", BaseUnits.Undefined); - yield return new (JerkUnit.NanometerPerSecondCubed, "NanometerPerSecondCubed", "NanometersPerSecondCubed", new BaseUnits(length: LengthUnit.Nanometer, time: DurationUnit.Second)); - yield return new (JerkUnit.StandardGravitiesPerSecond, "StandardGravitiesPerSecond", "StandardGravitiesPerSecond", BaseUnits.Undefined); + yield return new (JerkUnit.MicrometerPerSecondCubed, "MicrometerPerSecondCubed", "MicrometersPerSecondCubed", new BaseUnits(length: LengthUnit.Micrometer, time: DurationUnit.Second), + 1000000 + ); + yield return new (JerkUnit.MillimeterPerSecondCubed, "MillimeterPerSecondCubed", "MillimetersPerSecondCubed", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second), + 1000 + ); + yield return new (JerkUnit.MillistandardGravitiesPerSecond, "MillistandardGravitiesPerSecond", "MillistandardGravitiesPerSecond", BaseUnits.Undefined, + new QuantityValue(20000000, 196133) + ); + yield return new (JerkUnit.NanometerPerSecondCubed, "NanometerPerSecondCubed", "NanometersPerSecondCubed", new BaseUnits(length: LengthUnit.Nanometer, time: DurationUnit.Second), + 1000000000 + ); + yield return new (JerkUnit.StandardGravitiesPerSecond, "StandardGravitiesPerSecond", "StandardGravitiesPerSecond", BaseUnits.Undefined, + new QuantityValue(20000, 196133) + ); } } static Jerk() { - Info = JerkInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(JerkInfo.CreateDefault); } /// @@ -145,7 +162,7 @@ static Jerk() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Jerk(double value, JerkUnit unit) + public Jerk(QuantityValue value, JerkUnit unit) { _value = value; _unit = unit; @@ -159,7 +176,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -170,7 +187,8 @@ public Jerk(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -199,10 +217,8 @@ public Jerk(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public JerkUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -241,98 +257,64 @@ public Jerk(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentimetersPerSecondCubed => As(JerkUnit.CentimeterPerSecondCubed); + public QuantityValue CentimetersPerSecondCubed => this.As(JerkUnit.CentimeterPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecimetersPerSecondCubed => As(JerkUnit.DecimeterPerSecondCubed); + public QuantityValue DecimetersPerSecondCubed => this.As(JerkUnit.DecimeterPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double FeetPerSecondCubed => As(JerkUnit.FootPerSecondCubed); + public QuantityValue FeetPerSecondCubed => this.As(JerkUnit.FootPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InchesPerSecondCubed => As(JerkUnit.InchPerSecondCubed); + public QuantityValue InchesPerSecondCubed => this.As(JerkUnit.InchPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilometersPerSecondCubed => As(JerkUnit.KilometerPerSecondCubed); + public QuantityValue KilometersPerSecondCubed => this.As(JerkUnit.KilometerPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MetersPerSecondCubed => As(JerkUnit.MeterPerSecondCubed); + public QuantityValue MetersPerSecondCubed => this.As(JerkUnit.MeterPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrometersPerSecondCubed => As(JerkUnit.MicrometerPerSecondCubed); + public QuantityValue MicrometersPerSecondCubed => this.As(JerkUnit.MicrometerPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimetersPerSecondCubed => As(JerkUnit.MillimeterPerSecondCubed); + public QuantityValue MillimetersPerSecondCubed => this.As(JerkUnit.MillimeterPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillistandardGravitiesPerSecond => As(JerkUnit.MillistandardGravitiesPerSecond); + public QuantityValue MillistandardGravitiesPerSecond => this.As(JerkUnit.MillistandardGravitiesPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanometersPerSecondCubed => As(JerkUnit.NanometerPerSecondCubed); + public QuantityValue NanometersPerSecondCubed => this.As(JerkUnit.NanometerPerSecondCubed); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double StandardGravitiesPerSecond => As(JerkUnit.StandardGravitiesPerSecond); + public QuantityValue StandardGravitiesPerSecond => this.As(JerkUnit.StandardGravitiesPerSecond); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: JerkUnit -> BaseUnit - unitConverter.SetConversionFunction(JerkUnit.CentimeterPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); - unitConverter.SetConversionFunction(JerkUnit.DecimeterPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); - unitConverter.SetConversionFunction(JerkUnit.FootPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); - unitConverter.SetConversionFunction(JerkUnit.InchPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); - unitConverter.SetConversionFunction(JerkUnit.KilometerPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); - unitConverter.SetConversionFunction(JerkUnit.MicrometerPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); - unitConverter.SetConversionFunction(JerkUnit.MillimeterPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); - unitConverter.SetConversionFunction(JerkUnit.MillistandardGravitiesPerSecond, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); - unitConverter.SetConversionFunction(JerkUnit.NanometerPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); - unitConverter.SetConversionFunction(JerkUnit.StandardGravitiesPerSecond, JerkUnit.MeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MeterPerSecondCubed)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(JerkUnit.MeterPerSecondCubed, JerkUnit.MeterPerSecondCubed, quantity => quantity); - - // Register in unit converter: BaseUnit -> JerkUnit - unitConverter.SetConversionFunction(JerkUnit.MeterPerSecondCubed, JerkUnit.CentimeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.CentimeterPerSecondCubed)); - unitConverter.SetConversionFunction(JerkUnit.MeterPerSecondCubed, JerkUnit.DecimeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.DecimeterPerSecondCubed)); - unitConverter.SetConversionFunction(JerkUnit.MeterPerSecondCubed, JerkUnit.FootPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.FootPerSecondCubed)); - unitConverter.SetConversionFunction(JerkUnit.MeterPerSecondCubed, JerkUnit.InchPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.InchPerSecondCubed)); - unitConverter.SetConversionFunction(JerkUnit.MeterPerSecondCubed, JerkUnit.KilometerPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.KilometerPerSecondCubed)); - unitConverter.SetConversionFunction(JerkUnit.MeterPerSecondCubed, JerkUnit.MicrometerPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MicrometerPerSecondCubed)); - unitConverter.SetConversionFunction(JerkUnit.MeterPerSecondCubed, JerkUnit.MillimeterPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.MillimeterPerSecondCubed)); - unitConverter.SetConversionFunction(JerkUnit.MeterPerSecondCubed, JerkUnit.MillistandardGravitiesPerSecond, quantity => quantity.ToUnit(JerkUnit.MillistandardGravitiesPerSecond)); - unitConverter.SetConversionFunction(JerkUnit.MeterPerSecondCubed, JerkUnit.NanometerPerSecondCubed, quantity => quantity.ToUnit(JerkUnit.NanometerPerSecondCubed)); - unitConverter.SetConversionFunction(JerkUnit.MeterPerSecondCubed, JerkUnit.StandardGravitiesPerSecond, quantity => quantity.ToUnit(JerkUnit.StandardGravitiesPerSecond)); - } - /// /// Get unit abbreviation string. /// @@ -361,7 +343,7 @@ public static string GetAbbreviation(JerkUnit unit, IFormatProvider? provider) /// /// Creates a from . /// - public static Jerk FromCentimetersPerSecondCubed(double value) + public static Jerk FromCentimetersPerSecondCubed(QuantityValue value) { return new Jerk(value, JerkUnit.CentimeterPerSecondCubed); } @@ -369,7 +351,7 @@ public static Jerk FromCentimetersPerSecondCubed(double value) /// /// Creates a from . /// - public static Jerk FromDecimetersPerSecondCubed(double value) + public static Jerk FromDecimetersPerSecondCubed(QuantityValue value) { return new Jerk(value, JerkUnit.DecimeterPerSecondCubed); } @@ -377,7 +359,7 @@ public static Jerk FromDecimetersPerSecondCubed(double value) /// /// Creates a from . /// - public static Jerk FromFeetPerSecondCubed(double value) + public static Jerk FromFeetPerSecondCubed(QuantityValue value) { return new Jerk(value, JerkUnit.FootPerSecondCubed); } @@ -385,7 +367,7 @@ public static Jerk FromFeetPerSecondCubed(double value) /// /// Creates a from . /// - public static Jerk FromInchesPerSecondCubed(double value) + public static Jerk FromInchesPerSecondCubed(QuantityValue value) { return new Jerk(value, JerkUnit.InchPerSecondCubed); } @@ -393,7 +375,7 @@ public static Jerk FromInchesPerSecondCubed(double value) /// /// Creates a from . /// - public static Jerk FromKilometersPerSecondCubed(double value) + public static Jerk FromKilometersPerSecondCubed(QuantityValue value) { return new Jerk(value, JerkUnit.KilometerPerSecondCubed); } @@ -401,7 +383,7 @@ public static Jerk FromKilometersPerSecondCubed(double value) /// /// Creates a from . /// - public static Jerk FromMetersPerSecondCubed(double value) + public static Jerk FromMetersPerSecondCubed(QuantityValue value) { return new Jerk(value, JerkUnit.MeterPerSecondCubed); } @@ -409,7 +391,7 @@ public static Jerk FromMetersPerSecondCubed(double value) /// /// Creates a from . /// - public static Jerk FromMicrometersPerSecondCubed(double value) + public static Jerk FromMicrometersPerSecondCubed(QuantityValue value) { return new Jerk(value, JerkUnit.MicrometerPerSecondCubed); } @@ -417,7 +399,7 @@ public static Jerk FromMicrometersPerSecondCubed(double value) /// /// Creates a from . /// - public static Jerk FromMillimetersPerSecondCubed(double value) + public static Jerk FromMillimetersPerSecondCubed(QuantityValue value) { return new Jerk(value, JerkUnit.MillimeterPerSecondCubed); } @@ -425,7 +407,7 @@ public static Jerk FromMillimetersPerSecondCubed(double value) /// /// Creates a from . /// - public static Jerk FromMillistandardGravitiesPerSecond(double value) + public static Jerk FromMillistandardGravitiesPerSecond(QuantityValue value) { return new Jerk(value, JerkUnit.MillistandardGravitiesPerSecond); } @@ -433,7 +415,7 @@ public static Jerk FromMillistandardGravitiesPerSecond(double value) /// /// Creates a from . /// - public static Jerk FromNanometersPerSecondCubed(double value) + public static Jerk FromNanometersPerSecondCubed(QuantityValue value) { return new Jerk(value, JerkUnit.NanometerPerSecondCubed); } @@ -441,7 +423,7 @@ public static Jerk FromNanometersPerSecondCubed(double value) /// /// Creates a from . /// - public static Jerk FromStandardGravitiesPerSecond(double value) + public static Jerk FromStandardGravitiesPerSecond(QuantityValue value) { return new Jerk(value, JerkUnit.StandardGravitiesPerSecond); } @@ -452,7 +434,7 @@ public static Jerk FromStandardGravitiesPerSecond(double value) /// Value to convert from. /// Unit to convert from. /// Jerk unit value. - public static Jerk From(double value, JerkUnit fromUnit) + public static Jerk From(QuantityValue value, JerkUnit fromUnit) { return new Jerk(value, fromUnit); } @@ -513,10 +495,7 @@ public static Jerk Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Jerk Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -544,11 +523,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Jerk result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Jerk result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -569,7 +544,7 @@ public static JerkUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -580,7 +555,7 @@ public static JerkUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out JerkUnit unit) { return TryParseUnit(str, null, out unit); @@ -595,7 +570,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out JerkUnit uni /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out JerkUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -614,35 +589,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Jerk operator +(Jerk left, Jerk right) { - return new Jerk(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Jerk(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Jerk operator -(Jerk left, Jerk right) { - return new Jerk(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Jerk(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -664,97 +639,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Jerk left, Jerk right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Jerk left, Jerk right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Jerk left, Jerk right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Jerk left, Jerk right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Jerk other, Jerk tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Jerk left, Jerk right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Jerk other, Jerk tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Jerk left, Jerk right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Jerk other, Jerk tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Jerk otherQuantity)) + if (obj is not Jerk otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Jerk other, Jerk tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Jerk other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Jerk. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Jerk), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Jerk otherQuantity)) throw new ArgumentException("Expected type Jerk.", nameof(obj)); + if (obj is not Jerk otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -766,166 +726,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Jerk other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(JerkUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Jerk to another Jerk with the unit representation . - /// - /// The unit to convert to. - /// A Jerk with the specified unit. - public Jerk ToUnit(JerkUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Jerk with the specified unit. - public Jerk ToUnit(JerkUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Jerk), Unit, typeof(Jerk), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Jerk)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(JerkUnit unit, [NotNullWhen(true)] out Jerk? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Jerk? convertedOrNull = (Unit, unit) switch - { - // JerkUnit -> BaseUnit - (JerkUnit.CentimeterPerSecondCubed, JerkUnit.MeterPerSecondCubed) => new Jerk((_value) * 1e-2d, JerkUnit.MeterPerSecondCubed), - (JerkUnit.DecimeterPerSecondCubed, JerkUnit.MeterPerSecondCubed) => new Jerk((_value) * 1e-1d, JerkUnit.MeterPerSecondCubed), - (JerkUnit.FootPerSecondCubed, JerkUnit.MeterPerSecondCubed) => new Jerk(_value * 0.304800, JerkUnit.MeterPerSecondCubed), - (JerkUnit.InchPerSecondCubed, JerkUnit.MeterPerSecondCubed) => new Jerk(_value * 0.0254, JerkUnit.MeterPerSecondCubed), - (JerkUnit.KilometerPerSecondCubed, JerkUnit.MeterPerSecondCubed) => new Jerk((_value) * 1e3d, JerkUnit.MeterPerSecondCubed), - (JerkUnit.MicrometerPerSecondCubed, JerkUnit.MeterPerSecondCubed) => new Jerk((_value) * 1e-6d, JerkUnit.MeterPerSecondCubed), - (JerkUnit.MillimeterPerSecondCubed, JerkUnit.MeterPerSecondCubed) => new Jerk((_value) * 1e-3d, JerkUnit.MeterPerSecondCubed), - (JerkUnit.MillistandardGravitiesPerSecond, JerkUnit.MeterPerSecondCubed) => new Jerk((_value * 9.80665) * 1e-3d, JerkUnit.MeterPerSecondCubed), - (JerkUnit.NanometerPerSecondCubed, JerkUnit.MeterPerSecondCubed) => new Jerk((_value) * 1e-9d, JerkUnit.MeterPerSecondCubed), - (JerkUnit.StandardGravitiesPerSecond, JerkUnit.MeterPerSecondCubed) => new Jerk(_value * 9.80665, JerkUnit.MeterPerSecondCubed), - - // BaseUnit -> JerkUnit - (JerkUnit.MeterPerSecondCubed, JerkUnit.CentimeterPerSecondCubed) => new Jerk((_value) / 1e-2d, JerkUnit.CentimeterPerSecondCubed), - (JerkUnit.MeterPerSecondCubed, JerkUnit.DecimeterPerSecondCubed) => new Jerk((_value) / 1e-1d, JerkUnit.DecimeterPerSecondCubed), - (JerkUnit.MeterPerSecondCubed, JerkUnit.FootPerSecondCubed) => new Jerk(_value / 0.304800, JerkUnit.FootPerSecondCubed), - (JerkUnit.MeterPerSecondCubed, JerkUnit.InchPerSecondCubed) => new Jerk(_value / 0.0254, JerkUnit.InchPerSecondCubed), - (JerkUnit.MeterPerSecondCubed, JerkUnit.KilometerPerSecondCubed) => new Jerk((_value) / 1e3d, JerkUnit.KilometerPerSecondCubed), - (JerkUnit.MeterPerSecondCubed, JerkUnit.MicrometerPerSecondCubed) => new Jerk((_value) / 1e-6d, JerkUnit.MicrometerPerSecondCubed), - (JerkUnit.MeterPerSecondCubed, JerkUnit.MillimeterPerSecondCubed) => new Jerk((_value) / 1e-3d, JerkUnit.MillimeterPerSecondCubed), - (JerkUnit.MeterPerSecondCubed, JerkUnit.MillistandardGravitiesPerSecond) => new Jerk((_value / 9.80665) / 1e-3d, JerkUnit.MillistandardGravitiesPerSecond), - (JerkUnit.MeterPerSecondCubed, JerkUnit.NanometerPerSecondCubed) => new Jerk((_value) / 1e-9d, JerkUnit.NanometerPerSecondCubed), - (JerkUnit.MeterPerSecondCubed, JerkUnit.StandardGravitiesPerSecond) => new Jerk(_value / 9.80665, JerkUnit.StandardGravitiesPerSecond), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Jerk ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not JerkUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(JerkUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(JerkUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(JerkUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -940,7 +758,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs index dfd1dc8da2..c6b24320e1 100644 --- a/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/KinematicViscosity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// http://en.wikipedia.org/wiki/Viscosity /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct KinematicViscosity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -59,13 +58,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly KinematicViscosityUnit? _unit; /// @@ -110,7 +109,7 @@ public static KinematicViscosityInfo CreateDefault(Func - /// The for is [T^-1][L^2]. + /// The for is T^-1L^2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, -1, 0, 0, 0, 0); @@ -125,23 +124,37 @@ public static KinematicViscosityInfo CreateDefault(FuncAn of representing the default unit mappings for KinematicViscosity. public static IEnumerable> GetDefaultMappings() { - yield return new (KinematicViscosityUnit.Centistokes, "Centistokes", "Centistokes", BaseUnits.Undefined); - yield return new (KinematicViscosityUnit.Decistokes, "Decistokes", "Decistokes", BaseUnits.Undefined); - yield return new (KinematicViscosityUnit.Kilostokes, "Kilostokes", "Kilostokes", BaseUnits.Undefined); - yield return new (KinematicViscosityUnit.Microstokes, "Microstokes", "Microstokes", BaseUnits.Undefined); - yield return new (KinematicViscosityUnit.Millistokes, "Millistokes", "Millistokes", BaseUnits.Undefined); - yield return new (KinematicViscosityUnit.Nanostokes, "Nanostokes", "Nanostokes", BaseUnits.Undefined); - yield return new (KinematicViscosityUnit.SquareFootPerSecond, "SquareFootPerSecond", "SquareFeetPerSecond", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second)); + yield return new (KinematicViscosityUnit.Centistokes, "Centistokes", "Centistokes", BaseUnits.Undefined, + 1000000 + ); + yield return new (KinematicViscosityUnit.Decistokes, "Decistokes", "Decistokes", BaseUnits.Undefined, + 100000 + ); + yield return new (KinematicViscosityUnit.Kilostokes, "Kilostokes", "Kilostokes", BaseUnits.Undefined, + 10 + ); + yield return new (KinematicViscosityUnit.Microstokes, "Microstokes", "Microstokes", BaseUnits.Undefined, + 10000000000 + ); + yield return new (KinematicViscosityUnit.Millistokes, "Millistokes", "Millistokes", BaseUnits.Undefined, + 10000000 + ); + yield return new (KinematicViscosityUnit.Nanostokes, "Nanostokes", "Nanostokes", BaseUnits.Undefined, + 10000000000000 + ); + yield return new (KinematicViscosityUnit.SquareFootPerSecond, "SquareFootPerSecond", "SquareFeetPerSecond", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second), + new QuantityValue(1562500, 145161) + ); yield return new (KinematicViscosityUnit.SquareMeterPerSecond, "SquareMeterPerSecond", "SquareMetersPerSecond", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)); - yield return new (KinematicViscosityUnit.Stokes, "Stokes", "Stokes", BaseUnits.Undefined); + yield return new (KinematicViscosityUnit.Stokes, "Stokes", "Stokes", BaseUnits.Undefined, + 10000 + ); } } static KinematicViscosity() { - Info = KinematicViscosityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(KinematicViscosityInfo.CreateDefault); } /// @@ -149,7 +162,7 @@ static KinematicViscosity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public KinematicViscosity(double value, KinematicViscosityUnit unit) + public KinematicViscosity(QuantityValue value, KinematicViscosityUnit unit) { _value = value; _unit = unit; @@ -163,7 +176,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -174,7 +187,8 @@ public KinematicViscosity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -203,10 +217,8 @@ public KinematicViscosity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public KinematicViscosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -245,84 +257,54 @@ public KinematicViscosity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Centistokes => As(KinematicViscosityUnit.Centistokes); + public QuantityValue Centistokes => this.As(KinematicViscosityUnit.Centistokes); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Decistokes => As(KinematicViscosityUnit.Decistokes); + public QuantityValue Decistokes => this.As(KinematicViscosityUnit.Decistokes); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilostokes => As(KinematicViscosityUnit.Kilostokes); + public QuantityValue Kilostokes => this.As(KinematicViscosityUnit.Kilostokes); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microstokes => As(KinematicViscosityUnit.Microstokes); + public QuantityValue Microstokes => this.As(KinematicViscosityUnit.Microstokes); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millistokes => As(KinematicViscosityUnit.Millistokes); + public QuantityValue Millistokes => this.As(KinematicViscosityUnit.Millistokes); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanostokes => As(KinematicViscosityUnit.Nanostokes); + public QuantityValue Nanostokes => this.As(KinematicViscosityUnit.Nanostokes); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareFeetPerSecond => As(KinematicViscosityUnit.SquareFootPerSecond); + public QuantityValue SquareFeetPerSecond => this.As(KinematicViscosityUnit.SquareFootPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareMetersPerSecond => As(KinematicViscosityUnit.SquareMeterPerSecond); + public QuantityValue SquareMetersPerSecond => this.As(KinematicViscosityUnit.SquareMeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Stokes => As(KinematicViscosityUnit.Stokes); + public QuantityValue Stokes => this.As(KinematicViscosityUnit.Stokes); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: KinematicViscosityUnit -> BaseUnit - unitConverter.SetConversionFunction(KinematicViscosityUnit.Centistokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.Decistokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.Kilostokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.Microstokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.Millistokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.Nanostokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareFootPerSecond, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.Stokes, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareMeterPerSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.SquareMeterPerSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> KinematicViscosityUnit - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Centistokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Centistokes)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Decistokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Decistokes)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Kilostokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Kilostokes)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Microstokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Microstokes)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Millistokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Millistokes)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Nanostokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Nanostokes)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.SquareFootPerSecond, quantity => quantity.ToUnit(KinematicViscosityUnit.SquareFootPerSecond)); - unitConverter.SetConversionFunction(KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Stokes, quantity => quantity.ToUnit(KinematicViscosityUnit.Stokes)); - } - /// /// Get unit abbreviation string. /// @@ -351,7 +333,7 @@ public static string GetAbbreviation(KinematicViscosityUnit unit, IFormatProvide /// /// Creates a from . /// - public static KinematicViscosity FromCentistokes(double value) + public static KinematicViscosity FromCentistokes(QuantityValue value) { return new KinematicViscosity(value, KinematicViscosityUnit.Centistokes); } @@ -359,7 +341,7 @@ public static KinematicViscosity FromCentistokes(double value) /// /// Creates a from . /// - public static KinematicViscosity FromDecistokes(double value) + public static KinematicViscosity FromDecistokes(QuantityValue value) { return new KinematicViscosity(value, KinematicViscosityUnit.Decistokes); } @@ -367,7 +349,7 @@ public static KinematicViscosity FromDecistokes(double value) /// /// Creates a from . /// - public static KinematicViscosity FromKilostokes(double value) + public static KinematicViscosity FromKilostokes(QuantityValue value) { return new KinematicViscosity(value, KinematicViscosityUnit.Kilostokes); } @@ -375,7 +357,7 @@ public static KinematicViscosity FromKilostokes(double value) /// /// Creates a from . /// - public static KinematicViscosity FromMicrostokes(double value) + public static KinematicViscosity FromMicrostokes(QuantityValue value) { return new KinematicViscosity(value, KinematicViscosityUnit.Microstokes); } @@ -383,7 +365,7 @@ public static KinematicViscosity FromMicrostokes(double value) /// /// Creates a from . /// - public static KinematicViscosity FromMillistokes(double value) + public static KinematicViscosity FromMillistokes(QuantityValue value) { return new KinematicViscosity(value, KinematicViscosityUnit.Millistokes); } @@ -391,7 +373,7 @@ public static KinematicViscosity FromMillistokes(double value) /// /// Creates a from . /// - public static KinematicViscosity FromNanostokes(double value) + public static KinematicViscosity FromNanostokes(QuantityValue value) { return new KinematicViscosity(value, KinematicViscosityUnit.Nanostokes); } @@ -399,7 +381,7 @@ public static KinematicViscosity FromNanostokes(double value) /// /// Creates a from . /// - public static KinematicViscosity FromSquareFeetPerSecond(double value) + public static KinematicViscosity FromSquareFeetPerSecond(QuantityValue value) { return new KinematicViscosity(value, KinematicViscosityUnit.SquareFootPerSecond); } @@ -407,7 +389,7 @@ public static KinematicViscosity FromSquareFeetPerSecond(double value) /// /// Creates a from . /// - public static KinematicViscosity FromSquareMetersPerSecond(double value) + public static KinematicViscosity FromSquareMetersPerSecond(QuantityValue value) { return new KinematicViscosity(value, KinematicViscosityUnit.SquareMeterPerSecond); } @@ -415,7 +397,7 @@ public static KinematicViscosity FromSquareMetersPerSecond(double value) /// /// Creates a from . /// - public static KinematicViscosity FromStokes(double value) + public static KinematicViscosity FromStokes(QuantityValue value) { return new KinematicViscosity(value, KinematicViscosityUnit.Stokes); } @@ -426,7 +408,7 @@ public static KinematicViscosity FromStokes(double value) /// Value to convert from. /// Unit to convert from. /// KinematicViscosity unit value. - public static KinematicViscosity From(double value, KinematicViscosityUnit fromUnit) + public static KinematicViscosity From(QuantityValue value, KinematicViscosityUnit fromUnit) { return new KinematicViscosity(value, fromUnit); } @@ -487,10 +469,7 @@ public static KinematicViscosity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static KinematicViscosity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -518,11 +497,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out KinematicViscosi /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out KinematicViscosity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -543,7 +518,7 @@ public static KinematicViscosityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -554,7 +529,7 @@ public static KinematicViscosityUnit ParseUnit(string str, IFormatProvider? prov return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out KinematicViscosityUnit unit) { return TryParseUnit(str, null, out unit); @@ -569,7 +544,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out KinematicVis /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out KinematicViscosityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -588,35 +563,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static KinematicViscosity operator +(KinematicViscosity left, KinematicViscosity right) { - return new KinematicViscosity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new KinematicViscosity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static KinematicViscosity operator -(KinematicViscosity left, KinematicViscosity right) { - return new KinematicViscosity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new KinematicViscosity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -656,97 +631,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(KinematicViscosity left, KinematicViscosity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(KinematicViscosity left, KinematicViscosity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(KinematicViscosity left, KinematicViscosity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(KinematicViscosity left, KinematicViscosity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(KinematicViscosity other, KinematicViscosity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(KinematicViscosity left, KinematicViscosity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(KinematicViscosity other, KinematicViscosity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(KinematicViscosity left, KinematicViscosity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(KinematicViscosity other, KinematicViscosity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is KinematicViscosity otherQuantity)) + if (obj is not KinematicViscosity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(KinematicViscosity other, KinematicViscosity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(KinematicViscosity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current KinematicViscosity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(KinematicViscosity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is KinematicViscosity otherQuantity)) throw new ArgumentException("Expected type KinematicViscosity.", nameof(obj)); + if (obj is not KinematicViscosity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -758,162 +718,24 @@ public int CompareTo(object? obj) /// public int CompareTo(KinematicViscosity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(KinematicViscosityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this KinematicViscosity to another KinematicViscosity with the unit representation . - /// - /// The unit to convert to. - /// A KinematicViscosity with the specified unit. - public KinematicViscosity ToUnit(KinematicViscosityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A KinematicViscosity with the specified unit. - public KinematicViscosity ToUnit(KinematicViscosityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(KinematicViscosity), Unit, typeof(KinematicViscosity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (KinematicViscosity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(KinematicViscosityUnit unit, [NotNullWhen(true)] out KinematicViscosity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - KinematicViscosity? convertedOrNull = (Unit, unit) switch - { - // KinematicViscosityUnit -> BaseUnit - (KinematicViscosityUnit.Centistokes, KinematicViscosityUnit.SquareMeterPerSecond) => new KinematicViscosity((_value / 1e4) * 1e-2d, KinematicViscosityUnit.SquareMeterPerSecond), - (KinematicViscosityUnit.Decistokes, KinematicViscosityUnit.SquareMeterPerSecond) => new KinematicViscosity((_value / 1e4) * 1e-1d, KinematicViscosityUnit.SquareMeterPerSecond), - (KinematicViscosityUnit.Kilostokes, KinematicViscosityUnit.SquareMeterPerSecond) => new KinematicViscosity((_value / 1e4) * 1e3d, KinematicViscosityUnit.SquareMeterPerSecond), - (KinematicViscosityUnit.Microstokes, KinematicViscosityUnit.SquareMeterPerSecond) => new KinematicViscosity((_value / 1e4) * 1e-6d, KinematicViscosityUnit.SquareMeterPerSecond), - (KinematicViscosityUnit.Millistokes, KinematicViscosityUnit.SquareMeterPerSecond) => new KinematicViscosity((_value / 1e4) * 1e-3d, KinematicViscosityUnit.SquareMeterPerSecond), - (KinematicViscosityUnit.Nanostokes, KinematicViscosityUnit.SquareMeterPerSecond) => new KinematicViscosity((_value / 1e4) * 1e-9d, KinematicViscosityUnit.SquareMeterPerSecond), - (KinematicViscosityUnit.SquareFootPerSecond, KinematicViscosityUnit.SquareMeterPerSecond) => new KinematicViscosity(_value * 9.290304e-2, KinematicViscosityUnit.SquareMeterPerSecond), - (KinematicViscosityUnit.Stokes, KinematicViscosityUnit.SquareMeterPerSecond) => new KinematicViscosity(_value / 1e4, KinematicViscosityUnit.SquareMeterPerSecond), - - // BaseUnit -> KinematicViscosityUnit - (KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Centistokes) => new KinematicViscosity((_value * 1e4) / 1e-2d, KinematicViscosityUnit.Centistokes), - (KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Decistokes) => new KinematicViscosity((_value * 1e4) / 1e-1d, KinematicViscosityUnit.Decistokes), - (KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Kilostokes) => new KinematicViscosity((_value * 1e4) / 1e3d, KinematicViscosityUnit.Kilostokes), - (KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Microstokes) => new KinematicViscosity((_value * 1e4) / 1e-6d, KinematicViscosityUnit.Microstokes), - (KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Millistokes) => new KinematicViscosity((_value * 1e4) / 1e-3d, KinematicViscosityUnit.Millistokes), - (KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Nanostokes) => new KinematicViscosity((_value * 1e4) / 1e-9d, KinematicViscosityUnit.Nanostokes), - (KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.SquareFootPerSecond) => new KinematicViscosity(_value / 9.290304e-2, KinematicViscosityUnit.SquareFootPerSecond), - (KinematicViscosityUnit.SquareMeterPerSecond, KinematicViscosityUnit.Stokes) => new KinematicViscosity(_value * 1e4, KinematicViscosityUnit.Stokes), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public KinematicViscosity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not KinematicViscosityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(KinematicViscosityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(KinematicViscosityUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(KinematicViscosityUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -928,7 +750,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/LeakRate.g.cs b/UnitsNet/GeneratedCode/Quantities/LeakRate.g.cs index 31aedbb04b..9c31a40ff3 100644 --- a/UnitsNet/GeneratedCode/Quantities/LeakRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LeakRate.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://www.leybold.com/en-in/knowledge/vacuum-fundamentals/leak-detection/definition-and-measurement-of-vacuum-leaks /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct LeakRate : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly LeakRateUnit? _unit; /// @@ -104,7 +103,7 @@ public static LeakRateInfo CreateDefault(Func - /// The for is [T^-3][L^2][M]. + /// The for is T^-3L^2M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); @@ -119,18 +118,22 @@ public static LeakRateInfo CreateDefault(FuncAn of representing the default unit mappings for LeakRate. public static IEnumerable> GetDefaultMappings() { - yield return new (LeakRateUnit.AtmCubicCentimeterPerSecond, "AtmCubicCentimeterPerSecond", "AtmCubicCentimetersPerSecond", BaseUnits.Undefined); - yield return new (LeakRateUnit.MillibarLiterPerSecond, "MillibarLiterPerSecond", "MillibarLitersPerSecond", BaseUnits.Undefined); + yield return new (LeakRateUnit.AtmCubicCentimeterPerSecond, "AtmCubicCentimeterPerSecond", "AtmCubicCentimetersPerSecond", BaseUnits.Undefined, + new QuantityValue(40000, 4053) + ); + yield return new (LeakRateUnit.MillibarLiterPerSecond, "MillibarLiterPerSecond", "MillibarLitersPerSecond", BaseUnits.Undefined, + 10 + ); yield return new (LeakRateUnit.PascalCubicMeterPerSecond, "PascalCubicMeterPerSecond", "PascalCubicMetersPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (LeakRateUnit.TorrLiterPerSecond, "TorrLiterPerSecond", "TorrLitersPerSecond", BaseUnits.Undefined); + yield return new (LeakRateUnit.TorrLiterPerSecond, "TorrLiterPerSecond", "TorrLitersPerSecond", BaseUnits.Undefined, + new QuantityValue(15, 2) + ); } } static LeakRate() { - Info = LeakRateInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(LeakRateInfo.CreateDefault); } /// @@ -138,7 +141,7 @@ static LeakRate() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public LeakRate(double value, LeakRateUnit unit) + public LeakRate(QuantityValue value, LeakRateUnit unit) { _value = value; _unit = unit; @@ -152,7 +155,7 @@ public LeakRate(double value, LeakRateUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public LeakRate(double value, UnitSystem unitSystem) + public LeakRate(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -163,7 +166,8 @@ public LeakRate(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -192,10 +196,8 @@ public LeakRate(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public LeakRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -234,49 +236,29 @@ public LeakRate(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AtmCubicCentimetersPerSecond => As(LeakRateUnit.AtmCubicCentimeterPerSecond); + public QuantityValue AtmCubicCentimetersPerSecond => this.As(LeakRateUnit.AtmCubicCentimeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillibarLitersPerSecond => As(LeakRateUnit.MillibarLiterPerSecond); + public QuantityValue MillibarLitersPerSecond => this.As(LeakRateUnit.MillibarLiterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PascalCubicMetersPerSecond => As(LeakRateUnit.PascalCubicMeterPerSecond); + public QuantityValue PascalCubicMetersPerSecond => this.As(LeakRateUnit.PascalCubicMeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TorrLitersPerSecond => As(LeakRateUnit.TorrLiterPerSecond); + public QuantityValue TorrLitersPerSecond => this.As(LeakRateUnit.TorrLiterPerSecond); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: LeakRateUnit -> BaseUnit - unitConverter.SetConversionFunction(LeakRateUnit.AtmCubicCentimeterPerSecond, LeakRateUnit.PascalCubicMeterPerSecond, quantity => quantity.ToUnit(LeakRateUnit.PascalCubicMeterPerSecond)); - unitConverter.SetConversionFunction(LeakRateUnit.MillibarLiterPerSecond, LeakRateUnit.PascalCubicMeterPerSecond, quantity => quantity.ToUnit(LeakRateUnit.PascalCubicMeterPerSecond)); - unitConverter.SetConversionFunction(LeakRateUnit.TorrLiterPerSecond, LeakRateUnit.PascalCubicMeterPerSecond, quantity => quantity.ToUnit(LeakRateUnit.PascalCubicMeterPerSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(LeakRateUnit.PascalCubicMeterPerSecond, LeakRateUnit.PascalCubicMeterPerSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> LeakRateUnit - unitConverter.SetConversionFunction(LeakRateUnit.PascalCubicMeterPerSecond, LeakRateUnit.AtmCubicCentimeterPerSecond, quantity => quantity.ToUnit(LeakRateUnit.AtmCubicCentimeterPerSecond)); - unitConverter.SetConversionFunction(LeakRateUnit.PascalCubicMeterPerSecond, LeakRateUnit.MillibarLiterPerSecond, quantity => quantity.ToUnit(LeakRateUnit.MillibarLiterPerSecond)); - unitConverter.SetConversionFunction(LeakRateUnit.PascalCubicMeterPerSecond, LeakRateUnit.TorrLiterPerSecond, quantity => quantity.ToUnit(LeakRateUnit.TorrLiterPerSecond)); - } - /// /// Get unit abbreviation string. /// @@ -305,7 +287,7 @@ public static string GetAbbreviation(LeakRateUnit unit, IFormatProvider? provide /// /// Creates a from . /// - public static LeakRate FromAtmCubicCentimetersPerSecond(double value) + public static LeakRate FromAtmCubicCentimetersPerSecond(QuantityValue value) { return new LeakRate(value, LeakRateUnit.AtmCubicCentimeterPerSecond); } @@ -313,7 +295,7 @@ public static LeakRate FromAtmCubicCentimetersPerSecond(double value) /// /// Creates a from . /// - public static LeakRate FromMillibarLitersPerSecond(double value) + public static LeakRate FromMillibarLitersPerSecond(QuantityValue value) { return new LeakRate(value, LeakRateUnit.MillibarLiterPerSecond); } @@ -321,7 +303,7 @@ public static LeakRate FromMillibarLitersPerSecond(double value) /// /// Creates a from . /// - public static LeakRate FromPascalCubicMetersPerSecond(double value) + public static LeakRate FromPascalCubicMetersPerSecond(QuantityValue value) { return new LeakRate(value, LeakRateUnit.PascalCubicMeterPerSecond); } @@ -329,7 +311,7 @@ public static LeakRate FromPascalCubicMetersPerSecond(double value) /// /// Creates a from . /// - public static LeakRate FromTorrLitersPerSecond(double value) + public static LeakRate FromTorrLitersPerSecond(QuantityValue value) { return new LeakRate(value, LeakRateUnit.TorrLiterPerSecond); } @@ -340,7 +322,7 @@ public static LeakRate FromTorrLitersPerSecond(double value) /// Value to convert from. /// Unit to convert from. /// LeakRate unit value. - public static LeakRate From(double value, LeakRateUnit fromUnit) + public static LeakRate From(QuantityValue value, LeakRateUnit fromUnit) { return new LeakRate(value, fromUnit); } @@ -401,10 +383,7 @@ public static LeakRate Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static LeakRate Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -432,11 +411,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out LeakRate result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out LeakRate result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -457,7 +432,7 @@ public static LeakRateUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -468,7 +443,7 @@ public static LeakRateUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out LeakRateUnit unit) { return TryParseUnit(str, null, out unit); @@ -483,7 +458,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out LeakRateUnit /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out LeakRateUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -502,35 +477,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static LeakRate operator +(LeakRate left, LeakRate right) { - return new LeakRate(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new LeakRate(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static LeakRate operator -(LeakRate left, LeakRate right) { - return new LeakRate(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new LeakRate(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static LeakRate operator *(double left, LeakRate right) + public static LeakRate operator *(QuantityValue left, LeakRate right) { return new LeakRate(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static LeakRate operator *(LeakRate left, double right) + public static LeakRate operator *(LeakRate left, QuantityValue right) { return new LeakRate(left.Value * right, left.Unit); } /// Get from dividing by value. - public static LeakRate operator /(LeakRate left, double right) + public static LeakRate operator /(LeakRate left, QuantityValue right) { return new LeakRate(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(LeakRate left, LeakRate right) + public static QuantityValue operator /(LeakRate left, LeakRate right) { return left.PascalCubicMetersPerSecond / right.PascalCubicMetersPerSecond; } @@ -542,97 +517,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(LeakRate left, LeakRate right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(LeakRate left, LeakRate right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(LeakRate left, LeakRate right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(LeakRate left, LeakRate right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(LeakRate other, LeakRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(LeakRate left, LeakRate right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(LeakRate other, LeakRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(LeakRate left, LeakRate right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(LeakRate other, LeakRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is LeakRate otherQuantity)) + if (obj is not LeakRate otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(LeakRate other, LeakRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(LeakRate other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current LeakRate. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(LeakRate), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is LeakRate otherQuantity)) throw new ArgumentException("Expected type LeakRate.", nameof(obj)); + if (obj is not LeakRate otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -644,152 +604,24 @@ public int CompareTo(object? obj) /// public int CompareTo(LeakRate other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LeakRateUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this LeakRate to another LeakRate with the unit representation . - /// - /// The unit to convert to. - /// A LeakRate with the specified unit. - public LeakRate ToUnit(LeakRateUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A LeakRate with the specified unit. - public LeakRate ToUnit(LeakRateUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(LeakRate), Unit, typeof(LeakRate), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (LeakRate)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(LeakRateUnit unit, [NotNullWhen(true)] out LeakRate? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - LeakRate? convertedOrNull = (Unit, unit) switch - { - // LeakRateUnit -> BaseUnit - (LeakRateUnit.AtmCubicCentimeterPerSecond, LeakRateUnit.PascalCubicMeterPerSecond) => new LeakRate(_value / (1e6 / 101325), LeakRateUnit.PascalCubicMeterPerSecond), - (LeakRateUnit.MillibarLiterPerSecond, LeakRateUnit.PascalCubicMeterPerSecond) => new LeakRate(_value / 10, LeakRateUnit.PascalCubicMeterPerSecond), - (LeakRateUnit.TorrLiterPerSecond, LeakRateUnit.PascalCubicMeterPerSecond) => new LeakRate(_value / 7.5, LeakRateUnit.PascalCubicMeterPerSecond), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> LeakRateUnit - (LeakRateUnit.PascalCubicMeterPerSecond, LeakRateUnit.AtmCubicCentimeterPerSecond) => new LeakRate(_value * (1e6 / 101325), LeakRateUnit.AtmCubicCentimeterPerSecond), - (LeakRateUnit.PascalCubicMeterPerSecond, LeakRateUnit.MillibarLiterPerSecond) => new LeakRate(_value * 10, LeakRateUnit.MillibarLiterPerSecond), - (LeakRateUnit.PascalCubicMeterPerSecond, LeakRateUnit.TorrLiterPerSecond) => new LeakRate(_value * 7.5, LeakRateUnit.TorrLiterPerSecond), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public LeakRate ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not LeakRateUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LeakRateUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is LeakRateUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LeakRateUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(LeakRateUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(LeakRateUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -804,7 +636,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Length.g.cs b/UnitsNet/GeneratedCode/Quantities/Length.g.cs index 114aa9369d..c3da3db349 100644 --- a/UnitsNet/GeneratedCode/Quantities/Length.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Length.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Length : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -70,13 +69,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly LengthUnit? _unit; /// @@ -121,7 +120,7 @@ public static LengthInfo CreateDefault(Func - /// The for is [L]. + /// The for is L. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 0, 0, 0, 0, 0, 0); @@ -136,56 +135,136 @@ public static LengthInfo CreateDefault(FuncAn of representing the default unit mappings for Length. public static IEnumerable> GetDefaultMappings() { - yield return new (LengthUnit.Angstrom, "Angstrom", "Angstroms", new BaseUnits(length: LengthUnit.Angstrom)); - yield return new (LengthUnit.AstronomicalUnit, "AstronomicalUnit", "AstronomicalUnits", new BaseUnits(length: LengthUnit.AstronomicalUnit)); - yield return new (LengthUnit.Centimeter, "Centimeter", "Centimeters", new BaseUnits(length: LengthUnit.Centimeter)); - yield return new (LengthUnit.Chain, "Chain", "Chains", new BaseUnits(length: LengthUnit.Chain)); - yield return new (LengthUnit.DataMile, "DataMile", "DataMiles", new BaseUnits(length: LengthUnit.DataMile)); - yield return new (LengthUnit.Decameter, "Decameter", "Decameters", new BaseUnits(length: LengthUnit.Decameter)); - yield return new (LengthUnit.Decimeter, "Decimeter", "Decimeters", new BaseUnits(length: LengthUnit.Decimeter)); - yield return new (LengthUnit.DtpPica, "DtpPica", "DtpPicas", new BaseUnits(length: LengthUnit.DtpPica)); - yield return new (LengthUnit.DtpPoint, "DtpPoint", "DtpPoints", new BaseUnits(length: LengthUnit.DtpPoint)); - yield return new (LengthUnit.Fathom, "Fathom", "Fathoms", new BaseUnits(length: LengthUnit.Fathom)); - yield return new (LengthUnit.Femtometer, "Femtometer", "Femtometers", new BaseUnits(length: LengthUnit.Femtometer)); - yield return new (LengthUnit.Foot, "Foot", "Feet", new BaseUnits(length: LengthUnit.Foot)); - yield return new (LengthUnit.Gigameter, "Gigameter", "Gigameters", new BaseUnits(length: LengthUnit.Gigameter)); - yield return new (LengthUnit.Hand, "Hand", "Hands", new BaseUnits(length: LengthUnit.Hand)); - yield return new (LengthUnit.Hectometer, "Hectometer", "Hectometers", new BaseUnits(length: LengthUnit.Hectometer)); - yield return new (LengthUnit.Inch, "Inch", "Inches", new BaseUnits(length: LengthUnit.Inch)); - yield return new (LengthUnit.Kilofoot, "Kilofoot", "Kilofeet", new BaseUnits(length: LengthUnit.Kilofoot)); - yield return new (LengthUnit.KilolightYear, "KilolightYear", "KilolightYears", new BaseUnits(length: LengthUnit.KilolightYear)); - yield return new (LengthUnit.Kilometer, "Kilometer", "Kilometers", new BaseUnits(length: LengthUnit.Kilometer)); - yield return new (LengthUnit.Kiloparsec, "Kiloparsec", "Kiloparsecs", new BaseUnits(length: LengthUnit.Kiloparsec)); - yield return new (LengthUnit.Kiloyard, "Kiloyard", "Kiloyards", new BaseUnits(length: LengthUnit.Kiloyard)); - yield return new (LengthUnit.LightYear, "LightYear", "LightYears", new BaseUnits(length: LengthUnit.LightYear)); - yield return new (LengthUnit.MegalightYear, "MegalightYear", "MegalightYears", new BaseUnits(length: LengthUnit.MegalightYear)); - yield return new (LengthUnit.Megameter, "Megameter", "Megameters", new BaseUnits(length: LengthUnit.Megameter)); - yield return new (LengthUnit.Megaparsec, "Megaparsec", "Megaparsecs", new BaseUnits(length: LengthUnit.Megaparsec)); + yield return new (LengthUnit.Angstrom, "Angstrom", "Angstroms", new BaseUnits(length: LengthUnit.Angstrom), + 10000000000 + ); + yield return new (LengthUnit.AstronomicalUnit, "AstronomicalUnit", "AstronomicalUnits", new BaseUnits(length: LengthUnit.AstronomicalUnit), + new QuantityValue(1, 149597870700) + ); + yield return new (LengthUnit.Centimeter, "Centimeter", "Centimeters", new BaseUnits(length: LengthUnit.Centimeter), + 100 + ); + yield return new (LengthUnit.Chain, "Chain", "Chains", new BaseUnits(length: LengthUnit.Chain), + new QuantityValue(625, 12573) + ); + yield return new (LengthUnit.DataMile, "DataMile", "DataMiles", new BaseUnits(length: LengthUnit.DataMile), + new QuantityValue(5, 9144) + ); + yield return new (LengthUnit.Decameter, "Decameter", "Decameters", new BaseUnits(length: LengthUnit.Decameter), + new QuantityValue(1, 10) + ); + yield return new (LengthUnit.Decimeter, "Decimeter", "Decimeters", new BaseUnits(length: LengthUnit.Decimeter), + 10 + ); + yield return new (LengthUnit.DtpPica, "DtpPica", "DtpPicas", new BaseUnits(length: LengthUnit.DtpPica), + new QuantityValue(30000, 127) + ); + yield return new (LengthUnit.DtpPoint, "DtpPoint", "DtpPoints", new BaseUnits(length: LengthUnit.DtpPoint), + new QuantityValue(360000, 127) + ); + yield return new (LengthUnit.Fathom, "Fathom", "Fathoms", new BaseUnits(length: LengthUnit.Fathom), + new QuantityValue(625, 1143) + ); + yield return new (LengthUnit.Femtometer, "Femtometer", "Femtometers", new BaseUnits(length: LengthUnit.Femtometer), + 1000000000000000 + ); + yield return new (LengthUnit.Foot, "Foot", "Feet", new BaseUnits(length: LengthUnit.Foot), + new QuantityValue(1250, 381) + ); + yield return new (LengthUnit.Gigameter, "Gigameter", "Gigameters", new BaseUnits(length: LengthUnit.Gigameter), + new QuantityValue(1, 1000000000) + ); + yield return new (LengthUnit.Hand, "Hand", "Hands", new BaseUnits(length: LengthUnit.Hand), + new QuantityValue(1250, 127) + ); + yield return new (LengthUnit.Hectometer, "Hectometer", "Hectometers", new BaseUnits(length: LengthUnit.Hectometer), + new QuantityValue(1, 100) + ); + yield return new (LengthUnit.Inch, "Inch", "Inches", new BaseUnits(length: LengthUnit.Inch), + new QuantityValue(5000, 127) + ); + yield return new (LengthUnit.Kilofoot, "Kilofoot", "Kilofeet", new BaseUnits(length: LengthUnit.Kilofoot), + new QuantityValue(5, 1524) + ); + yield return new (LengthUnit.KilolightYear, "KilolightYear", "KilolightYears", new BaseUnits(length: LengthUnit.KilolightYear), + new QuantityValue(1, QuantityValue.PowerOfTen(7) * new BigInteger(946073047258)) + ); + yield return new (LengthUnit.Kilometer, "Kilometer", "Kilometers", new BaseUnits(length: LengthUnit.Kilometer), + new QuantityValue(1, 1000) + ); + yield return new (LengthUnit.Kiloparsec, "Kiloparsec", "Kiloparsecs", new BaseUnits(length: LengthUnit.Kiloparsec), + new QuantityValue(1, QuantityValue.PowerOfTen(8) * new BigInteger(308567758128)) + ); + yield return new (LengthUnit.Kiloyard, "Kiloyard", "Kiloyards", new BaseUnits(length: LengthUnit.Kiloyard), + new QuantityValue(5, 4572) + ); + yield return new (LengthUnit.LightYear, "LightYear", "LightYears", new BaseUnits(length: LengthUnit.LightYear), + new QuantityValue(1, 9460730472580000) + ); + yield return new (LengthUnit.MegalightYear, "MegalightYear", "MegalightYears", new BaseUnits(length: LengthUnit.MegalightYear), + new QuantityValue(1, QuantityValue.PowerOfTen(10) * new BigInteger(946073047258)) + ); + yield return new (LengthUnit.Megameter, "Megameter", "Megameters", new BaseUnits(length: LengthUnit.Megameter), + new QuantityValue(1, 1000000) + ); + yield return new (LengthUnit.Megaparsec, "Megaparsec", "Megaparsecs", new BaseUnits(length: LengthUnit.Megaparsec), + new QuantityValue(1, QuantityValue.PowerOfTen(11) * new BigInteger(308567758128)) + ); yield return new (LengthUnit.Meter, "Meter", "Meters", new BaseUnits(length: LengthUnit.Meter)); - yield return new (LengthUnit.Microinch, "Microinch", "Microinches", new BaseUnits(length: LengthUnit.Microinch)); - yield return new (LengthUnit.Micrometer, "Micrometer", "Micrometers", new BaseUnits(length: LengthUnit.Micrometer)); - yield return new (LengthUnit.Mil, "Mil", "Mils", new BaseUnits(length: LengthUnit.Mil)); - yield return new (LengthUnit.Mile, "Mile", "Miles", new BaseUnits(length: LengthUnit.Mile)); - yield return new (LengthUnit.Millimeter, "Millimeter", "Millimeters", new BaseUnits(length: LengthUnit.Millimeter)); - yield return new (LengthUnit.Nanometer, "Nanometer", "Nanometers", new BaseUnits(length: LengthUnit.Nanometer)); - yield return new (LengthUnit.NauticalMile, "NauticalMile", "NauticalMiles", new BaseUnits(length: LengthUnit.NauticalMile)); - yield return new (LengthUnit.Parsec, "Parsec", "Parsecs", new BaseUnits(length: LengthUnit.Parsec)); - yield return new (LengthUnit.Picometer, "Picometer", "Picometers", new BaseUnits(length: LengthUnit.Picometer)); - yield return new (LengthUnit.PrinterPica, "PrinterPica", "PrinterPicas", new BaseUnits(length: LengthUnit.PrinterPica)); - yield return new (LengthUnit.PrinterPoint, "PrinterPoint", "PrinterPoints", new BaseUnits(length: LengthUnit.PrinterPoint)); - yield return new (LengthUnit.Shackle, "Shackle", "Shackles", new BaseUnits(length: LengthUnit.Shackle)); - yield return new (LengthUnit.SolarRadius, "SolarRadius", "SolarRadiuses", new BaseUnits(length: LengthUnit.SolarRadius)); - yield return new (LengthUnit.Twip, "Twip", "Twips", new BaseUnits(length: LengthUnit.Twip)); - yield return new (LengthUnit.UsSurveyFoot, "UsSurveyFoot", "UsSurveyFeet", new BaseUnits(length: LengthUnit.UsSurveyFoot)); - yield return new (LengthUnit.Yard, "Yard", "Yards", new BaseUnits(length: LengthUnit.Yard)); + yield return new (LengthUnit.Microinch, "Microinch", "Microinches", new BaseUnits(length: LengthUnit.Microinch), + new QuantityValue(5000000000, 127) + ); + yield return new (LengthUnit.Micrometer, "Micrometer", "Micrometers", new BaseUnits(length: LengthUnit.Micrometer), + 1000000 + ); + yield return new (LengthUnit.Mil, "Mil", "Mils", new BaseUnits(length: LengthUnit.Mil), + new QuantityValue(5000000, 127) + ); + yield return new (LengthUnit.Mile, "Mile", "Miles", new BaseUnits(length: LengthUnit.Mile), + new QuantityValue(125, 201168) + ); + yield return new (LengthUnit.Millimeter, "Millimeter", "Millimeters", new BaseUnits(length: LengthUnit.Millimeter), + 1000 + ); + yield return new (LengthUnit.Nanometer, "Nanometer", "Nanometers", new BaseUnits(length: LengthUnit.Nanometer), + 1000000000 + ); + yield return new (LengthUnit.NauticalMile, "NauticalMile", "NauticalMiles", new BaseUnits(length: LengthUnit.NauticalMile), + new QuantityValue(1, 1852) + ); + yield return new (LengthUnit.Parsec, "Parsec", "Parsecs", new BaseUnits(length: LengthUnit.Parsec), + new QuantityValue(1, 30856775812800000) + ); + yield return new (LengthUnit.Picometer, "Picometer", "Picometers", new BaseUnits(length: LengthUnit.Picometer), + 1000000000000 + ); + yield return new (LengthUnit.PrinterPica, "PrinterPica", "PrinterPicas", new BaseUnits(length: LengthUnit.PrinterPica), + new QuantityValue(60225, 254) + ); + yield return new (LengthUnit.PrinterPoint, "PrinterPoint", "PrinterPoints", new BaseUnits(length: LengthUnit.PrinterPoint), + new QuantityValue(361350, 127) + ); + yield return new (LengthUnit.Shackle, "Shackle", "Shackles", new BaseUnits(length: LengthUnit.Shackle), + new QuantityValue(125, 3429) + ); + yield return new (LengthUnit.SolarRadius, "SolarRadius", "SolarRadiuses", new BaseUnits(length: LengthUnit.SolarRadius), + new QuantityValue(1, 695700000) + ); + yield return new (LengthUnit.Twip, "Twip", "Twips", new BaseUnits(length: LengthUnit.Twip), + new QuantityValue(7200000, 127) + ); + yield return new (LengthUnit.UsSurveyFoot, "UsSurveyFoot", "UsSurveyFeet", new BaseUnits(length: LengthUnit.UsSurveyFoot), + new QuantityValue(3937, 1200) + ); + yield return new (LengthUnit.Yard, "Yard", "Yards", new BaseUnits(length: LengthUnit.Yard), + new QuantityValue(1250, 1143) + ); } } static Length() { - Info = LengthInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(LengthInfo.CreateDefault); } /// @@ -193,7 +272,7 @@ static Length() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Length(double value, LengthUnit unit) + public Length(QuantityValue value, LengthUnit unit) { _value = value; _unit = unit; @@ -207,7 +286,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -218,7 +297,8 @@ public Length(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -247,10 +327,8 @@ public Length(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public LengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -289,315 +367,219 @@ public Length(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Angstroms => As(LengthUnit.Angstrom); + public QuantityValue Angstroms => this.As(LengthUnit.Angstrom); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AstronomicalUnits => As(LengthUnit.AstronomicalUnit); + public QuantityValue AstronomicalUnits => this.As(LengthUnit.AstronomicalUnit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Centimeters => As(LengthUnit.Centimeter); + public QuantityValue Centimeters => this.As(LengthUnit.Centimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Chains => As(LengthUnit.Chain); + public QuantityValue Chains => this.As(LengthUnit.Chain); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DataMiles => As(LengthUnit.DataMile); + public QuantityValue DataMiles => this.As(LengthUnit.DataMile); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Decameters => As(LengthUnit.Decameter); + public QuantityValue Decameters => this.As(LengthUnit.Decameter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Decimeters => As(LengthUnit.Decimeter); + public QuantityValue Decimeters => this.As(LengthUnit.Decimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DtpPicas => As(LengthUnit.DtpPica); + public QuantityValue DtpPicas => this.As(LengthUnit.DtpPica); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DtpPoints => As(LengthUnit.DtpPoint); + public QuantityValue DtpPoints => this.As(LengthUnit.DtpPoint); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Fathoms => As(LengthUnit.Fathom); + public QuantityValue Fathoms => this.As(LengthUnit.Fathom); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Femtometers => As(LengthUnit.Femtometer); + public QuantityValue Femtometers => this.As(LengthUnit.Femtometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Feet => As(LengthUnit.Foot); + public QuantityValue Feet => this.As(LengthUnit.Foot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigameters => As(LengthUnit.Gigameter); + public QuantityValue Gigameters => this.As(LengthUnit.Gigameter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Hands => As(LengthUnit.Hand); + public QuantityValue Hands => this.As(LengthUnit.Hand); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Hectometers => As(LengthUnit.Hectometer); + public QuantityValue Hectometers => this.As(LengthUnit.Hectometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Inches => As(LengthUnit.Inch); + public QuantityValue Inches => this.As(LengthUnit.Inch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilofeet => As(LengthUnit.Kilofoot); + public QuantityValue Kilofeet => this.As(LengthUnit.Kilofoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilolightYears => As(LengthUnit.KilolightYear); + public QuantityValue KilolightYears => this.As(LengthUnit.KilolightYear); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilometers => As(LengthUnit.Kilometer); + public QuantityValue Kilometers => this.As(LengthUnit.Kilometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kiloparsecs => As(LengthUnit.Kiloparsec); + public QuantityValue Kiloparsecs => this.As(LengthUnit.Kiloparsec); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kiloyards => As(LengthUnit.Kiloyard); + public QuantityValue Kiloyards => this.As(LengthUnit.Kiloyard); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double LightYears => As(LengthUnit.LightYear); + public QuantityValue LightYears => this.As(LengthUnit.LightYear); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegalightYears => As(LengthUnit.MegalightYear); + public QuantityValue MegalightYears => this.As(LengthUnit.MegalightYear); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megameters => As(LengthUnit.Megameter); + public QuantityValue Megameters => this.As(LengthUnit.Megameter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megaparsecs => As(LengthUnit.Megaparsec); + public QuantityValue Megaparsecs => this.As(LengthUnit.Megaparsec); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Meters => As(LengthUnit.Meter); + public QuantityValue Meters => this.As(LengthUnit.Meter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microinches => As(LengthUnit.Microinch); + public QuantityValue Microinches => this.As(LengthUnit.Microinch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Micrometers => As(LengthUnit.Micrometer); + public QuantityValue Micrometers => this.As(LengthUnit.Micrometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Mils => As(LengthUnit.Mil); + public QuantityValue Mils => this.As(LengthUnit.Mil); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Miles => As(LengthUnit.Mile); + public QuantityValue Miles => this.As(LengthUnit.Mile); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millimeters => As(LengthUnit.Millimeter); + public QuantityValue Millimeters => this.As(LengthUnit.Millimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanometers => As(LengthUnit.Nanometer); + public QuantityValue Nanometers => this.As(LengthUnit.Nanometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NauticalMiles => As(LengthUnit.NauticalMile); + public QuantityValue NauticalMiles => this.As(LengthUnit.NauticalMile); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Parsecs => As(LengthUnit.Parsec); + public QuantityValue Parsecs => this.As(LengthUnit.Parsec); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Picometers => As(LengthUnit.Picometer); + public QuantityValue Picometers => this.As(LengthUnit.Picometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PrinterPicas => As(LengthUnit.PrinterPica); + public QuantityValue PrinterPicas => this.As(LengthUnit.PrinterPica); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PrinterPoints => As(LengthUnit.PrinterPoint); + public QuantityValue PrinterPoints => this.As(LengthUnit.PrinterPoint); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Shackles => As(LengthUnit.Shackle); + public QuantityValue Shackles => this.As(LengthUnit.Shackle); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SolarRadiuses => As(LengthUnit.SolarRadius); + public QuantityValue SolarRadiuses => this.As(LengthUnit.SolarRadius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Twips => As(LengthUnit.Twip); + public QuantityValue Twips => this.As(LengthUnit.Twip); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsSurveyFeet => As(LengthUnit.UsSurveyFoot); + public QuantityValue UsSurveyFeet => this.As(LengthUnit.UsSurveyFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Yards => As(LengthUnit.Yard); + public QuantityValue Yards => this.As(LengthUnit.Yard); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: LengthUnit -> BaseUnit - unitConverter.SetConversionFunction(LengthUnit.Angstrom, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.AstronomicalUnit, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Centimeter, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Chain, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.DataMile, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Decameter, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Decimeter, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.DtpPica, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.DtpPoint, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Fathom, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Femtometer, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Foot, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Gigameter, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Hand, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Hectometer, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Inch, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Kilofoot, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.KilolightYear, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Kilometer, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Kiloparsec, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Kiloyard, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.LightYear, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.MegalightYear, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Megameter, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Megaparsec, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Microinch, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Micrometer, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Mil, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Mile, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Millimeter, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Nanometer, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.NauticalMile, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Parsec, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Picometer, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.PrinterPica, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.PrinterPoint, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Shackle, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.SolarRadius, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Twip, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.UsSurveyFoot, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - unitConverter.SetConversionFunction(LengthUnit.Yard, LengthUnit.Meter, quantity => quantity.ToUnit(LengthUnit.Meter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Meter, quantity => quantity); - - // Register in unit converter: BaseUnit -> LengthUnit - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Angstrom, quantity => quantity.ToUnit(LengthUnit.Angstrom)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.AstronomicalUnit, quantity => quantity.ToUnit(LengthUnit.AstronomicalUnit)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Centimeter, quantity => quantity.ToUnit(LengthUnit.Centimeter)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Chain, quantity => quantity.ToUnit(LengthUnit.Chain)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.DataMile, quantity => quantity.ToUnit(LengthUnit.DataMile)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Decameter, quantity => quantity.ToUnit(LengthUnit.Decameter)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Decimeter, quantity => quantity.ToUnit(LengthUnit.Decimeter)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.DtpPica, quantity => quantity.ToUnit(LengthUnit.DtpPica)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.DtpPoint, quantity => quantity.ToUnit(LengthUnit.DtpPoint)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Fathom, quantity => quantity.ToUnit(LengthUnit.Fathom)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Femtometer, quantity => quantity.ToUnit(LengthUnit.Femtometer)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Foot, quantity => quantity.ToUnit(LengthUnit.Foot)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Gigameter, quantity => quantity.ToUnit(LengthUnit.Gigameter)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Hand, quantity => quantity.ToUnit(LengthUnit.Hand)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Hectometer, quantity => quantity.ToUnit(LengthUnit.Hectometer)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Inch, quantity => quantity.ToUnit(LengthUnit.Inch)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Kilofoot, quantity => quantity.ToUnit(LengthUnit.Kilofoot)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.KilolightYear, quantity => quantity.ToUnit(LengthUnit.KilolightYear)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Kilometer, quantity => quantity.ToUnit(LengthUnit.Kilometer)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Kiloparsec, quantity => quantity.ToUnit(LengthUnit.Kiloparsec)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Kiloyard, quantity => quantity.ToUnit(LengthUnit.Kiloyard)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.LightYear, quantity => quantity.ToUnit(LengthUnit.LightYear)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.MegalightYear, quantity => quantity.ToUnit(LengthUnit.MegalightYear)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Megameter, quantity => quantity.ToUnit(LengthUnit.Megameter)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Megaparsec, quantity => quantity.ToUnit(LengthUnit.Megaparsec)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Microinch, quantity => quantity.ToUnit(LengthUnit.Microinch)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Micrometer, quantity => quantity.ToUnit(LengthUnit.Micrometer)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Mil, quantity => quantity.ToUnit(LengthUnit.Mil)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Mile, quantity => quantity.ToUnit(LengthUnit.Mile)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Millimeter, quantity => quantity.ToUnit(LengthUnit.Millimeter)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Nanometer, quantity => quantity.ToUnit(LengthUnit.Nanometer)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.NauticalMile, quantity => quantity.ToUnit(LengthUnit.NauticalMile)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Parsec, quantity => quantity.ToUnit(LengthUnit.Parsec)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Picometer, quantity => quantity.ToUnit(LengthUnit.Picometer)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.PrinterPica, quantity => quantity.ToUnit(LengthUnit.PrinterPica)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.PrinterPoint, quantity => quantity.ToUnit(LengthUnit.PrinterPoint)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Shackle, quantity => quantity.ToUnit(LengthUnit.Shackle)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.SolarRadius, quantity => quantity.ToUnit(LengthUnit.SolarRadius)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Twip, quantity => quantity.ToUnit(LengthUnit.Twip)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.UsSurveyFoot, quantity => quantity.ToUnit(LengthUnit.UsSurveyFoot)); - unitConverter.SetConversionFunction(LengthUnit.Meter, LengthUnit.Yard, quantity => quantity.ToUnit(LengthUnit.Yard)); - } - /// /// Get unit abbreviation string. /// @@ -626,7 +608,7 @@ public static string GetAbbreviation(LengthUnit unit, IFormatProvider? provider) /// /// Creates a from . /// - public static Length FromAngstroms(double value) + public static Length FromAngstroms(QuantityValue value) { return new Length(value, LengthUnit.Angstrom); } @@ -634,7 +616,7 @@ public static Length FromAngstroms(double value) /// /// Creates a from . /// - public static Length FromAstronomicalUnits(double value) + public static Length FromAstronomicalUnits(QuantityValue value) { return new Length(value, LengthUnit.AstronomicalUnit); } @@ -642,7 +624,7 @@ public static Length FromAstronomicalUnits(double value) /// /// Creates a from . /// - public static Length FromCentimeters(double value) + public static Length FromCentimeters(QuantityValue value) { return new Length(value, LengthUnit.Centimeter); } @@ -650,7 +632,7 @@ public static Length FromCentimeters(double value) /// /// Creates a from . /// - public static Length FromChains(double value) + public static Length FromChains(QuantityValue value) { return new Length(value, LengthUnit.Chain); } @@ -658,7 +640,7 @@ public static Length FromChains(double value) /// /// Creates a from . /// - public static Length FromDataMiles(double value) + public static Length FromDataMiles(QuantityValue value) { return new Length(value, LengthUnit.DataMile); } @@ -666,7 +648,7 @@ public static Length FromDataMiles(double value) /// /// Creates a from . /// - public static Length FromDecameters(double value) + public static Length FromDecameters(QuantityValue value) { return new Length(value, LengthUnit.Decameter); } @@ -674,7 +656,7 @@ public static Length FromDecameters(double value) /// /// Creates a from . /// - public static Length FromDecimeters(double value) + public static Length FromDecimeters(QuantityValue value) { return new Length(value, LengthUnit.Decimeter); } @@ -682,7 +664,7 @@ public static Length FromDecimeters(double value) /// /// Creates a from . /// - public static Length FromDtpPicas(double value) + public static Length FromDtpPicas(QuantityValue value) { return new Length(value, LengthUnit.DtpPica); } @@ -690,7 +672,7 @@ public static Length FromDtpPicas(double value) /// /// Creates a from . /// - public static Length FromDtpPoints(double value) + public static Length FromDtpPoints(QuantityValue value) { return new Length(value, LengthUnit.DtpPoint); } @@ -698,7 +680,7 @@ public static Length FromDtpPoints(double value) /// /// Creates a from . /// - public static Length FromFathoms(double value) + public static Length FromFathoms(QuantityValue value) { return new Length(value, LengthUnit.Fathom); } @@ -706,7 +688,7 @@ public static Length FromFathoms(double value) /// /// Creates a from . /// - public static Length FromFemtometers(double value) + public static Length FromFemtometers(QuantityValue value) { return new Length(value, LengthUnit.Femtometer); } @@ -714,7 +696,7 @@ public static Length FromFemtometers(double value) /// /// Creates a from . /// - public static Length FromFeet(double value) + public static Length FromFeet(QuantityValue value) { return new Length(value, LengthUnit.Foot); } @@ -722,7 +704,7 @@ public static Length FromFeet(double value) /// /// Creates a from . /// - public static Length FromGigameters(double value) + public static Length FromGigameters(QuantityValue value) { return new Length(value, LengthUnit.Gigameter); } @@ -730,7 +712,7 @@ public static Length FromGigameters(double value) /// /// Creates a from . /// - public static Length FromHands(double value) + public static Length FromHands(QuantityValue value) { return new Length(value, LengthUnit.Hand); } @@ -738,7 +720,7 @@ public static Length FromHands(double value) /// /// Creates a from . /// - public static Length FromHectometers(double value) + public static Length FromHectometers(QuantityValue value) { return new Length(value, LengthUnit.Hectometer); } @@ -746,7 +728,7 @@ public static Length FromHectometers(double value) /// /// Creates a from . /// - public static Length FromInches(double value) + public static Length FromInches(QuantityValue value) { return new Length(value, LengthUnit.Inch); } @@ -754,7 +736,7 @@ public static Length FromInches(double value) /// /// Creates a from . /// - public static Length FromKilofeet(double value) + public static Length FromKilofeet(QuantityValue value) { return new Length(value, LengthUnit.Kilofoot); } @@ -762,7 +744,7 @@ public static Length FromKilofeet(double value) /// /// Creates a from . /// - public static Length FromKilolightYears(double value) + public static Length FromKilolightYears(QuantityValue value) { return new Length(value, LengthUnit.KilolightYear); } @@ -770,7 +752,7 @@ public static Length FromKilolightYears(double value) /// /// Creates a from . /// - public static Length FromKilometers(double value) + public static Length FromKilometers(QuantityValue value) { return new Length(value, LengthUnit.Kilometer); } @@ -778,7 +760,7 @@ public static Length FromKilometers(double value) /// /// Creates a from . /// - public static Length FromKiloparsecs(double value) + public static Length FromKiloparsecs(QuantityValue value) { return new Length(value, LengthUnit.Kiloparsec); } @@ -786,7 +768,7 @@ public static Length FromKiloparsecs(double value) /// /// Creates a from . /// - public static Length FromKiloyards(double value) + public static Length FromKiloyards(QuantityValue value) { return new Length(value, LengthUnit.Kiloyard); } @@ -794,7 +776,7 @@ public static Length FromKiloyards(double value) /// /// Creates a from . /// - public static Length FromLightYears(double value) + public static Length FromLightYears(QuantityValue value) { return new Length(value, LengthUnit.LightYear); } @@ -802,7 +784,7 @@ public static Length FromLightYears(double value) /// /// Creates a from . /// - public static Length FromMegalightYears(double value) + public static Length FromMegalightYears(QuantityValue value) { return new Length(value, LengthUnit.MegalightYear); } @@ -810,7 +792,7 @@ public static Length FromMegalightYears(double value) /// /// Creates a from . /// - public static Length FromMegameters(double value) + public static Length FromMegameters(QuantityValue value) { return new Length(value, LengthUnit.Megameter); } @@ -818,7 +800,7 @@ public static Length FromMegameters(double value) /// /// Creates a from . /// - public static Length FromMegaparsecs(double value) + public static Length FromMegaparsecs(QuantityValue value) { return new Length(value, LengthUnit.Megaparsec); } @@ -826,7 +808,7 @@ public static Length FromMegaparsecs(double value) /// /// Creates a from . /// - public static Length FromMeters(double value) + public static Length FromMeters(QuantityValue value) { return new Length(value, LengthUnit.Meter); } @@ -834,7 +816,7 @@ public static Length FromMeters(double value) /// /// Creates a from . /// - public static Length FromMicroinches(double value) + public static Length FromMicroinches(QuantityValue value) { return new Length(value, LengthUnit.Microinch); } @@ -842,7 +824,7 @@ public static Length FromMicroinches(double value) /// /// Creates a from . /// - public static Length FromMicrometers(double value) + public static Length FromMicrometers(QuantityValue value) { return new Length(value, LengthUnit.Micrometer); } @@ -850,7 +832,7 @@ public static Length FromMicrometers(double value) /// /// Creates a from . /// - public static Length FromMils(double value) + public static Length FromMils(QuantityValue value) { return new Length(value, LengthUnit.Mil); } @@ -858,7 +840,7 @@ public static Length FromMils(double value) /// /// Creates a from . /// - public static Length FromMiles(double value) + public static Length FromMiles(QuantityValue value) { return new Length(value, LengthUnit.Mile); } @@ -866,7 +848,7 @@ public static Length FromMiles(double value) /// /// Creates a from . /// - public static Length FromMillimeters(double value) + public static Length FromMillimeters(QuantityValue value) { return new Length(value, LengthUnit.Millimeter); } @@ -874,7 +856,7 @@ public static Length FromMillimeters(double value) /// /// Creates a from . /// - public static Length FromNanometers(double value) + public static Length FromNanometers(QuantityValue value) { return new Length(value, LengthUnit.Nanometer); } @@ -882,7 +864,7 @@ public static Length FromNanometers(double value) /// /// Creates a from . /// - public static Length FromNauticalMiles(double value) + public static Length FromNauticalMiles(QuantityValue value) { return new Length(value, LengthUnit.NauticalMile); } @@ -890,7 +872,7 @@ public static Length FromNauticalMiles(double value) /// /// Creates a from . /// - public static Length FromParsecs(double value) + public static Length FromParsecs(QuantityValue value) { return new Length(value, LengthUnit.Parsec); } @@ -898,7 +880,7 @@ public static Length FromParsecs(double value) /// /// Creates a from . /// - public static Length FromPicometers(double value) + public static Length FromPicometers(QuantityValue value) { return new Length(value, LengthUnit.Picometer); } @@ -906,7 +888,7 @@ public static Length FromPicometers(double value) /// /// Creates a from . /// - public static Length FromPrinterPicas(double value) + public static Length FromPrinterPicas(QuantityValue value) { return new Length(value, LengthUnit.PrinterPica); } @@ -914,7 +896,7 @@ public static Length FromPrinterPicas(double value) /// /// Creates a from . /// - public static Length FromPrinterPoints(double value) + public static Length FromPrinterPoints(QuantityValue value) { return new Length(value, LengthUnit.PrinterPoint); } @@ -922,7 +904,7 @@ public static Length FromPrinterPoints(double value) /// /// Creates a from . /// - public static Length FromShackles(double value) + public static Length FromShackles(QuantityValue value) { return new Length(value, LengthUnit.Shackle); } @@ -930,7 +912,7 @@ public static Length FromShackles(double value) /// /// Creates a from . /// - public static Length FromSolarRadiuses(double value) + public static Length FromSolarRadiuses(QuantityValue value) { return new Length(value, LengthUnit.SolarRadius); } @@ -938,7 +920,7 @@ public static Length FromSolarRadiuses(double value) /// /// Creates a from . /// - public static Length FromTwips(double value) + public static Length FromTwips(QuantityValue value) { return new Length(value, LengthUnit.Twip); } @@ -946,7 +928,7 @@ public static Length FromTwips(double value) /// /// Creates a from . /// - public static Length FromUsSurveyFeet(double value) + public static Length FromUsSurveyFeet(QuantityValue value) { return new Length(value, LengthUnit.UsSurveyFoot); } @@ -954,7 +936,7 @@ public static Length FromUsSurveyFeet(double value) /// /// Creates a from . /// - public static Length FromYards(double value) + public static Length FromYards(QuantityValue value) { return new Length(value, LengthUnit.Yard); } @@ -965,7 +947,7 @@ public static Length FromYards(double value) /// Value to convert from. /// Unit to convert from. /// Length unit value. - public static Length From(double value, LengthUnit fromUnit) + public static Length From(QuantityValue value, LengthUnit fromUnit) { return new Length(value, fromUnit); } @@ -1026,10 +1008,7 @@ public static Length Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Length Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -1057,11 +1036,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Length result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Length result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -1082,7 +1057,7 @@ public static LengthUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -1093,7 +1068,7 @@ public static LengthUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out LengthUnit unit) { return TryParseUnit(str, null, out unit); @@ -1108,7 +1083,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out LengthUnit u /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out LengthUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -1127,35 +1102,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Length operator +(Length left, Length right) { - return new Length(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Length(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Length operator -(Length left, Length right) { - return new Length(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Length(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -1168,7 +1143,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// The corresponding inverse quantity, . public ReciprocalLength Inverse() { - return ReciprocalLength.FromInverseMeters(1 / Meters); + return UnitConverter.Default.ConvertTo(Value, Unit, ReciprocalLength.Info); } /// Get from * . @@ -1286,97 +1261,82 @@ public ReciprocalLength Inverse() /// Returns true if less or equal to. public static bool operator <=(Length left, Length right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Length left, Length right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Length left, Length right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Length left, Length right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Length other, Length tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Length left, Length right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Length other, Length tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Length left, Length right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Length other, Length tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Length otherQuantity)) + if (obj is not Length otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Length other, Length tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Length other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Length. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Length), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Length otherQuantity)) throw new ArgumentException("Expected type Length.", nameof(obj)); + if (obj is not Length otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1388,228 +1348,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Length other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LengthUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Length to another Length with the unit representation . - /// - /// The unit to convert to. - /// A Length with the specified unit. - public Length ToUnit(LengthUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Length with the specified unit. - public Length ToUnit(LengthUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Length), Unit, typeof(Length), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Length)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(LengthUnit unit, [NotNullWhen(true)] out Length? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Length? convertedOrNull = (Unit, unit) switch - { - // LengthUnit -> BaseUnit - (LengthUnit.Angstrom, LengthUnit.Meter) => new Length(_value * 1e-10, LengthUnit.Meter), - (LengthUnit.AstronomicalUnit, LengthUnit.Meter) => new Length(_value * 1.4959787070e11, LengthUnit.Meter), - (LengthUnit.Centimeter, LengthUnit.Meter) => new Length((_value) * 1e-2d, LengthUnit.Meter), - (LengthUnit.Chain, LengthUnit.Meter) => new Length(_value * 20.1168, LengthUnit.Meter), - (LengthUnit.DataMile, LengthUnit.Meter) => new Length(_value * 1828.8, LengthUnit.Meter), - (LengthUnit.Decameter, LengthUnit.Meter) => new Length((_value) * 1e1d, LengthUnit.Meter), - (LengthUnit.Decimeter, LengthUnit.Meter) => new Length((_value) * 1e-1d, LengthUnit.Meter), - (LengthUnit.DtpPica, LengthUnit.Meter) => new Length(_value * 2.54e-2 / 6, LengthUnit.Meter), - (LengthUnit.DtpPoint, LengthUnit.Meter) => new Length(_value * 2.54e-2 / 72, LengthUnit.Meter), - (LengthUnit.Fathom, LengthUnit.Meter) => new Length(_value * 1.8288, LengthUnit.Meter), - (LengthUnit.Femtometer, LengthUnit.Meter) => new Length((_value) * 1e-15d, LengthUnit.Meter), - (LengthUnit.Foot, LengthUnit.Meter) => new Length(_value * 0.3048, LengthUnit.Meter), - (LengthUnit.Gigameter, LengthUnit.Meter) => new Length((_value) * 1e9d, LengthUnit.Meter), - (LengthUnit.Hand, LengthUnit.Meter) => new Length(_value * 1.016e-1, LengthUnit.Meter), - (LengthUnit.Hectometer, LengthUnit.Meter) => new Length((_value) * 1e2d, LengthUnit.Meter), - (LengthUnit.Inch, LengthUnit.Meter) => new Length(_value * 2.54e-2, LengthUnit.Meter), - (LengthUnit.Kilofoot, LengthUnit.Meter) => new Length((_value * 0.3048) * 1e3d, LengthUnit.Meter), - (LengthUnit.KilolightYear, LengthUnit.Meter) => new Length((_value * 9.46073047258e15) * 1e3d, LengthUnit.Meter), - (LengthUnit.Kilometer, LengthUnit.Meter) => new Length((_value) * 1e3d, LengthUnit.Meter), - (LengthUnit.Kiloparsec, LengthUnit.Meter) => new Length((_value * 3.08567758128e16) * 1e3d, LengthUnit.Meter), - (LengthUnit.Kiloyard, LengthUnit.Meter) => new Length((_value * 0.9144) * 1e3d, LengthUnit.Meter), - (LengthUnit.LightYear, LengthUnit.Meter) => new Length(_value * 9.46073047258e15, LengthUnit.Meter), - (LengthUnit.MegalightYear, LengthUnit.Meter) => new Length((_value * 9.46073047258e15) * 1e6d, LengthUnit.Meter), - (LengthUnit.Megameter, LengthUnit.Meter) => new Length((_value) * 1e6d, LengthUnit.Meter), - (LengthUnit.Megaparsec, LengthUnit.Meter) => new Length((_value * 3.08567758128e16) * 1e6d, LengthUnit.Meter), - (LengthUnit.Microinch, LengthUnit.Meter) => new Length(_value * 2.54e-8, LengthUnit.Meter), - (LengthUnit.Micrometer, LengthUnit.Meter) => new Length((_value) * 1e-6d, LengthUnit.Meter), - (LengthUnit.Mil, LengthUnit.Meter) => new Length(_value * 2.54e-5, LengthUnit.Meter), - (LengthUnit.Mile, LengthUnit.Meter) => new Length(_value * 1609.344, LengthUnit.Meter), - (LengthUnit.Millimeter, LengthUnit.Meter) => new Length((_value) * 1e-3d, LengthUnit.Meter), - (LengthUnit.Nanometer, LengthUnit.Meter) => new Length((_value) * 1e-9d, LengthUnit.Meter), - (LengthUnit.NauticalMile, LengthUnit.Meter) => new Length(_value * 1852, LengthUnit.Meter), - (LengthUnit.Parsec, LengthUnit.Meter) => new Length(_value * 3.08567758128e16, LengthUnit.Meter), - (LengthUnit.Picometer, LengthUnit.Meter) => new Length((_value) * 1e-12d, LengthUnit.Meter), - (LengthUnit.PrinterPica, LengthUnit.Meter) => new Length(_value * 2.54e-2 * 400 / 2409, LengthUnit.Meter), - (LengthUnit.PrinterPoint, LengthUnit.Meter) => new Length(_value * 2.54e-2 / 72.27 , LengthUnit.Meter), - (LengthUnit.Shackle, LengthUnit.Meter) => new Length(_value * 27.432, LengthUnit.Meter), - (LengthUnit.SolarRadius, LengthUnit.Meter) => new Length(_value * 6.95700e8, LengthUnit.Meter), - (LengthUnit.Twip, LengthUnit.Meter) => new Length(_value * 2.54e-2 / 1440, LengthUnit.Meter), - (LengthUnit.UsSurveyFoot, LengthUnit.Meter) => new Length(_value * 1200 / 3937, LengthUnit.Meter), - (LengthUnit.Yard, LengthUnit.Meter) => new Length(_value * 0.9144, LengthUnit.Meter), - - // BaseUnit -> LengthUnit - (LengthUnit.Meter, LengthUnit.Angstrom) => new Length(_value / 1e-10, LengthUnit.Angstrom), - (LengthUnit.Meter, LengthUnit.AstronomicalUnit) => new Length(_value / 1.4959787070e11, LengthUnit.AstronomicalUnit), - (LengthUnit.Meter, LengthUnit.Centimeter) => new Length((_value) / 1e-2d, LengthUnit.Centimeter), - (LengthUnit.Meter, LengthUnit.Chain) => new Length(_value / 20.1168, LengthUnit.Chain), - (LengthUnit.Meter, LengthUnit.DataMile) => new Length(_value / 1828.8, LengthUnit.DataMile), - (LengthUnit.Meter, LengthUnit.Decameter) => new Length((_value) / 1e1d, LengthUnit.Decameter), - (LengthUnit.Meter, LengthUnit.Decimeter) => new Length((_value) / 1e-1d, LengthUnit.Decimeter), - (LengthUnit.Meter, LengthUnit.DtpPica) => new Length(_value * 6 / 2.54e-2, LengthUnit.DtpPica), - (LengthUnit.Meter, LengthUnit.DtpPoint) => new Length(_value * 72 / 2.54e-2, LengthUnit.DtpPoint), - (LengthUnit.Meter, LengthUnit.Fathom) => new Length(_value / 1.8288, LengthUnit.Fathom), - (LengthUnit.Meter, LengthUnit.Femtometer) => new Length((_value) / 1e-15d, LengthUnit.Femtometer), - (LengthUnit.Meter, LengthUnit.Foot) => new Length(_value / 0.3048, LengthUnit.Foot), - (LengthUnit.Meter, LengthUnit.Gigameter) => new Length((_value) / 1e9d, LengthUnit.Gigameter), - (LengthUnit.Meter, LengthUnit.Hand) => new Length(_value / 1.016e-1, LengthUnit.Hand), - (LengthUnit.Meter, LengthUnit.Hectometer) => new Length((_value) / 1e2d, LengthUnit.Hectometer), - (LengthUnit.Meter, LengthUnit.Inch) => new Length(_value / 2.54e-2, LengthUnit.Inch), - (LengthUnit.Meter, LengthUnit.Kilofoot) => new Length((_value / 0.3048) / 1e3d, LengthUnit.Kilofoot), - (LengthUnit.Meter, LengthUnit.KilolightYear) => new Length((_value / 9.46073047258e15) / 1e3d, LengthUnit.KilolightYear), - (LengthUnit.Meter, LengthUnit.Kilometer) => new Length((_value) / 1e3d, LengthUnit.Kilometer), - (LengthUnit.Meter, LengthUnit.Kiloparsec) => new Length((_value / 3.08567758128e16) / 1e3d, LengthUnit.Kiloparsec), - (LengthUnit.Meter, LengthUnit.Kiloyard) => new Length((_value / 0.9144) / 1e3d, LengthUnit.Kiloyard), - (LengthUnit.Meter, LengthUnit.LightYear) => new Length(_value / 9.46073047258e15, LengthUnit.LightYear), - (LengthUnit.Meter, LengthUnit.MegalightYear) => new Length((_value / 9.46073047258e15) / 1e6d, LengthUnit.MegalightYear), - (LengthUnit.Meter, LengthUnit.Megameter) => new Length((_value) / 1e6d, LengthUnit.Megameter), - (LengthUnit.Meter, LengthUnit.Megaparsec) => new Length((_value / 3.08567758128e16) / 1e6d, LengthUnit.Megaparsec), - (LengthUnit.Meter, LengthUnit.Microinch) => new Length(_value / 2.54e-8, LengthUnit.Microinch), - (LengthUnit.Meter, LengthUnit.Micrometer) => new Length((_value) / 1e-6d, LengthUnit.Micrometer), - (LengthUnit.Meter, LengthUnit.Mil) => new Length(_value / 2.54e-5, LengthUnit.Mil), - (LengthUnit.Meter, LengthUnit.Mile) => new Length(_value / 1609.344, LengthUnit.Mile), - (LengthUnit.Meter, LengthUnit.Millimeter) => new Length((_value) / 1e-3d, LengthUnit.Millimeter), - (LengthUnit.Meter, LengthUnit.Nanometer) => new Length((_value) / 1e-9d, LengthUnit.Nanometer), - (LengthUnit.Meter, LengthUnit.NauticalMile) => new Length(_value / 1852, LengthUnit.NauticalMile), - (LengthUnit.Meter, LengthUnit.Parsec) => new Length(_value / 3.08567758128e16, LengthUnit.Parsec), - (LengthUnit.Meter, LengthUnit.Picometer) => new Length((_value) / 1e-12d, LengthUnit.Picometer), - (LengthUnit.Meter, LengthUnit.PrinterPica) => new Length(_value / (2.54e-2 * 400 / 2409), LengthUnit.PrinterPica), - (LengthUnit.Meter, LengthUnit.PrinterPoint) => new Length(_value * 72.27 / 2.54e-2, LengthUnit.PrinterPoint), - (LengthUnit.Meter, LengthUnit.Shackle) => new Length(_value / 27.432, LengthUnit.Shackle), - (LengthUnit.Meter, LengthUnit.SolarRadius) => new Length(_value / 6.95700e8, LengthUnit.SolarRadius), - (LengthUnit.Meter, LengthUnit.Twip) => new Length(_value * 1440 / 2.54e-2, LengthUnit.Twip), - (LengthUnit.Meter, LengthUnit.UsSurveyFoot) => new Length(_value * 3937 / 1200, LengthUnit.UsSurveyFoot), - (LengthUnit.Meter, LengthUnit.Yard) => new Length(_value / 0.9144, LengthUnit.Yard), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Length ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not LengthUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LengthUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(LengthUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(LengthUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1624,7 +1380,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Level.g.cs b/UnitsNet/GeneratedCode/Quantities/Level.g.cs index a3756f2b3e..4315ad4e89 100644 --- a/UnitsNet/GeneratedCode/Quantities/Level.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Level.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Level : ILogarithmicQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly LevelUnit? _unit; /// @@ -117,15 +116,15 @@ public static LevelInfo CreateDefault(Func public static IEnumerable> GetDefaultMappings() { yield return new (LevelUnit.Decibel, "Decibel", "Decibels", BaseUnits.Undefined); - yield return new (LevelUnit.Neper, "Neper", "Nepers", BaseUnits.Undefined); + yield return new (LevelUnit.Neper, "Neper", "Nepers", BaseUnits.Undefined, + new QuantityValue(57564627, 500000000) + ); } } static Level() { - Info = LevelInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(LevelInfo.CreateDefault); } /// @@ -133,7 +132,7 @@ static Level() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Level(double value, LevelUnit unit) + public Level(QuantityValue value, LevelUnit unit) { _value = value; _unit = unit; @@ -144,7 +143,8 @@ public Level(double value, LevelUnit unit) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -170,16 +170,14 @@ public Level(double value, LevelUnit unit) public static Level Zero => Info.Zero; /// - public static double LogarithmicScalingFactor {get;} = 10; + public static QuantityValue LogarithmicScalingFactor {get;} = 10; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public LevelUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -212,7 +210,7 @@ public Level(double value, LevelUnit unit) #endif #if NETSTANDARD2_0 - double ILogarithmicQuantity.LogarithmicScalingFactor => LogarithmicScalingFactor; + QuantityValue ILogarithmicQuantity.LogarithmicScalingFactor => LogarithmicScalingFactor; #endif #endregion @@ -222,35 +220,19 @@ public Level(double value, LevelUnit unit) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Decibels => As(LevelUnit.Decibel); + public QuantityValue Decibels => this.As(LevelUnit.Decibel); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nepers => As(LevelUnit.Neper); + public QuantityValue Nepers => this.As(LevelUnit.Neper); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: LevelUnit -> BaseUnit - unitConverter.SetConversionFunction(LevelUnit.Neper, LevelUnit.Decibel, quantity => quantity.ToUnit(LevelUnit.Decibel)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(LevelUnit.Decibel, LevelUnit.Decibel, quantity => quantity); - - // Register in unit converter: BaseUnit -> LevelUnit - unitConverter.SetConversionFunction(LevelUnit.Decibel, LevelUnit.Neper, quantity => quantity.ToUnit(LevelUnit.Neper)); - } - /// /// Get unit abbreviation string. /// @@ -279,7 +261,7 @@ public static string GetAbbreviation(LevelUnit unit, IFormatProvider? provider) /// /// Creates a from . /// - public static Level FromDecibels(double value) + public static Level FromDecibels(QuantityValue value) { return new Level(value, LevelUnit.Decibel); } @@ -287,7 +269,7 @@ public static Level FromDecibels(double value) /// /// Creates a from . /// - public static Level FromNepers(double value) + public static Level FromNepers(QuantityValue value) { return new Level(value, LevelUnit.Neper); } @@ -298,7 +280,7 @@ public static Level FromNepers(double value) /// Value to convert from. /// Unit to convert from. /// Level unit value. - public static Level From(double value, LevelUnit fromUnit) + public static Level From(QuantityValue value, LevelUnit fromUnit) { return new Level(value, fromUnit); } @@ -359,10 +341,7 @@ public static Level Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Level Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -390,11 +369,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Level result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Level result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -415,7 +390,7 @@ public static LevelUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -426,7 +401,7 @@ public static LevelUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out LevelUnit unit) { return TryParseUnit(str, null, out unit); @@ -441,7 +416,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out LevelUnit un /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out LevelUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -452,53 +427,61 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? #region Logarithmic Arithmetic Operators /// Negate the value. - public static Level operator -(Level right) + public static Level operator -(Level quantity) { - return new Level(-right.Value, right.Unit); + return new Level(-quantity.Value, quantity.Unit); } /// Get from logarithmic addition of two . + /// This operation involves a conversion of the values to linear space, which is not guaranteed to produce an exact value. + /// The final result is rounded to 15 significant digits. + /// public static Level operator +(Level left, Level right) { // 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.ToUnit(left.Unit).Value / 10)), left.Unit); + var leftUnit = left.Unit; + return new Level(QuantityValueExtensions.AddWithLogScaling(left.Value, right.As(leftUnit), LogarithmicScalingFactor), leftUnit); } /// Get from logarithmic subtraction of two . + /// This operation involves a conversion of the values to linear space, which is not guaranteed to produce an exact value. + /// The final result is rounded to 15 significant digits. + /// public static Level operator -(Level left, Level right) { // 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.ToUnit(left.Unit).Value / 10)), left.Unit); + var leftUnit = left.Unit; + return new Level(QuantityValueExtensions.SubtractWithLogScaling(left.Value, right.As(leftUnit), LogarithmicScalingFactor), leftUnit); } /// 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); } /// Get from logarithmic multiplication of value and . - public static Level operator *(Level left, double right) + public static Level operator *(Level left, QuantityValue right) { // Logarithmic multiplication = addition return new Level(left.Value + right, left.Unit); } /// Get from logarithmic division of by value. - public static Level operator /(Level left, double right) + public static Level operator /(Level left, QuantityValue right) { // Logarithmic division = subtraction return new Level(left.Value - right, left.Unit); } /// Get ratio value from logarithmic division of by . - public static double operator /(Level left, Level right) + public static QuantityValue operator /(Level left, Level right) { // Logarithmic division = subtraction - return Convert.ToDouble(left.Value - right.ToUnit(left.Unit).Value); + return left.Value - right.As(left.Unit); } #endregion @@ -508,97 +491,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Level left, Level right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Level left, Level right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Level left, Level right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Level left, Level right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Level other, Level tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Level left, Level right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Level other, Level tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Level left, Level right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Level other, Level tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Level otherQuantity)) + if (obj is not Level otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Level other, Level tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Level other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Level. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Level), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Level otherQuantity)) throw new ArgumentException("Expected type Level.", nameof(obj)); + if (obj is not Level otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -610,148 +578,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Level other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LevelUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this Level to another Level with the unit representation . - /// - /// The unit to convert to. - /// A Level with the specified unit. - public Level ToUnit(LevelUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Level with the specified unit. - public Level ToUnit(LevelUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Level), Unit, typeof(Level), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Level)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(LevelUnit unit, [NotNullWhen(true)] out Level? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Level? convertedOrNull = (Unit, unit) switch - { - // LevelUnit -> BaseUnit - (LevelUnit.Neper, LevelUnit.Decibel) => new Level((1 / 0.115129254) * _value, LevelUnit.Decibel), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> LevelUnit - (LevelUnit.Decibel, LevelUnit.Neper) => new Level(0.115129254 * _value, LevelUnit.Neper), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Level ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not LevelUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LevelUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is LevelUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LevelUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(LevelUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(LevelUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -766,7 +610,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs index 772d18adc0..0f348e564d 100644 --- a/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LinearDensity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// http://en.wikipedia.org/wiki/Linear_density /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct LinearDensity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -58,13 +57,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly LinearDensityUnit? _unit; /// @@ -109,7 +108,7 @@ public static LinearDensityInfo CreateDefault(Func - /// The for is [L^-1][M]. + /// The for is L^-1M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 1, 0, 0, 0, 0, 0); @@ -124,32 +123,64 @@ public static LinearDensityInfo CreateDefault(FuncAn of representing the default unit mappings for LinearDensity. public static IEnumerable> GetDefaultMappings() { - yield return new (LinearDensityUnit.GramPerCentimeter, "GramPerCentimeter", "GramsPerCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram)); - yield return new (LinearDensityUnit.GramPerFoot, "GramPerFoot", "GramsPerFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Gram)); - yield return new (LinearDensityUnit.GramPerMeter, "GramPerMeter", "GramsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram)); - yield return new (LinearDensityUnit.GramPerMillimeter, "GramPerMillimeter", "GramsPerMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram)); - yield return new (LinearDensityUnit.KilogramPerCentimeter, "KilogramPerCentimeter", "KilogramsPerCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram)); - yield return new (LinearDensityUnit.KilogramPerFoot, "KilogramPerFoot", "KilogramsPerFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Kilogram)); + yield return new (LinearDensityUnit.GramPerCentimeter, "GramPerCentimeter", "GramsPerCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram), + 10 + ); + yield return new (LinearDensityUnit.GramPerFoot, "GramPerFoot", "GramsPerFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Gram), + new QuantityValue(1524, 5) + ); + yield return new (LinearDensityUnit.GramPerMeter, "GramPerMeter", "GramsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram), + 1000 + ); + yield return new (LinearDensityUnit.GramPerMillimeter, "GramPerMillimeter", "GramsPerMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram), + 1 + ); + yield return new (LinearDensityUnit.KilogramPerCentimeter, "KilogramPerCentimeter", "KilogramsPerCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram), + new QuantityValue(1, 100) + ); + yield return new (LinearDensityUnit.KilogramPerFoot, "KilogramPerFoot", "KilogramsPerFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Kilogram), + new QuantityValue(381, 1250) + ); yield return new (LinearDensityUnit.KilogramPerMeter, "KilogramPerMeter", "KilogramsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram)); - yield return new (LinearDensityUnit.KilogramPerMillimeter, "KilogramPerMillimeter", "KilogramsPerMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram)); - yield return new (LinearDensityUnit.MicrogramPerCentimeter, "MicrogramPerCentimeter", "MicrogramsPerCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Microgram)); - yield return new (LinearDensityUnit.MicrogramPerFoot, "MicrogramPerFoot", "MicrogramsPerFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Microgram)); - yield return new (LinearDensityUnit.MicrogramPerMeter, "MicrogramPerMeter", "MicrogramsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram)); - yield return new (LinearDensityUnit.MicrogramPerMillimeter, "MicrogramPerMillimeter", "MicrogramsPerMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Microgram)); - yield return new (LinearDensityUnit.MilligramPerCentimeter, "MilligramPerCentimeter", "MilligramsPerCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Milligram)); - yield return new (LinearDensityUnit.MilligramPerFoot, "MilligramPerFoot", "MilligramsPerFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Milligram)); - yield return new (LinearDensityUnit.MilligramPerMeter, "MilligramPerMeter", "MilligramsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram)); - yield return new (LinearDensityUnit.MilligramPerMillimeter, "MilligramPerMillimeter", "MilligramsPerMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Milligram)); - yield return new (LinearDensityUnit.PoundPerFoot, "PoundPerFoot", "PoundsPerFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound)); - yield return new (LinearDensityUnit.PoundPerInch, "PoundPerInch", "PoundsPerInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound)); + yield return new (LinearDensityUnit.KilogramPerMillimeter, "KilogramPerMillimeter", "KilogramsPerMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram), + new QuantityValue(1, 1000) + ); + yield return new (LinearDensityUnit.MicrogramPerCentimeter, "MicrogramPerCentimeter", "MicrogramsPerCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Microgram), + 10000000 + ); + yield return new (LinearDensityUnit.MicrogramPerFoot, "MicrogramPerFoot", "MicrogramsPerFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Microgram), + 304800000 + ); + yield return new (LinearDensityUnit.MicrogramPerMeter, "MicrogramPerMeter", "MicrogramsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram), + 1000000000 + ); + yield return new (LinearDensityUnit.MicrogramPerMillimeter, "MicrogramPerMillimeter", "MicrogramsPerMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Microgram), + 1000000 + ); + yield return new (LinearDensityUnit.MilligramPerCentimeter, "MilligramPerCentimeter", "MilligramsPerCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Milligram), + 10000 + ); + yield return new (LinearDensityUnit.MilligramPerFoot, "MilligramPerFoot", "MilligramsPerFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Milligram), + 304800 + ); + yield return new (LinearDensityUnit.MilligramPerMeter, "MilligramPerMeter", "MilligramsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram), + 1000000 + ); + yield return new (LinearDensityUnit.MilligramPerMillimeter, "MilligramPerMillimeter", "MilligramsPerMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Milligram), + 1000 + ); + yield return new (LinearDensityUnit.PoundPerFoot, "PoundPerFoot", "PoundsPerFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound), + new QuantityValue(30480000, 45359237) + ); + yield return new (LinearDensityUnit.PoundPerInch, "PoundPerInch", "PoundsPerInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound), + new QuantityValue(2540000, 45359237) + ); } } static LinearDensity() { - Info = LinearDensityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(LinearDensityInfo.CreateDefault); } /// @@ -157,7 +188,7 @@ static LinearDensity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public LinearDensity(double value, LinearDensityUnit unit) + public LinearDensity(QuantityValue value, LinearDensityUnit unit) { _value = value; _unit = unit; @@ -171,7 +202,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -182,7 +213,8 @@ public LinearDensity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -211,10 +243,8 @@ public LinearDensity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public LinearDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -253,147 +283,99 @@ public LinearDensity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerCentimeter => As(LinearDensityUnit.GramPerCentimeter); + public QuantityValue GramsPerCentimeter => this.As(LinearDensityUnit.GramPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerFoot => As(LinearDensityUnit.GramPerFoot); + public QuantityValue GramsPerFoot => this.As(LinearDensityUnit.GramPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerMeter => As(LinearDensityUnit.GramPerMeter); + public QuantityValue GramsPerMeter => this.As(LinearDensityUnit.GramPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerMillimeter => As(LinearDensityUnit.GramPerMillimeter); + public QuantityValue GramsPerMillimeter => this.As(LinearDensityUnit.GramPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerCentimeter => As(LinearDensityUnit.KilogramPerCentimeter); + public QuantityValue KilogramsPerCentimeter => this.As(LinearDensityUnit.KilogramPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerFoot => As(LinearDensityUnit.KilogramPerFoot); + public QuantityValue KilogramsPerFoot => this.As(LinearDensityUnit.KilogramPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerMeter => As(LinearDensityUnit.KilogramPerMeter); + public QuantityValue KilogramsPerMeter => this.As(LinearDensityUnit.KilogramPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerMillimeter => As(LinearDensityUnit.KilogramPerMillimeter); + public QuantityValue KilogramsPerMillimeter => this.As(LinearDensityUnit.KilogramPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerCentimeter => As(LinearDensityUnit.MicrogramPerCentimeter); + public QuantityValue MicrogramsPerCentimeter => this.As(LinearDensityUnit.MicrogramPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerFoot => As(LinearDensityUnit.MicrogramPerFoot); + public QuantityValue MicrogramsPerFoot => this.As(LinearDensityUnit.MicrogramPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerMeter => As(LinearDensityUnit.MicrogramPerMeter); + public QuantityValue MicrogramsPerMeter => this.As(LinearDensityUnit.MicrogramPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerMillimeter => As(LinearDensityUnit.MicrogramPerMillimeter); + public QuantityValue MicrogramsPerMillimeter => this.As(LinearDensityUnit.MicrogramPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerCentimeter => As(LinearDensityUnit.MilligramPerCentimeter); + public QuantityValue MilligramsPerCentimeter => this.As(LinearDensityUnit.MilligramPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerFoot => As(LinearDensityUnit.MilligramPerFoot); + public QuantityValue MilligramsPerFoot => this.As(LinearDensityUnit.MilligramPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerMeter => As(LinearDensityUnit.MilligramPerMeter); + public QuantityValue MilligramsPerMeter => this.As(LinearDensityUnit.MilligramPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerMillimeter => As(LinearDensityUnit.MilligramPerMillimeter); + public QuantityValue MilligramsPerMillimeter => this.As(LinearDensityUnit.MilligramPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerFoot => As(LinearDensityUnit.PoundPerFoot); + public QuantityValue PoundsPerFoot => this.As(LinearDensityUnit.PoundPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerInch => As(LinearDensityUnit.PoundPerInch); + public QuantityValue PoundsPerInch => this.As(LinearDensityUnit.PoundPerInch); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: LinearDensityUnit -> BaseUnit - unitConverter.SetConversionFunction(LinearDensityUnit.GramPerCentimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.GramPerFoot, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.GramPerMeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.GramPerMillimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerCentimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerFoot, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMillimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.MicrogramPerCentimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.MicrogramPerFoot, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.MicrogramPerMeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.MicrogramPerMillimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.MilligramPerCentimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.MilligramPerFoot, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.MilligramPerMeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.MilligramPerMillimeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.PoundPerFoot, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.PoundPerInch, LinearDensityUnit.KilogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.KilogramPerMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> LinearDensityUnit - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerCentimeter, quantity => quantity.ToUnit(LinearDensityUnit.GramPerCentimeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerFoot, quantity => quantity.ToUnit(LinearDensityUnit.GramPerFoot)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.GramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerMillimeter, quantity => quantity.ToUnit(LinearDensityUnit.GramPerMillimeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.KilogramPerCentimeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerCentimeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.KilogramPerFoot, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerFoot)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.KilogramPerMillimeter, quantity => quantity.ToUnit(LinearDensityUnit.KilogramPerMillimeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerCentimeter, quantity => quantity.ToUnit(LinearDensityUnit.MicrogramPerCentimeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerFoot, quantity => quantity.ToUnit(LinearDensityUnit.MicrogramPerFoot)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.MicrogramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerMillimeter, quantity => quantity.ToUnit(LinearDensityUnit.MicrogramPerMillimeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerCentimeter, quantity => quantity.ToUnit(LinearDensityUnit.MilligramPerCentimeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerFoot, quantity => quantity.ToUnit(LinearDensityUnit.MilligramPerFoot)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerMeter, quantity => quantity.ToUnit(LinearDensityUnit.MilligramPerMeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerMillimeter, quantity => quantity.ToUnit(LinearDensityUnit.MilligramPerMillimeter)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.PoundPerFoot, quantity => quantity.ToUnit(LinearDensityUnit.PoundPerFoot)); - unitConverter.SetConversionFunction(LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.PoundPerInch, quantity => quantity.ToUnit(LinearDensityUnit.PoundPerInch)); - } - /// /// Get unit abbreviation string. /// @@ -422,7 +404,7 @@ public static string GetAbbreviation(LinearDensityUnit unit, IFormatProvider? pr /// /// Creates a from . /// - public static LinearDensity FromGramsPerCentimeter(double value) + public static LinearDensity FromGramsPerCentimeter(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.GramPerCentimeter); } @@ -430,7 +412,7 @@ public static LinearDensity FromGramsPerCentimeter(double value) /// /// Creates a from . /// - public static LinearDensity FromGramsPerFoot(double value) + public static LinearDensity FromGramsPerFoot(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.GramPerFoot); } @@ -438,7 +420,7 @@ public static LinearDensity FromGramsPerFoot(double value) /// /// Creates a from . /// - public static LinearDensity FromGramsPerMeter(double value) + public static LinearDensity FromGramsPerMeter(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.GramPerMeter); } @@ -446,7 +428,7 @@ public static LinearDensity FromGramsPerMeter(double value) /// /// Creates a from . /// - public static LinearDensity FromGramsPerMillimeter(double value) + public static LinearDensity FromGramsPerMillimeter(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.GramPerMillimeter); } @@ -454,7 +436,7 @@ public static LinearDensity FromGramsPerMillimeter(double value) /// /// Creates a from . /// - public static LinearDensity FromKilogramsPerCentimeter(double value) + public static LinearDensity FromKilogramsPerCentimeter(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.KilogramPerCentimeter); } @@ -462,7 +444,7 @@ public static LinearDensity FromKilogramsPerCentimeter(double value) /// /// Creates a from . /// - public static LinearDensity FromKilogramsPerFoot(double value) + public static LinearDensity FromKilogramsPerFoot(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.KilogramPerFoot); } @@ -470,7 +452,7 @@ public static LinearDensity FromKilogramsPerFoot(double value) /// /// Creates a from . /// - public static LinearDensity FromKilogramsPerMeter(double value) + public static LinearDensity FromKilogramsPerMeter(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.KilogramPerMeter); } @@ -478,7 +460,7 @@ public static LinearDensity FromKilogramsPerMeter(double value) /// /// Creates a from . /// - public static LinearDensity FromKilogramsPerMillimeter(double value) + public static LinearDensity FromKilogramsPerMillimeter(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.KilogramPerMillimeter); } @@ -486,7 +468,7 @@ public static LinearDensity FromKilogramsPerMillimeter(double value) /// /// Creates a from . /// - public static LinearDensity FromMicrogramsPerCentimeter(double value) + public static LinearDensity FromMicrogramsPerCentimeter(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.MicrogramPerCentimeter); } @@ -494,7 +476,7 @@ public static LinearDensity FromMicrogramsPerCentimeter(double value) /// /// Creates a from . /// - public static LinearDensity FromMicrogramsPerFoot(double value) + public static LinearDensity FromMicrogramsPerFoot(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.MicrogramPerFoot); } @@ -502,7 +484,7 @@ public static LinearDensity FromMicrogramsPerFoot(double value) /// /// Creates a from . /// - public static LinearDensity FromMicrogramsPerMeter(double value) + public static LinearDensity FromMicrogramsPerMeter(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.MicrogramPerMeter); } @@ -510,7 +492,7 @@ public static LinearDensity FromMicrogramsPerMeter(double value) /// /// Creates a from . /// - public static LinearDensity FromMicrogramsPerMillimeter(double value) + public static LinearDensity FromMicrogramsPerMillimeter(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.MicrogramPerMillimeter); } @@ -518,7 +500,7 @@ public static LinearDensity FromMicrogramsPerMillimeter(double value) /// /// Creates a from . /// - public static LinearDensity FromMilligramsPerCentimeter(double value) + public static LinearDensity FromMilligramsPerCentimeter(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.MilligramPerCentimeter); } @@ -526,7 +508,7 @@ public static LinearDensity FromMilligramsPerCentimeter(double value) /// /// Creates a from . /// - public static LinearDensity FromMilligramsPerFoot(double value) + public static LinearDensity FromMilligramsPerFoot(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.MilligramPerFoot); } @@ -534,7 +516,7 @@ public static LinearDensity FromMilligramsPerFoot(double value) /// /// Creates a from . /// - public static LinearDensity FromMilligramsPerMeter(double value) + public static LinearDensity FromMilligramsPerMeter(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.MilligramPerMeter); } @@ -542,7 +524,7 @@ public static LinearDensity FromMilligramsPerMeter(double value) /// /// Creates a from . /// - public static LinearDensity FromMilligramsPerMillimeter(double value) + public static LinearDensity FromMilligramsPerMillimeter(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.MilligramPerMillimeter); } @@ -550,7 +532,7 @@ public static LinearDensity FromMilligramsPerMillimeter(double value) /// /// Creates a from . /// - public static LinearDensity FromPoundsPerFoot(double value) + public static LinearDensity FromPoundsPerFoot(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.PoundPerFoot); } @@ -558,7 +540,7 @@ public static LinearDensity FromPoundsPerFoot(double value) /// /// Creates a from . /// - public static LinearDensity FromPoundsPerInch(double value) + public static LinearDensity FromPoundsPerInch(QuantityValue value) { return new LinearDensity(value, LinearDensityUnit.PoundPerInch); } @@ -569,7 +551,7 @@ public static LinearDensity FromPoundsPerInch(double value) /// Value to convert from. /// Unit to convert from. /// LinearDensity unit value. - public static LinearDensity From(double value, LinearDensityUnit fromUnit) + public static LinearDensity From(QuantityValue value, LinearDensityUnit fromUnit) { return new LinearDensity(value, fromUnit); } @@ -630,10 +612,7 @@ public static LinearDensity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static LinearDensity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -661,11 +640,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out LinearDensity re /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out LinearDensity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -686,7 +661,7 @@ public static LinearDensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -697,7 +672,7 @@ public static LinearDensityUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out LinearDensityUnit unit) { return TryParseUnit(str, null, out unit); @@ -712,7 +687,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out LinearDensit /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out LinearDensityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -731,35 +706,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static LinearDensity operator +(LinearDensity left, LinearDensity right) { - return new LinearDensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new LinearDensity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static LinearDensity operator -(LinearDensity left, LinearDensity right) { - return new LinearDensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new LinearDensity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -793,97 +768,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(LinearDensity left, LinearDensity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(LinearDensity left, LinearDensity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(LinearDensity left, LinearDensity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(LinearDensity left, LinearDensity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(LinearDensity other, LinearDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(LinearDensity left, LinearDensity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(LinearDensity other, LinearDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(LinearDensity left, LinearDensity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(LinearDensity other, LinearDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is LinearDensity otherQuantity)) + if (obj is not LinearDensity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(LinearDensity other, LinearDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(LinearDensity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current LinearDensity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(LinearDensity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is LinearDensity otherQuantity)) throw new ArgumentException("Expected type LinearDensity.", nameof(obj)); + if (obj is not LinearDensity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -895,180 +855,24 @@ public int CompareTo(object? obj) /// public int CompareTo(LinearDensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LinearDensityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this LinearDensity to another LinearDensity with the unit representation . - /// - /// The unit to convert to. - /// A LinearDensity with the specified unit. - public LinearDensity ToUnit(LinearDensityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A LinearDensity with the specified unit. - public LinearDensity ToUnit(LinearDensityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(LinearDensity), Unit, typeof(LinearDensity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (LinearDensity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(LinearDensityUnit unit, [NotNullWhen(true)] out LinearDensity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - LinearDensity? convertedOrNull = (Unit, unit) switch - { - // LinearDensityUnit -> BaseUnit - (LinearDensityUnit.GramPerCentimeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity(_value * 1e-1, LinearDensityUnit.KilogramPerMeter), - (LinearDensityUnit.GramPerFoot, LinearDensityUnit.KilogramPerMeter) => new LinearDensity(_value * ( 1e-3 / 0.3048 ), LinearDensityUnit.KilogramPerMeter), - (LinearDensityUnit.GramPerMeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity(_value * 1e-3, LinearDensityUnit.KilogramPerMeter), - (LinearDensityUnit.GramPerMillimeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity(_value, LinearDensityUnit.KilogramPerMeter), - (LinearDensityUnit.KilogramPerCentimeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value * 1e-1) * 1e3d, LinearDensityUnit.KilogramPerMeter), - (LinearDensityUnit.KilogramPerFoot, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value * ( 1e-3 / 0.3048 )) * 1e3d, LinearDensityUnit.KilogramPerMeter), - (LinearDensityUnit.KilogramPerMillimeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value) * 1e3d, LinearDensityUnit.KilogramPerMeter), - (LinearDensityUnit.MicrogramPerCentimeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value * 1e-1) * 1e-6d, LinearDensityUnit.KilogramPerMeter), - (LinearDensityUnit.MicrogramPerFoot, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value * ( 1e-3 / 0.3048 )) * 1e-6d, LinearDensityUnit.KilogramPerMeter), - (LinearDensityUnit.MicrogramPerMeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value * 1e-3) * 1e-6d, LinearDensityUnit.KilogramPerMeter), - (LinearDensityUnit.MicrogramPerMillimeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value) * 1e-6d, LinearDensityUnit.KilogramPerMeter), - (LinearDensityUnit.MilligramPerCentimeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value * 1e-1) * 1e-3d, LinearDensityUnit.KilogramPerMeter), - (LinearDensityUnit.MilligramPerFoot, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value * ( 1e-3 / 0.3048 )) * 1e-3d, LinearDensityUnit.KilogramPerMeter), - (LinearDensityUnit.MilligramPerMeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value * 1e-3) * 1e-3d, LinearDensityUnit.KilogramPerMeter), - (LinearDensityUnit.MilligramPerMillimeter, LinearDensityUnit.KilogramPerMeter) => new LinearDensity((_value) * 1e-3d, LinearDensityUnit.KilogramPerMeter), - (LinearDensityUnit.PoundPerFoot, LinearDensityUnit.KilogramPerMeter) => new LinearDensity(_value * 0.45359237 / 0.3048, LinearDensityUnit.KilogramPerMeter), - (LinearDensityUnit.PoundPerInch, LinearDensityUnit.KilogramPerMeter) => new LinearDensity(_value * 0.45359237 / 2.54e-2, LinearDensityUnit.KilogramPerMeter), - - // BaseUnit -> LinearDensityUnit - (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerCentimeter) => new LinearDensity(_value / 1e-1, LinearDensityUnit.GramPerCentimeter), - (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerFoot) => new LinearDensity(_value / ( 1e-3 / 0.3048 ), LinearDensityUnit.GramPerFoot), - (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerMeter) => new LinearDensity(_value / 1e-3, LinearDensityUnit.GramPerMeter), - (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.GramPerMillimeter) => new LinearDensity(_value, LinearDensityUnit.GramPerMillimeter), - (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.KilogramPerCentimeter) => new LinearDensity((_value / 1e-1) / 1e3d, LinearDensityUnit.KilogramPerCentimeter), - (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.KilogramPerFoot) => new LinearDensity((_value / ( 1e-3 / 0.3048 )) / 1e3d, LinearDensityUnit.KilogramPerFoot), - (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.KilogramPerMillimeter) => new LinearDensity((_value) / 1e3d, LinearDensityUnit.KilogramPerMillimeter), - (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerCentimeter) => new LinearDensity((_value / 1e-1) / 1e-6d, LinearDensityUnit.MicrogramPerCentimeter), - (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerFoot) => new LinearDensity((_value / ( 1e-3 / 0.3048 )) / 1e-6d, LinearDensityUnit.MicrogramPerFoot), - (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerMeter) => new LinearDensity((_value / 1e-3) / 1e-6d, LinearDensityUnit.MicrogramPerMeter), - (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MicrogramPerMillimeter) => new LinearDensity((_value) / 1e-6d, LinearDensityUnit.MicrogramPerMillimeter), - (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerCentimeter) => new LinearDensity((_value / 1e-1) / 1e-3d, LinearDensityUnit.MilligramPerCentimeter), - (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerFoot) => new LinearDensity((_value / ( 1e-3 / 0.3048 )) / 1e-3d, LinearDensityUnit.MilligramPerFoot), - (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerMeter) => new LinearDensity((_value / 1e-3) / 1e-3d, LinearDensityUnit.MilligramPerMeter), - (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.MilligramPerMillimeter) => new LinearDensity((_value) / 1e-3d, LinearDensityUnit.MilligramPerMillimeter), - (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.PoundPerFoot) => new LinearDensity(_value * 0.3048 / 0.45359237, LinearDensityUnit.PoundPerFoot), - (LinearDensityUnit.KilogramPerMeter, LinearDensityUnit.PoundPerInch) => new LinearDensity(_value * 2.54e-2 / 0.45359237, LinearDensityUnit.PoundPerInch), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public LinearDensity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not LinearDensityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LinearDensityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(LinearDensityUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(LinearDensityUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1083,7 +887,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs index 49c885310f..db34c266d8 100644 --- a/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LinearPowerDensity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// http://en.wikipedia.org/wiki/Linear_density /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct LinearPowerDensity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly LinearPowerDensityUnit? _unit; /// @@ -104,7 +103,7 @@ public static LinearPowerDensityInfo CreateDefault(Func - /// The for is [T^-3][L][M]. + /// The for is T^-3LM. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 1, -3, 0, 0, 0, 0); @@ -119,39 +118,85 @@ public static LinearPowerDensityInfo CreateDefault(FuncAn of representing the default unit mappings for LinearPowerDensity. public static IEnumerable> GetDefaultMappings() { - yield return new (LinearPowerDensityUnit.GigawattPerCentimeter, "GigawattPerCentimeter", "GigawattsPerCentimeter", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.GigawattPerFoot, "GigawattPerFoot", "GigawattsPerFoot", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.GigawattPerInch, "GigawattPerInch", "GigawattsPerInch", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.GigawattPerMeter, "GigawattPerMeter", "GigawattsPerMeter", new BaseUnits(length: LengthUnit.Gigameter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (LinearPowerDensityUnit.GigawattPerMillimeter, "GigawattPerMillimeter", "GigawattsPerMillimeter", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.KilowattPerCentimeter, "KilowattPerCentimeter", "KilowattsPerCentimeter", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.KilowattPerFoot, "KilowattPerFoot", "KilowattsPerFoot", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.KilowattPerInch, "KilowattPerInch", "KilowattsPerInch", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.KilowattPerMeter, "KilowattPerMeter", "KilowattsPerMeter", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (LinearPowerDensityUnit.KilowattPerMillimeter, "KilowattPerMillimeter", "KilowattsPerMillimeter", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.MegawattPerCentimeter, "MegawattPerCentimeter", "MegawattsPerCentimeter", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.MegawattPerFoot, "MegawattPerFoot", "MegawattsPerFoot", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.MegawattPerInch, "MegawattPerInch", "MegawattsPerInch", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.MegawattPerMeter, "MegawattPerMeter", "MegawattsPerMeter", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (LinearPowerDensityUnit.MegawattPerMillimeter, "MegawattPerMillimeter", "MegawattsPerMillimeter", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.MilliwattPerCentimeter, "MilliwattPerCentimeter", "MilliwattsPerCentimeter", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.MilliwattPerFoot, "MilliwattPerFoot", "MilliwattsPerFoot", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.MilliwattPerInch, "MilliwattPerInch", "MilliwattsPerInch", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.MilliwattPerMeter, "MilliwattPerMeter", "MilliwattsPerMeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (LinearPowerDensityUnit.MilliwattPerMillimeter, "MilliwattPerMillimeter", "MilliwattsPerMillimeter", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.WattPerCentimeter, "WattPerCentimeter", "WattsPerCentimeter", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.WattPerFoot, "WattPerFoot", "WattsPerFoot", BaseUnits.Undefined); - yield return new (LinearPowerDensityUnit.WattPerInch, "WattPerInch", "WattsPerInch", BaseUnits.Undefined); + yield return new (LinearPowerDensityUnit.GigawattPerCentimeter, "GigawattPerCentimeter", "GigawattsPerCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 100000000000) + ); + yield return new (LinearPowerDensityUnit.GigawattPerFoot, "GigawattPerFoot", "GigawattsPerFoot", BaseUnits.Undefined, + new QuantityValue(381, 1250000000000) + ); + yield return new (LinearPowerDensityUnit.GigawattPerInch, "GigawattPerInch", "GigawattsPerInch", BaseUnits.Undefined, + new QuantityValue(127, 5000000000000) + ); + yield return new (LinearPowerDensityUnit.GigawattPerMeter, "GigawattPerMeter", "GigawattsPerMeter", new BaseUnits(length: LengthUnit.Gigameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000000) + ); + yield return new (LinearPowerDensityUnit.GigawattPerMillimeter, "GigawattPerMillimeter", "GigawattsPerMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000) + ); + yield return new (LinearPowerDensityUnit.KilowattPerCentimeter, "KilowattPerCentimeter", "KilowattsPerCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 100000) + ); + yield return new (LinearPowerDensityUnit.KilowattPerFoot, "KilowattPerFoot", "KilowattsPerFoot", BaseUnits.Undefined, + new QuantityValue(381, 1250000) + ); + yield return new (LinearPowerDensityUnit.KilowattPerInch, "KilowattPerInch", "KilowattsPerInch", BaseUnits.Undefined, + new QuantityValue(127, 5000000) + ); + yield return new (LinearPowerDensityUnit.KilowattPerMeter, "KilowattPerMeter", "KilowattsPerMeter", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000) + ); + yield return new (LinearPowerDensityUnit.KilowattPerMillimeter, "KilowattPerMillimeter", "KilowattsPerMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 1000000) + ); + yield return new (LinearPowerDensityUnit.MegawattPerCentimeter, "MegawattPerCentimeter", "MegawattsPerCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 100000000) + ); + yield return new (LinearPowerDensityUnit.MegawattPerFoot, "MegawattPerFoot", "MegawattsPerFoot", BaseUnits.Undefined, + new QuantityValue(381, 1250000000) + ); + yield return new (LinearPowerDensityUnit.MegawattPerInch, "MegawattPerInch", "MegawattsPerInch", BaseUnits.Undefined, + new QuantityValue(127, 5000000000) + ); + yield return new (LinearPowerDensityUnit.MegawattPerMeter, "MegawattPerMeter", "MegawattsPerMeter", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (LinearPowerDensityUnit.MegawattPerMillimeter, "MegawattPerMillimeter", "MegawattsPerMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 1000000000) + ); + yield return new (LinearPowerDensityUnit.MilliwattPerCentimeter, "MilliwattPerCentimeter", "MilliwattsPerCentimeter", BaseUnits.Undefined, + 10 + ); + yield return new (LinearPowerDensityUnit.MilliwattPerFoot, "MilliwattPerFoot", "MilliwattsPerFoot", BaseUnits.Undefined, + new QuantityValue(1524, 5) + ); + yield return new (LinearPowerDensityUnit.MilliwattPerInch, "MilliwattPerInch", "MilliwattsPerInch", BaseUnits.Undefined, + new QuantityValue(127, 5) + ); + yield return new (LinearPowerDensityUnit.MilliwattPerMeter, "MilliwattPerMeter", "MilliwattsPerMeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + 1000 + ); + yield return new (LinearPowerDensityUnit.MilliwattPerMillimeter, "MilliwattPerMillimeter", "MilliwattsPerMillimeter", BaseUnits.Undefined, + 1 + ); + yield return new (LinearPowerDensityUnit.WattPerCentimeter, "WattPerCentimeter", "WattsPerCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 100) + ); + yield return new (LinearPowerDensityUnit.WattPerFoot, "WattPerFoot", "WattsPerFoot", BaseUnits.Undefined, + new QuantityValue(381, 1250) + ); + yield return new (LinearPowerDensityUnit.WattPerInch, "WattPerInch", "WattsPerInch", BaseUnits.Undefined, + new QuantityValue(127, 5000) + ); yield return new (LinearPowerDensityUnit.WattPerMeter, "WattPerMeter", "WattsPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (LinearPowerDensityUnit.WattPerMillimeter, "WattPerMillimeter", "WattsPerMillimeter", BaseUnits.Undefined); + yield return new (LinearPowerDensityUnit.WattPerMillimeter, "WattPerMillimeter", "WattsPerMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); } } static LinearPowerDensity() { - Info = LinearPowerDensityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(LinearPowerDensityInfo.CreateDefault); } /// @@ -159,7 +204,7 @@ static LinearPowerDensity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public LinearPowerDensity(double value, LinearPowerDensityUnit unit) + public LinearPowerDensity(QuantityValue value, LinearPowerDensityUnit unit) { _value = value; _unit = unit; @@ -173,7 +218,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -184,7 +229,8 @@ public LinearPowerDensity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -213,10 +259,8 @@ public LinearPowerDensity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public LinearPowerDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -255,196 +299,134 @@ public LinearPowerDensity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigawattsPerCentimeter => As(LinearPowerDensityUnit.GigawattPerCentimeter); + public QuantityValue GigawattsPerCentimeter => this.As(LinearPowerDensityUnit.GigawattPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigawattsPerFoot => As(LinearPowerDensityUnit.GigawattPerFoot); + public QuantityValue GigawattsPerFoot => this.As(LinearPowerDensityUnit.GigawattPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigawattsPerInch => As(LinearPowerDensityUnit.GigawattPerInch); + public QuantityValue GigawattsPerInch => this.As(LinearPowerDensityUnit.GigawattPerInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigawattsPerMeter => As(LinearPowerDensityUnit.GigawattPerMeter); + public QuantityValue GigawattsPerMeter => this.As(LinearPowerDensityUnit.GigawattPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigawattsPerMillimeter => As(LinearPowerDensityUnit.GigawattPerMillimeter); + public QuantityValue GigawattsPerMillimeter => this.As(LinearPowerDensityUnit.GigawattPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattsPerCentimeter => As(LinearPowerDensityUnit.KilowattPerCentimeter); + public QuantityValue KilowattsPerCentimeter => this.As(LinearPowerDensityUnit.KilowattPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattsPerFoot => As(LinearPowerDensityUnit.KilowattPerFoot); + public QuantityValue KilowattsPerFoot => this.As(LinearPowerDensityUnit.KilowattPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattsPerInch => As(LinearPowerDensityUnit.KilowattPerInch); + public QuantityValue KilowattsPerInch => this.As(LinearPowerDensityUnit.KilowattPerInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattsPerMeter => As(LinearPowerDensityUnit.KilowattPerMeter); + public QuantityValue KilowattsPerMeter => this.As(LinearPowerDensityUnit.KilowattPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattsPerMillimeter => As(LinearPowerDensityUnit.KilowattPerMillimeter); + public QuantityValue KilowattsPerMillimeter => this.As(LinearPowerDensityUnit.KilowattPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattsPerCentimeter => As(LinearPowerDensityUnit.MegawattPerCentimeter); + public QuantityValue MegawattsPerCentimeter => this.As(LinearPowerDensityUnit.MegawattPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattsPerFoot => As(LinearPowerDensityUnit.MegawattPerFoot); + public QuantityValue MegawattsPerFoot => this.As(LinearPowerDensityUnit.MegawattPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattsPerInch => As(LinearPowerDensityUnit.MegawattPerInch); + public QuantityValue MegawattsPerInch => this.As(LinearPowerDensityUnit.MegawattPerInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattsPerMeter => As(LinearPowerDensityUnit.MegawattPerMeter); + public QuantityValue MegawattsPerMeter => this.As(LinearPowerDensityUnit.MegawattPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattsPerMillimeter => As(LinearPowerDensityUnit.MegawattPerMillimeter); + public QuantityValue MegawattsPerMillimeter => this.As(LinearPowerDensityUnit.MegawattPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliwattsPerCentimeter => As(LinearPowerDensityUnit.MilliwattPerCentimeter); + public QuantityValue MilliwattsPerCentimeter => this.As(LinearPowerDensityUnit.MilliwattPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliwattsPerFoot => As(LinearPowerDensityUnit.MilliwattPerFoot); + public QuantityValue MilliwattsPerFoot => this.As(LinearPowerDensityUnit.MilliwattPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliwattsPerInch => As(LinearPowerDensityUnit.MilliwattPerInch); + public QuantityValue MilliwattsPerInch => this.As(LinearPowerDensityUnit.MilliwattPerInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliwattsPerMeter => As(LinearPowerDensityUnit.MilliwattPerMeter); + public QuantityValue MilliwattsPerMeter => this.As(LinearPowerDensityUnit.MilliwattPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliwattsPerMillimeter => As(LinearPowerDensityUnit.MilliwattPerMillimeter); + public QuantityValue MilliwattsPerMillimeter => this.As(LinearPowerDensityUnit.MilliwattPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattsPerCentimeter => As(LinearPowerDensityUnit.WattPerCentimeter); + public QuantityValue WattsPerCentimeter => this.As(LinearPowerDensityUnit.WattPerCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattsPerFoot => As(LinearPowerDensityUnit.WattPerFoot); + public QuantityValue WattsPerFoot => this.As(LinearPowerDensityUnit.WattPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattsPerInch => As(LinearPowerDensityUnit.WattPerInch); + public QuantityValue WattsPerInch => this.As(LinearPowerDensityUnit.WattPerInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattsPerMeter => As(LinearPowerDensityUnit.WattPerMeter); + public QuantityValue WattsPerMeter => this.As(LinearPowerDensityUnit.WattPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattsPerMillimeter => As(LinearPowerDensityUnit.WattPerMillimeter); + public QuantityValue WattsPerMillimeter => this.As(LinearPowerDensityUnit.WattPerMillimeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: LinearPowerDensityUnit -> BaseUnit - unitConverter.SetConversionFunction(LinearPowerDensityUnit.GigawattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.GigawattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.GigawattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.GigawattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.GigawattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.KilowattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.KilowattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.KilowattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.KilowattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.KilowattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MegawattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MegawattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MegawattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MegawattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MegawattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MilliwattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MilliwattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MilliwattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MilliwattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.MilliwattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerCentimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerFoot, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerInch, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMillimeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> LinearPowerDensityUnit - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerCentimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.GigawattPerCentimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerFoot, quantity => quantity.ToUnit(LinearPowerDensityUnit.GigawattPerFoot)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerInch, quantity => quantity.ToUnit(LinearPowerDensityUnit.GigawattPerInch)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.GigawattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerMillimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.GigawattPerMillimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerCentimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.KilowattPerCentimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerFoot, quantity => quantity.ToUnit(LinearPowerDensityUnit.KilowattPerFoot)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerInch, quantity => quantity.ToUnit(LinearPowerDensityUnit.KilowattPerInch)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.KilowattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerMillimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.KilowattPerMillimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerCentimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MegawattPerCentimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerFoot, quantity => quantity.ToUnit(LinearPowerDensityUnit.MegawattPerFoot)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerInch, quantity => quantity.ToUnit(LinearPowerDensityUnit.MegawattPerInch)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MegawattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerMillimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MegawattPerMillimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerCentimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MilliwattPerCentimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerFoot, quantity => quantity.ToUnit(LinearPowerDensityUnit.MilliwattPerFoot)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerInch, quantity => quantity.ToUnit(LinearPowerDensityUnit.MilliwattPerInch)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerMeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MilliwattPerMeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerMillimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.MilliwattPerMillimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerCentimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerCentimeter)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerFoot, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerFoot)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerInch, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerInch)); - unitConverter.SetConversionFunction(LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerMillimeter, quantity => quantity.ToUnit(LinearPowerDensityUnit.WattPerMillimeter)); - } - /// /// Get unit abbreviation string. /// @@ -473,7 +455,7 @@ public static string GetAbbreviation(LinearPowerDensityUnit unit, IFormatProvide /// /// Creates a from . /// - public static LinearPowerDensity FromGigawattsPerCentimeter(double value) + public static LinearPowerDensity FromGigawattsPerCentimeter(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerCentimeter); } @@ -481,7 +463,7 @@ public static LinearPowerDensity FromGigawattsPerCentimeter(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromGigawattsPerFoot(double value) + public static LinearPowerDensity FromGigawattsPerFoot(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerFoot); } @@ -489,7 +471,7 @@ public static LinearPowerDensity FromGigawattsPerFoot(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromGigawattsPerInch(double value) + public static LinearPowerDensity FromGigawattsPerInch(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerInch); } @@ -497,7 +479,7 @@ public static LinearPowerDensity FromGigawattsPerInch(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromGigawattsPerMeter(double value) + public static LinearPowerDensity FromGigawattsPerMeter(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerMeter); } @@ -505,7 +487,7 @@ public static LinearPowerDensity FromGigawattsPerMeter(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromGigawattsPerMillimeter(double value) + public static LinearPowerDensity FromGigawattsPerMillimeter(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.GigawattPerMillimeter); } @@ -513,7 +495,7 @@ public static LinearPowerDensity FromGigawattsPerMillimeter(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromKilowattsPerCentimeter(double value) + public static LinearPowerDensity FromKilowattsPerCentimeter(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerCentimeter); } @@ -521,7 +503,7 @@ public static LinearPowerDensity FromKilowattsPerCentimeter(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromKilowattsPerFoot(double value) + public static LinearPowerDensity FromKilowattsPerFoot(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerFoot); } @@ -529,7 +511,7 @@ public static LinearPowerDensity FromKilowattsPerFoot(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromKilowattsPerInch(double value) + public static LinearPowerDensity FromKilowattsPerInch(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerInch); } @@ -537,7 +519,7 @@ public static LinearPowerDensity FromKilowattsPerInch(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromKilowattsPerMeter(double value) + public static LinearPowerDensity FromKilowattsPerMeter(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerMeter); } @@ -545,7 +527,7 @@ public static LinearPowerDensity FromKilowattsPerMeter(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromKilowattsPerMillimeter(double value) + public static LinearPowerDensity FromKilowattsPerMillimeter(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.KilowattPerMillimeter); } @@ -553,7 +535,7 @@ public static LinearPowerDensity FromKilowattsPerMillimeter(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromMegawattsPerCentimeter(double value) + public static LinearPowerDensity FromMegawattsPerCentimeter(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerCentimeter); } @@ -561,7 +543,7 @@ public static LinearPowerDensity FromMegawattsPerCentimeter(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromMegawattsPerFoot(double value) + public static LinearPowerDensity FromMegawattsPerFoot(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerFoot); } @@ -569,7 +551,7 @@ public static LinearPowerDensity FromMegawattsPerFoot(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromMegawattsPerInch(double value) + public static LinearPowerDensity FromMegawattsPerInch(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerInch); } @@ -577,7 +559,7 @@ public static LinearPowerDensity FromMegawattsPerInch(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromMegawattsPerMeter(double value) + public static LinearPowerDensity FromMegawattsPerMeter(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerMeter); } @@ -585,7 +567,7 @@ public static LinearPowerDensity FromMegawattsPerMeter(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromMegawattsPerMillimeter(double value) + public static LinearPowerDensity FromMegawattsPerMillimeter(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.MegawattPerMillimeter); } @@ -593,7 +575,7 @@ public static LinearPowerDensity FromMegawattsPerMillimeter(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromMilliwattsPerCentimeter(double value) + public static LinearPowerDensity FromMilliwattsPerCentimeter(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerCentimeter); } @@ -601,7 +583,7 @@ public static LinearPowerDensity FromMilliwattsPerCentimeter(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromMilliwattsPerFoot(double value) + public static LinearPowerDensity FromMilliwattsPerFoot(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerFoot); } @@ -609,7 +591,7 @@ public static LinearPowerDensity FromMilliwattsPerFoot(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromMilliwattsPerInch(double value) + public static LinearPowerDensity FromMilliwattsPerInch(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerInch); } @@ -617,7 +599,7 @@ public static LinearPowerDensity FromMilliwattsPerInch(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromMilliwattsPerMeter(double value) + public static LinearPowerDensity FromMilliwattsPerMeter(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerMeter); } @@ -625,7 +607,7 @@ public static LinearPowerDensity FromMilliwattsPerMeter(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromMilliwattsPerMillimeter(double value) + public static LinearPowerDensity FromMilliwattsPerMillimeter(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.MilliwattPerMillimeter); } @@ -633,7 +615,7 @@ public static LinearPowerDensity FromMilliwattsPerMillimeter(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromWattsPerCentimeter(double value) + public static LinearPowerDensity FromWattsPerCentimeter(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerCentimeter); } @@ -641,7 +623,7 @@ public static LinearPowerDensity FromWattsPerCentimeter(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromWattsPerFoot(double value) + public static LinearPowerDensity FromWattsPerFoot(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerFoot); } @@ -649,7 +631,7 @@ public static LinearPowerDensity FromWattsPerFoot(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromWattsPerInch(double value) + public static LinearPowerDensity FromWattsPerInch(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerInch); } @@ -657,7 +639,7 @@ public static LinearPowerDensity FromWattsPerInch(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromWattsPerMeter(double value) + public static LinearPowerDensity FromWattsPerMeter(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerMeter); } @@ -665,7 +647,7 @@ public static LinearPowerDensity FromWattsPerMeter(double value) /// /// Creates a from . /// - public static LinearPowerDensity FromWattsPerMillimeter(double value) + public static LinearPowerDensity FromWattsPerMillimeter(QuantityValue value) { return new LinearPowerDensity(value, LinearPowerDensityUnit.WattPerMillimeter); } @@ -676,7 +658,7 @@ public static LinearPowerDensity FromWattsPerMillimeter(double value) /// Value to convert from. /// Unit to convert from. /// LinearPowerDensity unit value. - public static LinearPowerDensity From(double value, LinearPowerDensityUnit fromUnit) + public static LinearPowerDensity From(QuantityValue value, LinearPowerDensityUnit fromUnit) { return new LinearPowerDensity(value, fromUnit); } @@ -737,10 +719,7 @@ public static LinearPowerDensity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static LinearPowerDensity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -768,11 +747,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out LinearPowerDensi /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out LinearPowerDensity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -793,7 +768,7 @@ public static LinearPowerDensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -804,7 +779,7 @@ public static LinearPowerDensityUnit ParseUnit(string str, IFormatProvider? prov return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out LinearPowerDensityUnit unit) { return TryParseUnit(str, null, out unit); @@ -819,7 +794,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out LinearPowerD /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out LinearPowerDensityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -838,35 +813,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static LinearPowerDensity operator +(LinearPowerDensity left, LinearPowerDensity right) { - return new LinearPowerDensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new LinearPowerDensity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static LinearPowerDensity operator -(LinearPowerDensity left, LinearPowerDensity right) { - return new LinearPowerDensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new LinearPowerDensity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -878,97 +853,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(LinearPowerDensity left, LinearPowerDensity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(LinearPowerDensity left, LinearPowerDensity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(LinearPowerDensity left, LinearPowerDensity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(LinearPowerDensity left, LinearPowerDensity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(LinearPowerDensity other, LinearPowerDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(LinearPowerDensity left, LinearPowerDensity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(LinearPowerDensity other, LinearPowerDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(LinearPowerDensity left, LinearPowerDensity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(LinearPowerDensity other, LinearPowerDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is LinearPowerDensity otherQuantity)) + if (obj is not LinearPowerDensity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(LinearPowerDensity other, LinearPowerDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(LinearPowerDensity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current LinearPowerDensity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(LinearPowerDensity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is LinearPowerDensity otherQuantity)) throw new ArgumentException("Expected type LinearPowerDensity.", nameof(obj)); + if (obj is not LinearPowerDensity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -980,194 +940,24 @@ public int CompareTo(object? obj) /// public int CompareTo(LinearPowerDensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LinearPowerDensityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this LinearPowerDensity to another LinearPowerDensity with the unit representation . - /// - /// The unit to convert to. - /// A LinearPowerDensity with the specified unit. - public LinearPowerDensity ToUnit(LinearPowerDensityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A LinearPowerDensity with the specified unit. - public LinearPowerDensity ToUnit(LinearPowerDensityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(LinearPowerDensity), Unit, typeof(LinearPowerDensity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (LinearPowerDensity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(LinearPowerDensityUnit unit, [NotNullWhen(true)] out LinearPowerDensity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - LinearPowerDensity? convertedOrNull = (Unit, unit) switch - { - // LinearPowerDensityUnit -> BaseUnit - (LinearPowerDensityUnit.GigawattPerCentimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 1e2) * 1e9d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.GigawattPerFoot, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value / 0.3048) * 1e9d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.GigawattPerInch, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value / 2.54e-2) * 1e9d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.GigawattPerMeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value) * 1e9d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.GigawattPerMillimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 1e3) * 1e9d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.KilowattPerCentimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 1e2) * 1e3d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.KilowattPerFoot, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value / 0.3048) * 1e3d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.KilowattPerInch, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value / 2.54e-2) * 1e3d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.KilowattPerMeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value) * 1e3d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.KilowattPerMillimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 1e3) * 1e3d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.MegawattPerCentimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 1e2) * 1e6d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.MegawattPerFoot, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value / 0.3048) * 1e6d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.MegawattPerInch, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value / 2.54e-2) * 1e6d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.MegawattPerMeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value) * 1e6d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.MegawattPerMillimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 1e3) * 1e6d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.MilliwattPerCentimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 1e2) * 1e-3d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.MilliwattPerFoot, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value / 0.3048) * 1e-3d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.MilliwattPerInch, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value / 2.54e-2) * 1e-3d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.MilliwattPerMeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value) * 1e-3d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.MilliwattPerMillimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity((_value * 1e3) * 1e-3d, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.WattPerCentimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity(_value * 1e2, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.WattPerFoot, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity(_value / 0.3048, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.WattPerInch, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity(_value / 2.54e-2, LinearPowerDensityUnit.WattPerMeter), - (LinearPowerDensityUnit.WattPerMillimeter, LinearPowerDensityUnit.WattPerMeter) => new LinearPowerDensity(_value * 1e3, LinearPowerDensityUnit.WattPerMeter), - - // BaseUnit -> LinearPowerDensityUnit - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerCentimeter) => new LinearPowerDensity((_value / 1e2) / 1e9d, LinearPowerDensityUnit.GigawattPerCentimeter), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerFoot) => new LinearPowerDensity((_value * 0.3048) / 1e9d, LinearPowerDensityUnit.GigawattPerFoot), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerInch) => new LinearPowerDensity((_value * 2.54e-2) / 1e9d, LinearPowerDensityUnit.GigawattPerInch), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerMeter) => new LinearPowerDensity((_value) / 1e9d, LinearPowerDensityUnit.GigawattPerMeter), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.GigawattPerMillimeter) => new LinearPowerDensity((_value / 1e3) / 1e9d, LinearPowerDensityUnit.GigawattPerMillimeter), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerCentimeter) => new LinearPowerDensity((_value / 1e2) / 1e3d, LinearPowerDensityUnit.KilowattPerCentimeter), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerFoot) => new LinearPowerDensity((_value * 0.3048) / 1e3d, LinearPowerDensityUnit.KilowattPerFoot), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerInch) => new LinearPowerDensity((_value * 2.54e-2) / 1e3d, LinearPowerDensityUnit.KilowattPerInch), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerMeter) => new LinearPowerDensity((_value) / 1e3d, LinearPowerDensityUnit.KilowattPerMeter), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.KilowattPerMillimeter) => new LinearPowerDensity((_value / 1e3) / 1e3d, LinearPowerDensityUnit.KilowattPerMillimeter), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerCentimeter) => new LinearPowerDensity((_value / 1e2) / 1e6d, LinearPowerDensityUnit.MegawattPerCentimeter), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerFoot) => new LinearPowerDensity((_value * 0.3048) / 1e6d, LinearPowerDensityUnit.MegawattPerFoot), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerInch) => new LinearPowerDensity((_value * 2.54e-2) / 1e6d, LinearPowerDensityUnit.MegawattPerInch), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerMeter) => new LinearPowerDensity((_value) / 1e6d, LinearPowerDensityUnit.MegawattPerMeter), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MegawattPerMillimeter) => new LinearPowerDensity((_value / 1e3) / 1e6d, LinearPowerDensityUnit.MegawattPerMillimeter), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerCentimeter) => new LinearPowerDensity((_value / 1e2) / 1e-3d, LinearPowerDensityUnit.MilliwattPerCentimeter), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerFoot) => new LinearPowerDensity((_value * 0.3048) / 1e-3d, LinearPowerDensityUnit.MilliwattPerFoot), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerInch) => new LinearPowerDensity((_value * 2.54e-2) / 1e-3d, LinearPowerDensityUnit.MilliwattPerInch), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerMeter) => new LinearPowerDensity((_value) / 1e-3d, LinearPowerDensityUnit.MilliwattPerMeter), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.MilliwattPerMillimeter) => new LinearPowerDensity((_value / 1e3) / 1e-3d, LinearPowerDensityUnit.MilliwattPerMillimeter), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerCentimeter) => new LinearPowerDensity(_value / 1e2, LinearPowerDensityUnit.WattPerCentimeter), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerFoot) => new LinearPowerDensity(_value * 0.3048, LinearPowerDensityUnit.WattPerFoot), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerInch) => new LinearPowerDensity(_value * 2.54e-2, LinearPowerDensityUnit.WattPerInch), - (LinearPowerDensityUnit.WattPerMeter, LinearPowerDensityUnit.WattPerMillimeter) => new LinearPowerDensity(_value / 1e3, LinearPowerDensityUnit.WattPerMillimeter), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public LinearPowerDensity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not LinearPowerDensityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LinearPowerDensityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(LinearPowerDensityUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(LinearPowerDensityUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1182,7 +972,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Luminance.g.cs b/UnitsNet/GeneratedCode/Quantities/Luminance.g.cs index d7abbb4fa8..fc2e70081f 100644 --- a/UnitsNet/GeneratedCode/Quantities/Luminance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Luminance.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Luminance /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Luminance : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -56,13 +55,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly LuminanceUnit? _unit; /// @@ -107,7 +106,7 @@ public static LuminanceInfo CreateDefault(Func - /// The for is [L^-2][J]. + /// The for is L^-2J. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 0, 0, 0, 0, 0, 1); @@ -122,24 +121,40 @@ public static LuminanceInfo CreateDefault(FuncAn of representing the default unit mappings for Luminance. public static IEnumerable> GetDefaultMappings() { - yield return new (LuminanceUnit.CandelaPerSquareFoot, "CandelaPerSquareFoot", "CandelasPerSquareFoot", BaseUnits.Undefined); - yield return new (LuminanceUnit.CandelaPerSquareInch, "CandelaPerSquareInch", "CandelasPerSquareInch", BaseUnits.Undefined); + yield return new (LuminanceUnit.CandelaPerSquareFoot, "CandelaPerSquareFoot", "CandelasPerSquareFoot", BaseUnits.Undefined, + new QuantityValue(145161, 1562500) + ); + yield return new (LuminanceUnit.CandelaPerSquareInch, "CandelaPerSquareInch", "CandelasPerSquareInch", BaseUnits.Undefined, + new QuantityValue(16129, 25000000) + ); yield return new (LuminanceUnit.CandelaPerSquareMeter, "CandelaPerSquareMeter", "CandelasPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, luminousIntensity: LuminousIntensityUnit.Candela)); - yield return new (LuminanceUnit.CenticandelaPerSquareMeter, "CenticandelaPerSquareMeter", "CenticandelasPerSquareMeter", new BaseUnits(length: LengthUnit.Decameter, luminousIntensity: LuminousIntensityUnit.Candela)); - yield return new (LuminanceUnit.DecicandelaPerSquareMeter, "DecicandelaPerSquareMeter", "DecicandelasPerSquareMeter", BaseUnits.Undefined); - yield return new (LuminanceUnit.KilocandelaPerSquareMeter, "KilocandelaPerSquareMeter", "KilocandelasPerSquareMeter", BaseUnits.Undefined); - yield return new (LuminanceUnit.MicrocandelaPerSquareMeter, "MicrocandelaPerSquareMeter", "MicrocandelasPerSquareMeter", new BaseUnits(length: LengthUnit.Kilometer, luminousIntensity: LuminousIntensityUnit.Candela)); - yield return new (LuminanceUnit.MillicandelaPerSquareMeter, "MillicandelaPerSquareMeter", "MillicandelasPerSquareMeter", BaseUnits.Undefined); - yield return new (LuminanceUnit.NanocandelaPerSquareMeter, "NanocandelaPerSquareMeter", "NanocandelasPerSquareMeter", BaseUnits.Undefined); - yield return new (LuminanceUnit.Nit, "Nit", "Nits", BaseUnits.Undefined); + yield return new (LuminanceUnit.CenticandelaPerSquareMeter, "CenticandelaPerSquareMeter", "CenticandelasPerSquareMeter", new BaseUnits(length: LengthUnit.Decameter, luminousIntensity: LuminousIntensityUnit.Candela), + 100 + ); + yield return new (LuminanceUnit.DecicandelaPerSquareMeter, "DecicandelaPerSquareMeter", "DecicandelasPerSquareMeter", BaseUnits.Undefined, + 10 + ); + yield return new (LuminanceUnit.KilocandelaPerSquareMeter, "KilocandelaPerSquareMeter", "KilocandelasPerSquareMeter", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (LuminanceUnit.MicrocandelaPerSquareMeter, "MicrocandelaPerSquareMeter", "MicrocandelasPerSquareMeter", new BaseUnits(length: LengthUnit.Kilometer, luminousIntensity: LuminousIntensityUnit.Candela), + 1000000 + ); + yield return new (LuminanceUnit.MillicandelaPerSquareMeter, "MillicandelaPerSquareMeter", "MillicandelasPerSquareMeter", BaseUnits.Undefined, + 1000 + ); + yield return new (LuminanceUnit.NanocandelaPerSquareMeter, "NanocandelaPerSquareMeter", "NanocandelasPerSquareMeter", BaseUnits.Undefined, + 1000000000 + ); + yield return new (LuminanceUnit.Nit, "Nit", "Nits", BaseUnits.Undefined, + 1 + ); } } static Luminance() { - Info = LuminanceInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(LuminanceInfo.CreateDefault); } /// @@ -147,7 +162,7 @@ static Luminance() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Luminance(double value, LuminanceUnit unit) + public Luminance(QuantityValue value, LuminanceUnit unit) { _value = value; _unit = unit; @@ -161,7 +176,7 @@ public Luminance(double value, LuminanceUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Luminance(double value, UnitSystem unitSystem) + public Luminance(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -172,7 +187,8 @@ public Luminance(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -201,10 +217,8 @@ public Luminance(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public LuminanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -243,91 +257,59 @@ public Luminance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CandelasPerSquareFoot => As(LuminanceUnit.CandelaPerSquareFoot); + public QuantityValue CandelasPerSquareFoot => this.As(LuminanceUnit.CandelaPerSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CandelasPerSquareInch => As(LuminanceUnit.CandelaPerSquareInch); + public QuantityValue CandelasPerSquareInch => this.As(LuminanceUnit.CandelaPerSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CandelasPerSquareMeter => As(LuminanceUnit.CandelaPerSquareMeter); + public QuantityValue CandelasPerSquareMeter => this.As(LuminanceUnit.CandelaPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CenticandelasPerSquareMeter => As(LuminanceUnit.CenticandelaPerSquareMeter); + public QuantityValue CenticandelasPerSquareMeter => this.As(LuminanceUnit.CenticandelaPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecicandelasPerSquareMeter => As(LuminanceUnit.DecicandelaPerSquareMeter); + public QuantityValue DecicandelasPerSquareMeter => this.As(LuminanceUnit.DecicandelaPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilocandelasPerSquareMeter => As(LuminanceUnit.KilocandelaPerSquareMeter); + public QuantityValue KilocandelasPerSquareMeter => this.As(LuminanceUnit.KilocandelaPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrocandelasPerSquareMeter => As(LuminanceUnit.MicrocandelaPerSquareMeter); + public QuantityValue MicrocandelasPerSquareMeter => this.As(LuminanceUnit.MicrocandelaPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillicandelasPerSquareMeter => As(LuminanceUnit.MillicandelaPerSquareMeter); + public QuantityValue MillicandelasPerSquareMeter => this.As(LuminanceUnit.MillicandelaPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanocandelasPerSquareMeter => As(LuminanceUnit.NanocandelaPerSquareMeter); + public QuantityValue NanocandelasPerSquareMeter => this.As(LuminanceUnit.NanocandelaPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nits => As(LuminanceUnit.Nit); + public QuantityValue Nits => this.As(LuminanceUnit.Nit); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: LuminanceUnit -> BaseUnit - unitConverter.SetConversionFunction(LuminanceUnit.CandelaPerSquareFoot, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); - unitConverter.SetConversionFunction(LuminanceUnit.CandelaPerSquareInch, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); - unitConverter.SetConversionFunction(LuminanceUnit.CenticandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); - unitConverter.SetConversionFunction(LuminanceUnit.DecicandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); - unitConverter.SetConversionFunction(LuminanceUnit.KilocandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); - unitConverter.SetConversionFunction(LuminanceUnit.MicrocandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); - unitConverter.SetConversionFunction(LuminanceUnit.MillicandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); - unitConverter.SetConversionFunction(LuminanceUnit.NanocandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); - unitConverter.SetConversionFunction(LuminanceUnit.Nit, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> LuminanceUnit - unitConverter.SetConversionFunction(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareFoot, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareFoot)); - unitConverter.SetConversionFunction(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareInch, quantity => quantity.ToUnit(LuminanceUnit.CandelaPerSquareInch)); - unitConverter.SetConversionFunction(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.CenticandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.CenticandelaPerSquareMeter)); - unitConverter.SetConversionFunction(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.DecicandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.DecicandelaPerSquareMeter)); - unitConverter.SetConversionFunction(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.KilocandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.KilocandelaPerSquareMeter)); - unitConverter.SetConversionFunction(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.MicrocandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.MicrocandelaPerSquareMeter)); - unitConverter.SetConversionFunction(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.MillicandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.MillicandelaPerSquareMeter)); - unitConverter.SetConversionFunction(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.NanocandelaPerSquareMeter, quantity => quantity.ToUnit(LuminanceUnit.NanocandelaPerSquareMeter)); - unitConverter.SetConversionFunction(LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.Nit, quantity => quantity.ToUnit(LuminanceUnit.Nit)); - } - /// /// Get unit abbreviation string. /// @@ -356,7 +338,7 @@ public static string GetAbbreviation(LuminanceUnit unit, IFormatProvider? provid /// /// Creates a from . /// - public static Luminance FromCandelasPerSquareFoot(double value) + public static Luminance FromCandelasPerSquareFoot(QuantityValue value) { return new Luminance(value, LuminanceUnit.CandelaPerSquareFoot); } @@ -364,7 +346,7 @@ public static Luminance FromCandelasPerSquareFoot(double value) /// /// Creates a from . /// - public static Luminance FromCandelasPerSquareInch(double value) + public static Luminance FromCandelasPerSquareInch(QuantityValue value) { return new Luminance(value, LuminanceUnit.CandelaPerSquareInch); } @@ -372,7 +354,7 @@ public static Luminance FromCandelasPerSquareInch(double value) /// /// Creates a from . /// - public static Luminance FromCandelasPerSquareMeter(double value) + public static Luminance FromCandelasPerSquareMeter(QuantityValue value) { return new Luminance(value, LuminanceUnit.CandelaPerSquareMeter); } @@ -380,7 +362,7 @@ public static Luminance FromCandelasPerSquareMeter(double value) /// /// Creates a from . /// - public static Luminance FromCenticandelasPerSquareMeter(double value) + public static Luminance FromCenticandelasPerSquareMeter(QuantityValue value) { return new Luminance(value, LuminanceUnit.CenticandelaPerSquareMeter); } @@ -388,7 +370,7 @@ public static Luminance FromCenticandelasPerSquareMeter(double value) /// /// Creates a from . /// - public static Luminance FromDecicandelasPerSquareMeter(double value) + public static Luminance FromDecicandelasPerSquareMeter(QuantityValue value) { return new Luminance(value, LuminanceUnit.DecicandelaPerSquareMeter); } @@ -396,7 +378,7 @@ public static Luminance FromDecicandelasPerSquareMeter(double value) /// /// Creates a from . /// - public static Luminance FromKilocandelasPerSquareMeter(double value) + public static Luminance FromKilocandelasPerSquareMeter(QuantityValue value) { return new Luminance(value, LuminanceUnit.KilocandelaPerSquareMeter); } @@ -404,7 +386,7 @@ public static Luminance FromKilocandelasPerSquareMeter(double value) /// /// Creates a from . /// - public static Luminance FromMicrocandelasPerSquareMeter(double value) + public static Luminance FromMicrocandelasPerSquareMeter(QuantityValue value) { return new Luminance(value, LuminanceUnit.MicrocandelaPerSquareMeter); } @@ -412,7 +394,7 @@ public static Luminance FromMicrocandelasPerSquareMeter(double value) /// /// Creates a from . /// - public static Luminance FromMillicandelasPerSquareMeter(double value) + public static Luminance FromMillicandelasPerSquareMeter(QuantityValue value) { return new Luminance(value, LuminanceUnit.MillicandelaPerSquareMeter); } @@ -420,7 +402,7 @@ public static Luminance FromMillicandelasPerSquareMeter(double value) /// /// Creates a from . /// - public static Luminance FromNanocandelasPerSquareMeter(double value) + public static Luminance FromNanocandelasPerSquareMeter(QuantityValue value) { return new Luminance(value, LuminanceUnit.NanocandelaPerSquareMeter); } @@ -428,7 +410,7 @@ public static Luminance FromNanocandelasPerSquareMeter(double value) /// /// Creates a from . /// - public static Luminance FromNits(double value) + public static Luminance FromNits(QuantityValue value) { return new Luminance(value, LuminanceUnit.Nit); } @@ -439,7 +421,7 @@ public static Luminance FromNits(double value) /// Value to convert from. /// Unit to convert from. /// Luminance unit value. - public static Luminance From(double value, LuminanceUnit fromUnit) + public static Luminance From(QuantityValue value, LuminanceUnit fromUnit) { return new Luminance(value, fromUnit); } @@ -500,10 +482,7 @@ public static Luminance Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Luminance Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -531,11 +510,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Luminance result /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Luminance result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -556,7 +531,7 @@ public static LuminanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -567,7 +542,7 @@ public static LuminanceUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out LuminanceUnit unit) { return TryParseUnit(str, null, out unit); @@ -582,7 +557,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out LuminanceUni /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out LuminanceUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -601,35 +576,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Luminance operator +(Luminance left, Luminance right) { - return new Luminance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Luminance(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Luminance operator -(Luminance left, Luminance right) { - return new Luminance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Luminance(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static Luminance operator *(double left, Luminance right) + public static Luminance operator *(QuantityValue left, Luminance right) { return new Luminance(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Luminance operator *(Luminance left, double right) + public static Luminance operator *(Luminance left, QuantityValue right) { return new Luminance(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Luminance operator /(Luminance left, double right) + public static Luminance operator /(Luminance left, QuantityValue right) { return new Luminance(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Luminance left, Luminance right) + public static QuantityValue operator /(Luminance left, Luminance right) { return left.CandelasPerSquareMeter / right.CandelasPerSquareMeter; } @@ -651,97 +626,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Luminance left, Luminance right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Luminance left, Luminance right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Luminance left, Luminance right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Luminance left, Luminance right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Luminance other, Luminance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Luminance left, Luminance right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Luminance other, Luminance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Luminance left, Luminance right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Luminance other, Luminance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Luminance otherQuantity)) + if (obj is not Luminance otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Luminance other, Luminance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Luminance other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Luminance. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Luminance), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Luminance otherQuantity)) throw new ArgumentException("Expected type Luminance.", nameof(obj)); + if (obj is not Luminance otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -753,164 +713,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Luminance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LuminanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Luminance to another Luminance with the unit representation . - /// - /// The unit to convert to. - /// A Luminance with the specified unit. - public Luminance ToUnit(LuminanceUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Luminance with the specified unit. - public Luminance ToUnit(LuminanceUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Luminance), Unit, typeof(Luminance), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Luminance)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(LuminanceUnit unit, [NotNullWhen(true)] out Luminance? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Luminance? convertedOrNull = (Unit, unit) switch - { - // LuminanceUnit -> BaseUnit - (LuminanceUnit.CandelaPerSquareFoot, LuminanceUnit.CandelaPerSquareMeter) => new Luminance(_value / 9.290304e-2, LuminanceUnit.CandelaPerSquareMeter), - (LuminanceUnit.CandelaPerSquareInch, LuminanceUnit.CandelaPerSquareMeter) => new Luminance(_value / 0.00064516, LuminanceUnit.CandelaPerSquareMeter), - (LuminanceUnit.CenticandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter) => new Luminance((_value) * 1e-2d, LuminanceUnit.CandelaPerSquareMeter), - (LuminanceUnit.DecicandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter) => new Luminance((_value) * 1e-1d, LuminanceUnit.CandelaPerSquareMeter), - (LuminanceUnit.KilocandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter) => new Luminance((_value) * 1e3d, LuminanceUnit.CandelaPerSquareMeter), - (LuminanceUnit.MicrocandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter) => new Luminance((_value) * 1e-6d, LuminanceUnit.CandelaPerSquareMeter), - (LuminanceUnit.MillicandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter) => new Luminance((_value) * 1e-3d, LuminanceUnit.CandelaPerSquareMeter), - (LuminanceUnit.NanocandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareMeter) => new Luminance((_value) * 1e-9d, LuminanceUnit.CandelaPerSquareMeter), - (LuminanceUnit.Nit, LuminanceUnit.CandelaPerSquareMeter) => new Luminance(_value, LuminanceUnit.CandelaPerSquareMeter), - - // BaseUnit -> LuminanceUnit - (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareFoot) => new Luminance(_value * 9.290304e-2, LuminanceUnit.CandelaPerSquareFoot), - (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.CandelaPerSquareInch) => new Luminance(_value * 0.00064516, LuminanceUnit.CandelaPerSquareInch), - (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.CenticandelaPerSquareMeter) => new Luminance((_value) / 1e-2d, LuminanceUnit.CenticandelaPerSquareMeter), - (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.DecicandelaPerSquareMeter) => new Luminance((_value) / 1e-1d, LuminanceUnit.DecicandelaPerSquareMeter), - (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.KilocandelaPerSquareMeter) => new Luminance((_value) / 1e3d, LuminanceUnit.KilocandelaPerSquareMeter), - (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.MicrocandelaPerSquareMeter) => new Luminance((_value) / 1e-6d, LuminanceUnit.MicrocandelaPerSquareMeter), - (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.MillicandelaPerSquareMeter) => new Luminance((_value) / 1e-3d, LuminanceUnit.MillicandelaPerSquareMeter), - (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.NanocandelaPerSquareMeter) => new Luminance((_value) / 1e-9d, LuminanceUnit.NanocandelaPerSquareMeter), - (LuminanceUnit.CandelaPerSquareMeter, LuminanceUnit.Nit) => new Luminance(_value, LuminanceUnit.Nit), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Luminance ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not LuminanceUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminanceUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is LuminanceUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminanceUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(LuminanceUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(LuminanceUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -925,7 +745,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs b/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs index fc52c77bf5..59e3ea4d4d 100644 --- a/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Luminosity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Luminosity /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Luminosity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly LuminosityUnit? _unit; /// @@ -104,7 +103,7 @@ public static LuminosityInfo CreateDefault(Func - /// The for is [T^-3][L^2][M]. + /// The for is T^-3L^2M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); @@ -119,28 +118,52 @@ public static LuminosityInfo CreateDefault(FuncAn of representing the default unit mappings for Luminosity. public static IEnumerable> GetDefaultMappings() { - yield return new (LuminosityUnit.Decawatt, "Decawatt", "Decawatts", BaseUnits.Undefined); - yield return new (LuminosityUnit.Deciwatt, "Deciwatt", "Deciwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Hectogram, time: DurationUnit.Second)); - yield return new (LuminosityUnit.Femtowatt, "Femtowatt", "Femtowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Picogram, time: DurationUnit.Second)); - yield return new (LuminosityUnit.Gigawatt, "Gigawatt", "Gigawatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond)); - yield return new (LuminosityUnit.Kilowatt, "Kilowatt", "Kilowatts", BaseUnits.Undefined); - yield return new (LuminosityUnit.Megawatt, "Megawatt", "Megawatts", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (LuminosityUnit.Microwatt, "Microwatt", "Microwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second)); - yield return new (LuminosityUnit.Milliwatt, "Milliwatt", "Milliwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second)); - yield return new (LuminosityUnit.Nanowatt, "Nanowatt", "Nanowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second)); - yield return new (LuminosityUnit.Petawatt, "Petawatt", "Petawatts", BaseUnits.Undefined); - yield return new (LuminosityUnit.Picowatt, "Picowatt", "Picowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second)); - yield return new (LuminosityUnit.SolarLuminosity, "SolarLuminosity", "SolarLuminosities", BaseUnits.Undefined); - yield return new (LuminosityUnit.Terawatt, "Terawatt", "Terawatts", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); + yield return new (LuminosityUnit.Decawatt, "Decawatt", "Decawatts", BaseUnits.Undefined, + new QuantityValue(1, 10) + ); + yield return new (LuminosityUnit.Deciwatt, "Deciwatt", "Deciwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Hectogram, time: DurationUnit.Second), + 10 + ); + yield return new (LuminosityUnit.Femtowatt, "Femtowatt", "Femtowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Picogram, time: DurationUnit.Second), + 1000000000000000 + ); + yield return new (LuminosityUnit.Gigawatt, "Gigawatt", "Gigawatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond), + new QuantityValue(1, 1000000000) + ); + yield return new (LuminosityUnit.Kilowatt, "Kilowatt", "Kilowatts", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (LuminosityUnit.Megawatt, "Megawatt", "Megawatts", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (LuminosityUnit.Microwatt, "Microwatt", "Microwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second), + 1000000 + ); + yield return new (LuminosityUnit.Milliwatt, "Milliwatt", "Milliwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second), + 1000 + ); + yield return new (LuminosityUnit.Nanowatt, "Nanowatt", "Nanowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second), + 1000000000 + ); + yield return new (LuminosityUnit.Petawatt, "Petawatt", "Petawatts", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000000) + ); + yield return new (LuminosityUnit.Picowatt, "Picowatt", "Picowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second), + 1000000000000 + ); + yield return new (LuminosityUnit.SolarLuminosity, "SolarLuminosity", "SolarLuminosities", BaseUnits.Undefined, + new QuantityValue(1, new BigInteger(3828) * QuantityValue.PowerOfTen(23)) + ); + yield return new (LuminosityUnit.Terawatt, "Terawatt", "Terawatts", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000000000) + ); yield return new (LuminosityUnit.Watt, "Watt", "Watts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); } } static Luminosity() { - Info = LuminosityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(LuminosityInfo.CreateDefault); } /// @@ -148,7 +171,7 @@ static Luminosity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Luminosity(double value, LuminosityUnit unit) + public Luminosity(QuantityValue value, LuminosityUnit unit) { _value = value; _unit = unit; @@ -162,7 +185,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -173,7 +196,8 @@ public Luminosity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -202,10 +226,8 @@ public Luminosity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public LuminosityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -244,119 +266,79 @@ public Luminosity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Decawatts => As(LuminosityUnit.Decawatt); + public QuantityValue Decawatts => this.As(LuminosityUnit.Decawatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Deciwatts => As(LuminosityUnit.Deciwatt); + public QuantityValue Deciwatts => this.As(LuminosityUnit.Deciwatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Femtowatts => As(LuminosityUnit.Femtowatt); + public QuantityValue Femtowatts => this.As(LuminosityUnit.Femtowatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigawatts => As(LuminosityUnit.Gigawatt); + public QuantityValue Gigawatts => this.As(LuminosityUnit.Gigawatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilowatts => As(LuminosityUnit.Kilowatt); + public QuantityValue Kilowatts => this.As(LuminosityUnit.Kilowatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megawatts => As(LuminosityUnit.Megawatt); + public QuantityValue Megawatts => this.As(LuminosityUnit.Megawatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microwatts => As(LuminosityUnit.Microwatt); + public QuantityValue Microwatts => this.As(LuminosityUnit.Microwatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Milliwatts => As(LuminosityUnit.Milliwatt); + public QuantityValue Milliwatts => this.As(LuminosityUnit.Milliwatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanowatts => As(LuminosityUnit.Nanowatt); + public QuantityValue Nanowatts => this.As(LuminosityUnit.Nanowatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Petawatts => As(LuminosityUnit.Petawatt); + public QuantityValue Petawatts => this.As(LuminosityUnit.Petawatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Picowatts => As(LuminosityUnit.Picowatt); + public QuantityValue Picowatts => this.As(LuminosityUnit.Picowatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SolarLuminosities => As(LuminosityUnit.SolarLuminosity); + public QuantityValue SolarLuminosities => this.As(LuminosityUnit.SolarLuminosity); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Terawatts => As(LuminosityUnit.Terawatt); + public QuantityValue Terawatts => this.As(LuminosityUnit.Terawatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Watts => As(LuminosityUnit.Watt); + public QuantityValue Watts => this.As(LuminosityUnit.Watt); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: LuminosityUnit -> BaseUnit - unitConverter.SetConversionFunction(LuminosityUnit.Decawatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); - unitConverter.SetConversionFunction(LuminosityUnit.Deciwatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); - unitConverter.SetConversionFunction(LuminosityUnit.Femtowatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); - unitConverter.SetConversionFunction(LuminosityUnit.Gigawatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); - unitConverter.SetConversionFunction(LuminosityUnit.Kilowatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); - unitConverter.SetConversionFunction(LuminosityUnit.Megawatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); - unitConverter.SetConversionFunction(LuminosityUnit.Microwatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); - unitConverter.SetConversionFunction(LuminosityUnit.Milliwatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); - unitConverter.SetConversionFunction(LuminosityUnit.Nanowatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); - unitConverter.SetConversionFunction(LuminosityUnit.Petawatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); - unitConverter.SetConversionFunction(LuminosityUnit.Picowatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); - unitConverter.SetConversionFunction(LuminosityUnit.SolarLuminosity, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); - unitConverter.SetConversionFunction(LuminosityUnit.Terawatt, LuminosityUnit.Watt, quantity => quantity.ToUnit(LuminosityUnit.Watt)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Watt, quantity => quantity); - - // Register in unit converter: BaseUnit -> LuminosityUnit - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Decawatt, quantity => quantity.ToUnit(LuminosityUnit.Decawatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Deciwatt, quantity => quantity.ToUnit(LuminosityUnit.Deciwatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Femtowatt, quantity => quantity.ToUnit(LuminosityUnit.Femtowatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Gigawatt, quantity => quantity.ToUnit(LuminosityUnit.Gigawatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Kilowatt, quantity => quantity.ToUnit(LuminosityUnit.Kilowatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Megawatt, quantity => quantity.ToUnit(LuminosityUnit.Megawatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Microwatt, quantity => quantity.ToUnit(LuminosityUnit.Microwatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Milliwatt, quantity => quantity.ToUnit(LuminosityUnit.Milliwatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Nanowatt, quantity => quantity.ToUnit(LuminosityUnit.Nanowatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Petawatt, quantity => quantity.ToUnit(LuminosityUnit.Petawatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Picowatt, quantity => quantity.ToUnit(LuminosityUnit.Picowatt)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.SolarLuminosity, quantity => quantity.ToUnit(LuminosityUnit.SolarLuminosity)); - unitConverter.SetConversionFunction(LuminosityUnit.Watt, LuminosityUnit.Terawatt, quantity => quantity.ToUnit(LuminosityUnit.Terawatt)); - } - /// /// Get unit abbreviation string. /// @@ -385,7 +367,7 @@ public static string GetAbbreviation(LuminosityUnit unit, IFormatProvider? provi /// /// Creates a from . /// - public static Luminosity FromDecawatts(double value) + public static Luminosity FromDecawatts(QuantityValue value) { return new Luminosity(value, LuminosityUnit.Decawatt); } @@ -393,7 +375,7 @@ public static Luminosity FromDecawatts(double value) /// /// Creates a from . /// - public static Luminosity FromDeciwatts(double value) + public static Luminosity FromDeciwatts(QuantityValue value) { return new Luminosity(value, LuminosityUnit.Deciwatt); } @@ -401,7 +383,7 @@ public static Luminosity FromDeciwatts(double value) /// /// Creates a from . /// - public static Luminosity FromFemtowatts(double value) + public static Luminosity FromFemtowatts(QuantityValue value) { return new Luminosity(value, LuminosityUnit.Femtowatt); } @@ -409,7 +391,7 @@ public static Luminosity FromFemtowatts(double value) /// /// Creates a from . /// - public static Luminosity FromGigawatts(double value) + public static Luminosity FromGigawatts(QuantityValue value) { return new Luminosity(value, LuminosityUnit.Gigawatt); } @@ -417,7 +399,7 @@ public static Luminosity FromGigawatts(double value) /// /// Creates a from . /// - public static Luminosity FromKilowatts(double value) + public static Luminosity FromKilowatts(QuantityValue value) { return new Luminosity(value, LuminosityUnit.Kilowatt); } @@ -425,7 +407,7 @@ public static Luminosity FromKilowatts(double value) /// /// Creates a from . /// - public static Luminosity FromMegawatts(double value) + public static Luminosity FromMegawatts(QuantityValue value) { return new Luminosity(value, LuminosityUnit.Megawatt); } @@ -433,7 +415,7 @@ public static Luminosity FromMegawatts(double value) /// /// Creates a from . /// - public static Luminosity FromMicrowatts(double value) + public static Luminosity FromMicrowatts(QuantityValue value) { return new Luminosity(value, LuminosityUnit.Microwatt); } @@ -441,7 +423,7 @@ public static Luminosity FromMicrowatts(double value) /// /// Creates a from . /// - public static Luminosity FromMilliwatts(double value) + public static Luminosity FromMilliwatts(QuantityValue value) { return new Luminosity(value, LuminosityUnit.Milliwatt); } @@ -449,7 +431,7 @@ public static Luminosity FromMilliwatts(double value) /// /// Creates a from . /// - public static Luminosity FromNanowatts(double value) + public static Luminosity FromNanowatts(QuantityValue value) { return new Luminosity(value, LuminosityUnit.Nanowatt); } @@ -457,7 +439,7 @@ public static Luminosity FromNanowatts(double value) /// /// Creates a from . /// - public static Luminosity FromPetawatts(double value) + public static Luminosity FromPetawatts(QuantityValue value) { return new Luminosity(value, LuminosityUnit.Petawatt); } @@ -465,7 +447,7 @@ public static Luminosity FromPetawatts(double value) /// /// Creates a from . /// - public static Luminosity FromPicowatts(double value) + public static Luminosity FromPicowatts(QuantityValue value) { return new Luminosity(value, LuminosityUnit.Picowatt); } @@ -473,7 +455,7 @@ public static Luminosity FromPicowatts(double value) /// /// Creates a from . /// - public static Luminosity FromSolarLuminosities(double value) + public static Luminosity FromSolarLuminosities(QuantityValue value) { return new Luminosity(value, LuminosityUnit.SolarLuminosity); } @@ -481,7 +463,7 @@ public static Luminosity FromSolarLuminosities(double value) /// /// Creates a from . /// - public static Luminosity FromTerawatts(double value) + public static Luminosity FromTerawatts(QuantityValue value) { return new Luminosity(value, LuminosityUnit.Terawatt); } @@ -489,7 +471,7 @@ public static Luminosity FromTerawatts(double value) /// /// Creates a from . /// - public static Luminosity FromWatts(double value) + public static Luminosity FromWatts(QuantityValue value) { return new Luminosity(value, LuminosityUnit.Watt); } @@ -500,7 +482,7 @@ public static Luminosity FromWatts(double value) /// Value to convert from. /// Unit to convert from. /// Luminosity unit value. - public static Luminosity From(double value, LuminosityUnit fromUnit) + public static Luminosity From(QuantityValue value, LuminosityUnit fromUnit) { return new Luminosity(value, fromUnit); } @@ -561,10 +543,7 @@ public static Luminosity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Luminosity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -592,11 +571,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Luminosity resul /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Luminosity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -617,7 +592,7 @@ public static LuminosityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -628,7 +603,7 @@ public static LuminosityUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out LuminosityUnit unit) { return TryParseUnit(str, null, out unit); @@ -643,7 +618,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out LuminosityUn /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out LuminosityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -662,35 +637,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Luminosity operator +(Luminosity left, Luminosity right) { - return new Luminosity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Luminosity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Luminosity operator -(Luminosity left, Luminosity right) { - return new Luminosity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Luminosity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -702,97 +677,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Luminosity left, Luminosity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Luminosity left, Luminosity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Luminosity left, Luminosity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Luminosity left, Luminosity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Luminosity other, Luminosity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Luminosity left, Luminosity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Luminosity other, Luminosity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Luminosity left, Luminosity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Luminosity other, Luminosity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Luminosity otherQuantity)) + if (obj is not Luminosity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Luminosity other, Luminosity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Luminosity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Luminosity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Luminosity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Luminosity otherQuantity)) throw new ArgumentException("Expected type Luminosity.", nameof(obj)); + if (obj is not Luminosity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -804,172 +764,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Luminosity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LuminosityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Luminosity to another Luminosity with the unit representation . - /// - /// The unit to convert to. - /// A Luminosity with the specified unit. - public Luminosity ToUnit(LuminosityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Luminosity with the specified unit. - public Luminosity ToUnit(LuminosityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Luminosity), Unit, typeof(Luminosity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Luminosity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(LuminosityUnit unit, [NotNullWhen(true)] out Luminosity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Luminosity? convertedOrNull = (Unit, unit) switch - { - // LuminosityUnit -> BaseUnit - (LuminosityUnit.Decawatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e1d, LuminosityUnit.Watt), - (LuminosityUnit.Deciwatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e-1d, LuminosityUnit.Watt), - (LuminosityUnit.Femtowatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e-15d, LuminosityUnit.Watt), - (LuminosityUnit.Gigawatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e9d, LuminosityUnit.Watt), - (LuminosityUnit.Kilowatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e3d, LuminosityUnit.Watt), - (LuminosityUnit.Megawatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e6d, LuminosityUnit.Watt), - (LuminosityUnit.Microwatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e-6d, LuminosityUnit.Watt), - (LuminosityUnit.Milliwatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e-3d, LuminosityUnit.Watt), - (LuminosityUnit.Nanowatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e-9d, LuminosityUnit.Watt), - (LuminosityUnit.Petawatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e15d, LuminosityUnit.Watt), - (LuminosityUnit.Picowatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e-12d, LuminosityUnit.Watt), - (LuminosityUnit.SolarLuminosity, LuminosityUnit.Watt) => new Luminosity(_value * 3.828e26, LuminosityUnit.Watt), - (LuminosityUnit.Terawatt, LuminosityUnit.Watt) => new Luminosity((_value) * 1e12d, LuminosityUnit.Watt), - - // BaseUnit -> LuminosityUnit - (LuminosityUnit.Watt, LuminosityUnit.Decawatt) => new Luminosity((_value) / 1e1d, LuminosityUnit.Decawatt), - (LuminosityUnit.Watt, LuminosityUnit.Deciwatt) => new Luminosity((_value) / 1e-1d, LuminosityUnit.Deciwatt), - (LuminosityUnit.Watt, LuminosityUnit.Femtowatt) => new Luminosity((_value) / 1e-15d, LuminosityUnit.Femtowatt), - (LuminosityUnit.Watt, LuminosityUnit.Gigawatt) => new Luminosity((_value) / 1e9d, LuminosityUnit.Gigawatt), - (LuminosityUnit.Watt, LuminosityUnit.Kilowatt) => new Luminosity((_value) / 1e3d, LuminosityUnit.Kilowatt), - (LuminosityUnit.Watt, LuminosityUnit.Megawatt) => new Luminosity((_value) / 1e6d, LuminosityUnit.Megawatt), - (LuminosityUnit.Watt, LuminosityUnit.Microwatt) => new Luminosity((_value) / 1e-6d, LuminosityUnit.Microwatt), - (LuminosityUnit.Watt, LuminosityUnit.Milliwatt) => new Luminosity((_value) / 1e-3d, LuminosityUnit.Milliwatt), - (LuminosityUnit.Watt, LuminosityUnit.Nanowatt) => new Luminosity((_value) / 1e-9d, LuminosityUnit.Nanowatt), - (LuminosityUnit.Watt, LuminosityUnit.Petawatt) => new Luminosity((_value) / 1e15d, LuminosityUnit.Petawatt), - (LuminosityUnit.Watt, LuminosityUnit.Picowatt) => new Luminosity((_value) / 1e-12d, LuminosityUnit.Picowatt), - (LuminosityUnit.Watt, LuminosityUnit.SolarLuminosity) => new Luminosity(_value / 3.828e26, LuminosityUnit.SolarLuminosity), - (LuminosityUnit.Watt, LuminosityUnit.Terawatt) => new Luminosity((_value) / 1e12d, LuminosityUnit.Terawatt), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Luminosity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not LuminosityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminosityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(LuminosityUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(LuminosityUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -984,7 +796,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs index 397551e87c..c4e093a2a8 100644 --- a/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LuminousFlux.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Luminous_flux /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct LuminousFlux : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -57,13 +56,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly LuminousFluxUnit? _unit; /// @@ -108,7 +107,7 @@ public static LuminousFluxInfo CreateDefault(Func - /// The for is [J]. + /// The for is J. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); @@ -129,9 +128,7 @@ public static IEnumerable> GetDefaultMappings() static LuminousFlux() { - Info = LuminousFluxInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(LuminousFluxInfo.CreateDefault); } /// @@ -139,7 +136,7 @@ static LuminousFlux() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public LuminousFlux(double value, LuminousFluxUnit unit) + public LuminousFlux(QuantityValue value, LuminousFluxUnit unit) { _value = value; _unit = unit; @@ -153,7 +150,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -164,7 +161,8 @@ public LuminousFlux(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -193,10 +191,8 @@ public LuminousFlux(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public LuminousFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -235,28 +231,14 @@ public LuminousFlux(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Lumens => As(LuminousFluxUnit.Lumen); + public QuantityValue Lumens => this.As(LuminousFluxUnit.Lumen); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: LuminousFluxUnit -> BaseUnit - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(LuminousFluxUnit.Lumen, LuminousFluxUnit.Lumen, quantity => quantity); - - // Register in unit converter: BaseUnit -> LuminousFluxUnit - } - /// /// Get unit abbreviation string. /// @@ -285,7 +267,7 @@ public static string GetAbbreviation(LuminousFluxUnit unit, IFormatProvider? pro /// /// Creates a from . /// - public static LuminousFlux FromLumens(double value) + public static LuminousFlux FromLumens(QuantityValue value) { return new LuminousFlux(value, LuminousFluxUnit.Lumen); } @@ -296,7 +278,7 @@ public static LuminousFlux FromLumens(double value) /// Value to convert from. /// Unit to convert from. /// LuminousFlux unit value. - public static LuminousFlux From(double value, LuminousFluxUnit fromUnit) + public static LuminousFlux From(QuantityValue value, LuminousFluxUnit fromUnit) { return new LuminousFlux(value, fromUnit); } @@ -357,10 +339,7 @@ public static LuminousFlux Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static LuminousFlux Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -388,11 +367,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out LuminousFlux res /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out LuminousFlux result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -413,7 +388,7 @@ public static LuminousFluxUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -424,7 +399,7 @@ public static LuminousFluxUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out LuminousFluxUnit unit) { return TryParseUnit(str, null, out unit); @@ -439,7 +414,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out LuminousFlux /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out LuminousFluxUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -458,35 +433,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static LuminousFlux operator +(LuminousFlux left, LuminousFlux right) { - return new LuminousFlux(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new LuminousFlux(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static LuminousFlux operator -(LuminousFlux left, LuminousFlux right) { - return new LuminousFlux(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new LuminousFlux(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -514,97 +489,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(LuminousFlux left, LuminousFlux right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(LuminousFlux left, LuminousFlux right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(LuminousFlux left, LuminousFlux right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(LuminousFlux left, LuminousFlux right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(LuminousFlux other, LuminousFlux tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(LuminousFlux left, LuminousFlux right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(LuminousFlux other, LuminousFlux tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(LuminousFlux left, LuminousFlux right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(LuminousFlux other, LuminousFlux tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is LuminousFlux otherQuantity)) + if (obj is not LuminousFlux otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(LuminousFlux other, LuminousFlux tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(LuminousFlux other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current LuminousFlux. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(LuminousFlux), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is LuminousFlux otherQuantity)) throw new ArgumentException("Expected type LuminousFlux.", nameof(obj)); + if (obj is not LuminousFlux otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -616,146 +576,24 @@ public int CompareTo(object? obj) /// public int CompareTo(LuminousFlux other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LuminousFluxUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this LuminousFlux to another LuminousFlux with the unit representation . - /// - /// The unit to convert to. - /// A LuminousFlux with the specified unit. - public LuminousFlux ToUnit(LuminousFluxUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A LuminousFlux with the specified unit. - public LuminousFlux ToUnit(LuminousFluxUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(LuminousFlux), Unit, typeof(LuminousFlux), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (LuminousFlux)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(LuminousFluxUnit unit, [NotNullWhen(true)] out LuminousFlux? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - LuminousFlux? convertedOrNull = (Unit, unit) switch - { - // LuminousFluxUnit -> BaseUnit + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> LuminousFluxUnit - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public LuminousFlux ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not LuminousFluxUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousFluxUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is LuminousFluxUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousFluxUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(LuminousFluxUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(LuminousFluxUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -770,7 +608,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs index e6115ea875..3d6f25cbcc 100644 --- a/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/LuminousIntensity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Luminous_intensity /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct LuminousIntensity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -57,13 +56,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly LuminousIntensityUnit? _unit; /// @@ -108,7 +107,7 @@ public static LuminousIntensityInfo CreateDefault(Func - /// The for is [J]. + /// The for is J. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 0, 0, 0, 0, 1); @@ -129,9 +128,7 @@ public static IEnumerable> GetDefaultMappi static LuminousIntensity() { - Info = LuminousIntensityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(LuminousIntensityInfo.CreateDefault); } /// @@ -139,7 +136,7 @@ static LuminousIntensity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public LuminousIntensity(double value, LuminousIntensityUnit unit) + public LuminousIntensity(QuantityValue value, LuminousIntensityUnit unit) { _value = value; _unit = unit; @@ -153,7 +150,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -164,7 +161,8 @@ public LuminousIntensity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -193,10 +191,8 @@ public LuminousIntensity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public LuminousIntensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -235,28 +231,14 @@ public LuminousIntensity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Candela => As(LuminousIntensityUnit.Candela); + public QuantityValue Candela => this.As(LuminousIntensityUnit.Candela); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: LuminousIntensityUnit -> BaseUnit - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(LuminousIntensityUnit.Candela, LuminousIntensityUnit.Candela, quantity => quantity); - - // Register in unit converter: BaseUnit -> LuminousIntensityUnit - } - /// /// Get unit abbreviation string. /// @@ -285,7 +267,7 @@ public static string GetAbbreviation(LuminousIntensityUnit unit, IFormatProvider /// /// Creates a from . /// - public static LuminousIntensity FromCandela(double value) + public static LuminousIntensity FromCandela(QuantityValue value) { return new LuminousIntensity(value, LuminousIntensityUnit.Candela); } @@ -296,7 +278,7 @@ public static LuminousIntensity FromCandela(double value) /// Value to convert from. /// Unit to convert from. /// LuminousIntensity unit value. - public static LuminousIntensity From(double value, LuminousIntensityUnit fromUnit) + public static LuminousIntensity From(QuantityValue value, LuminousIntensityUnit fromUnit) { return new LuminousIntensity(value, fromUnit); } @@ -357,10 +339,7 @@ public static LuminousIntensity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static LuminousIntensity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -388,11 +367,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out LuminousIntensit /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out LuminousIntensity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -413,7 +388,7 @@ public static LuminousIntensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -424,7 +399,7 @@ public static LuminousIntensityUnit ParseUnit(string str, IFormatProvider? provi return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out LuminousIntensityUnit unit) { return TryParseUnit(str, null, out unit); @@ -439,7 +414,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out LuminousInte /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out LuminousIntensityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -458,35 +433,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static LuminousIntensity operator +(LuminousIntensity left, LuminousIntensity right) { - return new LuminousIntensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new LuminousIntensity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static LuminousIntensity operator -(LuminousIntensity left, LuminousIntensity right) { - return new LuminousIntensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new LuminousIntensity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -514,97 +489,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(LuminousIntensity left, LuminousIntensity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(LuminousIntensity left, LuminousIntensity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(LuminousIntensity left, LuminousIntensity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(LuminousIntensity left, LuminousIntensity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(LuminousIntensity other, LuminousIntensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(LuminousIntensity left, LuminousIntensity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(LuminousIntensity other, LuminousIntensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(LuminousIntensity left, LuminousIntensity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(LuminousIntensity other, LuminousIntensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is LuminousIntensity otherQuantity)) + if (obj is not LuminousIntensity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(LuminousIntensity other, LuminousIntensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(LuminousIntensity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current LuminousIntensity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(LuminousIntensity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is LuminousIntensity otherQuantity)) throw new ArgumentException("Expected type LuminousIntensity.", nameof(obj)); + if (obj is not LuminousIntensity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -616,146 +576,24 @@ public int CompareTo(object? obj) /// public int CompareTo(LuminousIntensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(LuminousIntensityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this LuminousIntensity to another LuminousIntensity with the unit representation . - /// - /// The unit to convert to. - /// A LuminousIntensity with the specified unit. - public LuminousIntensity ToUnit(LuminousIntensityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A LuminousIntensity with the specified unit. - public LuminousIntensity ToUnit(LuminousIntensityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(LuminousIntensity), Unit, typeof(LuminousIntensity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (LuminousIntensity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(LuminousIntensityUnit unit, [NotNullWhen(true)] out LuminousIntensity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - LuminousIntensity? convertedOrNull = (Unit, unit) switch - { - // LuminousIntensityUnit -> BaseUnit + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> LuminousIntensityUnit - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public LuminousIntensity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not LuminousIntensityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousIntensityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is LuminousIntensityUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(LuminousIntensityUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(LuminousIntensityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(LuminousIntensityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -770,7 +608,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs index 1d96df089a..3c5b0229c9 100644 --- a/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MagneticField.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Magnetic_field /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct MagneticField : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly MagneticFieldUnit? _unit; /// @@ -104,7 +103,7 @@ public static MagneticFieldInfo CreateDefault(Func - /// The for is [T^-2][M][I^-1]. + /// The for is T^-2MI^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, -2, -1, 0, 0, 0); @@ -119,20 +118,28 @@ public static MagneticFieldInfo CreateDefault(FuncAn of representing the default unit mappings for MagneticField. public static IEnumerable> GetDefaultMappings() { - yield return new (MagneticFieldUnit.Gauss, "Gauss", "Gausses", BaseUnits.Undefined); - yield return new (MagneticFieldUnit.Microtesla, "Microtesla", "Microteslas", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, current: ElectricCurrentUnit.Ampere)); - yield return new (MagneticFieldUnit.Milligauss, "Milligauss", "Milligausses", BaseUnits.Undefined); - yield return new (MagneticFieldUnit.Millitesla, "Millitesla", "Milliteslas", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, current: ElectricCurrentUnit.Ampere)); - yield return new (MagneticFieldUnit.Nanotesla, "Nanotesla", "Nanoteslas", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, current: ElectricCurrentUnit.Ampere)); + yield return new (MagneticFieldUnit.Gauss, "Gauss", "Gausses", BaseUnits.Undefined, + 10000 + ); + yield return new (MagneticFieldUnit.Microtesla, "Microtesla", "Microteslas", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, current: ElectricCurrentUnit.Ampere), + 1000000 + ); + yield return new (MagneticFieldUnit.Milligauss, "Milligauss", "Milligausses", BaseUnits.Undefined, + 10000000 + ); + yield return new (MagneticFieldUnit.Millitesla, "Millitesla", "Milliteslas", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, current: ElectricCurrentUnit.Ampere), + 1000 + ); + yield return new (MagneticFieldUnit.Nanotesla, "Nanotesla", "Nanoteslas", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, current: ElectricCurrentUnit.Ampere), + 1000000000 + ); yield return new (MagneticFieldUnit.Tesla, "Tesla", "Teslas", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, current: ElectricCurrentUnit.Ampere)); } } static MagneticField() { - Info = MagneticFieldInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MagneticFieldInfo.CreateDefault); } /// @@ -140,7 +147,7 @@ static MagneticField() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public MagneticField(double value, MagneticFieldUnit unit) + public MagneticField(QuantityValue value, MagneticFieldUnit unit) { _value = value; _unit = unit; @@ -154,7 +161,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -165,7 +172,8 @@ public MagneticField(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -194,10 +202,8 @@ public MagneticField(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public MagneticFieldUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -236,63 +242,39 @@ public MagneticField(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gausses => As(MagneticFieldUnit.Gauss); + public QuantityValue Gausses => this.As(MagneticFieldUnit.Gauss); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microteslas => As(MagneticFieldUnit.Microtesla); + public QuantityValue Microteslas => this.As(MagneticFieldUnit.Microtesla); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Milligausses => As(MagneticFieldUnit.Milligauss); + public QuantityValue Milligausses => this.As(MagneticFieldUnit.Milligauss); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Milliteslas => As(MagneticFieldUnit.Millitesla); + public QuantityValue Milliteslas => this.As(MagneticFieldUnit.Millitesla); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanoteslas => As(MagneticFieldUnit.Nanotesla); + public QuantityValue Nanoteslas => this.As(MagneticFieldUnit.Nanotesla); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Teslas => As(MagneticFieldUnit.Tesla); + public QuantityValue Teslas => this.As(MagneticFieldUnit.Tesla); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: MagneticFieldUnit -> BaseUnit - unitConverter.SetConversionFunction(MagneticFieldUnit.Gauss, MagneticFieldUnit.Tesla, quantity => quantity.ToUnit(MagneticFieldUnit.Tesla)); - unitConverter.SetConversionFunction(MagneticFieldUnit.Microtesla, MagneticFieldUnit.Tesla, quantity => quantity.ToUnit(MagneticFieldUnit.Tesla)); - unitConverter.SetConversionFunction(MagneticFieldUnit.Milligauss, MagneticFieldUnit.Tesla, quantity => quantity.ToUnit(MagneticFieldUnit.Tesla)); - unitConverter.SetConversionFunction(MagneticFieldUnit.Millitesla, MagneticFieldUnit.Tesla, quantity => quantity.ToUnit(MagneticFieldUnit.Tesla)); - unitConverter.SetConversionFunction(MagneticFieldUnit.Nanotesla, MagneticFieldUnit.Tesla, quantity => quantity.ToUnit(MagneticFieldUnit.Tesla)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(MagneticFieldUnit.Tesla, MagneticFieldUnit.Tesla, quantity => quantity); - - // Register in unit converter: BaseUnit -> MagneticFieldUnit - unitConverter.SetConversionFunction(MagneticFieldUnit.Tesla, MagneticFieldUnit.Gauss, quantity => quantity.ToUnit(MagneticFieldUnit.Gauss)); - unitConverter.SetConversionFunction(MagneticFieldUnit.Tesla, MagneticFieldUnit.Microtesla, quantity => quantity.ToUnit(MagneticFieldUnit.Microtesla)); - unitConverter.SetConversionFunction(MagneticFieldUnit.Tesla, MagneticFieldUnit.Milligauss, quantity => quantity.ToUnit(MagneticFieldUnit.Milligauss)); - unitConverter.SetConversionFunction(MagneticFieldUnit.Tesla, MagneticFieldUnit.Millitesla, quantity => quantity.ToUnit(MagneticFieldUnit.Millitesla)); - unitConverter.SetConversionFunction(MagneticFieldUnit.Tesla, MagneticFieldUnit.Nanotesla, quantity => quantity.ToUnit(MagneticFieldUnit.Nanotesla)); - } - /// /// Get unit abbreviation string. /// @@ -321,7 +303,7 @@ public static string GetAbbreviation(MagneticFieldUnit unit, IFormatProvider? pr /// /// Creates a from . /// - public static MagneticField FromGausses(double value) + public static MagneticField FromGausses(QuantityValue value) { return new MagneticField(value, MagneticFieldUnit.Gauss); } @@ -329,7 +311,7 @@ public static MagneticField FromGausses(double value) /// /// Creates a from . /// - public static MagneticField FromMicroteslas(double value) + public static MagneticField FromMicroteslas(QuantityValue value) { return new MagneticField(value, MagneticFieldUnit.Microtesla); } @@ -337,7 +319,7 @@ public static MagneticField FromMicroteslas(double value) /// /// Creates a from . /// - public static MagneticField FromMilligausses(double value) + public static MagneticField FromMilligausses(QuantityValue value) { return new MagneticField(value, MagneticFieldUnit.Milligauss); } @@ -345,7 +327,7 @@ public static MagneticField FromMilligausses(double value) /// /// Creates a from . /// - public static MagneticField FromMilliteslas(double value) + public static MagneticField FromMilliteslas(QuantityValue value) { return new MagneticField(value, MagneticFieldUnit.Millitesla); } @@ -353,7 +335,7 @@ public static MagneticField FromMilliteslas(double value) /// /// Creates a from . /// - public static MagneticField FromNanoteslas(double value) + public static MagneticField FromNanoteslas(QuantityValue value) { return new MagneticField(value, MagneticFieldUnit.Nanotesla); } @@ -361,7 +343,7 @@ public static MagneticField FromNanoteslas(double value) /// /// Creates a from . /// - public static MagneticField FromTeslas(double value) + public static MagneticField FromTeslas(QuantityValue value) { return new MagneticField(value, MagneticFieldUnit.Tesla); } @@ -372,7 +354,7 @@ public static MagneticField FromTeslas(double value) /// Value to convert from. /// Unit to convert from. /// MagneticField unit value. - public static MagneticField From(double value, MagneticFieldUnit fromUnit) + public static MagneticField From(QuantityValue value, MagneticFieldUnit fromUnit) { return new MagneticField(value, fromUnit); } @@ -433,10 +415,7 @@ public static MagneticField Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static MagneticField Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -464,11 +443,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out MagneticField re /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out MagneticField result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -489,7 +464,7 @@ public static MagneticFieldUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -500,7 +475,7 @@ public static MagneticFieldUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out MagneticFieldUnit unit) { return TryParseUnit(str, null, out unit); @@ -515,7 +490,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out MagneticFiel /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out MagneticFieldUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -534,35 +509,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static MagneticField operator +(MagneticField left, MagneticField right) { - return new MagneticField(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new MagneticField(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static MagneticField operator -(MagneticField left, MagneticField right) { - return new MagneticField(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new MagneticField(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -574,97 +549,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(MagneticField left, MagneticField right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(MagneticField left, MagneticField right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(MagneticField left, MagneticField right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(MagneticField left, MagneticField right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MagneticField other, MagneticField tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(MagneticField left, MagneticField right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MagneticField other, MagneticField tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(MagneticField left, MagneticField right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MagneticField other, MagneticField tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is MagneticField otherQuantity)) + if (obj is not MagneticField otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MagneticField other, MagneticField tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(MagneticField other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current MagneticField. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(MagneticField), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MagneticField otherQuantity)) throw new ArgumentException("Expected type MagneticField.", nameof(obj)); + if (obj is not MagneticField otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -676,156 +636,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MagneticField other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MagneticFieldUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this MagneticField to another MagneticField with the unit representation . - /// - /// The unit to convert to. - /// A MagneticField with the specified unit. - public MagneticField ToUnit(MagneticFieldUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A MagneticField with the specified unit. - public MagneticField ToUnit(MagneticFieldUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(MagneticField), Unit, typeof(MagneticField), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (MagneticField)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(MagneticFieldUnit unit, [NotNullWhen(true)] out MagneticField? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - MagneticField? convertedOrNull = (Unit, unit) switch - { - // MagneticFieldUnit -> BaseUnit - (MagneticFieldUnit.Gauss, MagneticFieldUnit.Tesla) => new MagneticField(_value / 1e4, MagneticFieldUnit.Tesla), - (MagneticFieldUnit.Microtesla, MagneticFieldUnit.Tesla) => new MagneticField((_value) * 1e-6d, MagneticFieldUnit.Tesla), - (MagneticFieldUnit.Milligauss, MagneticFieldUnit.Tesla) => new MagneticField((_value / 1e4) * 1e-3d, MagneticFieldUnit.Tesla), - (MagneticFieldUnit.Millitesla, MagneticFieldUnit.Tesla) => new MagneticField((_value) * 1e-3d, MagneticFieldUnit.Tesla), - (MagneticFieldUnit.Nanotesla, MagneticFieldUnit.Tesla) => new MagneticField((_value) * 1e-9d, MagneticFieldUnit.Tesla), - - // BaseUnit -> MagneticFieldUnit - (MagneticFieldUnit.Tesla, MagneticFieldUnit.Gauss) => new MagneticField(_value * 1e4, MagneticFieldUnit.Gauss), - (MagneticFieldUnit.Tesla, MagneticFieldUnit.Microtesla) => new MagneticField((_value) / 1e-6d, MagneticFieldUnit.Microtesla), - (MagneticFieldUnit.Tesla, MagneticFieldUnit.Milligauss) => new MagneticField((_value * 1e4) / 1e-3d, MagneticFieldUnit.Milligauss), - (MagneticFieldUnit.Tesla, MagneticFieldUnit.Millitesla) => new MagneticField((_value) / 1e-3d, MagneticFieldUnit.Millitesla), - (MagneticFieldUnit.Tesla, MagneticFieldUnit.Nanotesla) => new MagneticField((_value) / 1e-9d, MagneticFieldUnit.Nanotesla), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public MagneticField ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not MagneticFieldUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFieldUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(MagneticFieldUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(MagneticFieldUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -840,7 +668,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs index 3d38034988..f469e5571e 100644 --- a/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MagneticFlux.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Magnetic_flux /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct MagneticFlux : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly MagneticFluxUnit? _unit; /// @@ -104,7 +103,7 @@ public static MagneticFluxInfo CreateDefault(Func - /// The for is [T^-2][L^2][M][I^-1]. + /// The for is T^-2L^2MI^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, -1, 0, 0, 0); @@ -125,9 +124,7 @@ public static IEnumerable> GetDefaultMappings() static MagneticFlux() { - Info = MagneticFluxInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MagneticFluxInfo.CreateDefault); } /// @@ -135,7 +132,7 @@ static MagneticFlux() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public MagneticFlux(double value, MagneticFluxUnit unit) + public MagneticFlux(QuantityValue value, MagneticFluxUnit unit) { _value = value; _unit = unit; @@ -149,7 +146,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -160,7 +157,8 @@ public MagneticFlux(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -189,10 +187,8 @@ public MagneticFlux(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public MagneticFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -231,28 +227,14 @@ public MagneticFlux(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Webers => As(MagneticFluxUnit.Weber); + public QuantityValue Webers => this.As(MagneticFluxUnit.Weber); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: MagneticFluxUnit -> BaseUnit - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(MagneticFluxUnit.Weber, MagneticFluxUnit.Weber, quantity => quantity); - - // Register in unit converter: BaseUnit -> MagneticFluxUnit - } - /// /// Get unit abbreviation string. /// @@ -281,7 +263,7 @@ public static string GetAbbreviation(MagneticFluxUnit unit, IFormatProvider? pro /// /// Creates a from . /// - public static MagneticFlux FromWebers(double value) + public static MagneticFlux FromWebers(QuantityValue value) { return new MagneticFlux(value, MagneticFluxUnit.Weber); } @@ -292,7 +274,7 @@ public static MagneticFlux FromWebers(double value) /// Value to convert from. /// Unit to convert from. /// MagneticFlux unit value. - public static MagneticFlux From(double value, MagneticFluxUnit fromUnit) + public static MagneticFlux From(QuantityValue value, MagneticFluxUnit fromUnit) { return new MagneticFlux(value, fromUnit); } @@ -353,10 +335,7 @@ public static MagneticFlux Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static MagneticFlux Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -384,11 +363,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out MagneticFlux res /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out MagneticFlux result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -409,7 +384,7 @@ public static MagneticFluxUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -420,7 +395,7 @@ public static MagneticFluxUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out MagneticFluxUnit unit) { return TryParseUnit(str, null, out unit); @@ -435,7 +410,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out MagneticFlux /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out MagneticFluxUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -454,35 +429,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static MagneticFlux operator +(MagneticFlux left, MagneticFlux right) { - return new MagneticFlux(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new MagneticFlux(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static MagneticFlux operator -(MagneticFlux left, MagneticFlux right) { - return new MagneticFlux(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new MagneticFlux(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -494,97 +469,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(MagneticFlux left, MagneticFlux right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(MagneticFlux left, MagneticFlux right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(MagneticFlux left, MagneticFlux right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(MagneticFlux left, MagneticFlux right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MagneticFlux other, MagneticFlux tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(MagneticFlux left, MagneticFlux right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MagneticFlux other, MagneticFlux tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(MagneticFlux left, MagneticFlux right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MagneticFlux other, MagneticFlux tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is MagneticFlux otherQuantity)) + if (obj is not MagneticFlux otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MagneticFlux other, MagneticFlux tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(MagneticFlux other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current MagneticFlux. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(MagneticFlux), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MagneticFlux otherQuantity)) throw new ArgumentException("Expected type MagneticFlux.", nameof(obj)); + if (obj is not MagneticFlux otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -596,146 +556,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MagneticFlux other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MagneticFluxUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this MagneticFlux to another MagneticFlux with the unit representation . - /// - /// The unit to convert to. - /// A MagneticFlux with the specified unit. - public MagneticFlux ToUnit(MagneticFluxUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A MagneticFlux with the specified unit. - public MagneticFlux ToUnit(MagneticFluxUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(MagneticFlux), Unit, typeof(MagneticFlux), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (MagneticFlux)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(MagneticFluxUnit unit, [NotNullWhen(true)] out MagneticFlux? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - MagneticFlux? convertedOrNull = (Unit, unit) switch - { - // MagneticFluxUnit -> BaseUnit + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> MagneticFluxUnit - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public MagneticFlux ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not MagneticFluxUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFluxUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is MagneticFluxUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagneticFluxUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(MagneticFluxUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(MagneticFluxUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -750,7 +588,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs b/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs index 9e0db4c8ee..1a241f9809 100644 --- a/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Magnetization.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Magnetization /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Magnetization : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly MagnetizationUnit? _unit; /// @@ -104,7 +103,7 @@ public static MagnetizationInfo CreateDefault(Func - /// The for is [L^-1][I]. + /// The for is L^-1I. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 0, 0, 1, 0, 0, 0); @@ -125,9 +124,7 @@ public static IEnumerable> GetDefaultMappings( static Magnetization() { - Info = MagnetizationInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MagnetizationInfo.CreateDefault); } /// @@ -135,7 +132,7 @@ static Magnetization() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Magnetization(double value, MagnetizationUnit unit) + public Magnetization(QuantityValue value, MagnetizationUnit unit) { _value = value; _unit = unit; @@ -149,7 +146,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -160,7 +157,8 @@ public Magnetization(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -189,10 +187,8 @@ public Magnetization(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public MagnetizationUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -231,28 +227,14 @@ public Magnetization(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AmperesPerMeter => As(MagnetizationUnit.AmperePerMeter); + public QuantityValue AmperesPerMeter => this.As(MagnetizationUnit.AmperePerMeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: MagnetizationUnit -> BaseUnit - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(MagnetizationUnit.AmperePerMeter, MagnetizationUnit.AmperePerMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> MagnetizationUnit - } - /// /// Get unit abbreviation string. /// @@ -281,7 +263,7 @@ public static string GetAbbreviation(MagnetizationUnit unit, IFormatProvider? pr /// /// Creates a from . /// - public static Magnetization FromAmperesPerMeter(double value) + public static Magnetization FromAmperesPerMeter(QuantityValue value) { return new Magnetization(value, MagnetizationUnit.AmperePerMeter); } @@ -292,7 +274,7 @@ public static Magnetization FromAmperesPerMeter(double value) /// Value to convert from. /// Unit to convert from. /// Magnetization unit value. - public static Magnetization From(double value, MagnetizationUnit fromUnit) + public static Magnetization From(QuantityValue value, MagnetizationUnit fromUnit) { return new Magnetization(value, fromUnit); } @@ -353,10 +335,7 @@ public static Magnetization Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Magnetization Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -384,11 +363,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Magnetization re /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Magnetization result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -409,7 +384,7 @@ public static MagnetizationUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -420,7 +395,7 @@ public static MagnetizationUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out MagnetizationUnit unit) { return TryParseUnit(str, null, out unit); @@ -435,7 +410,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out Magnetizatio /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out MagnetizationUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -454,35 +429,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Magnetization operator +(Magnetization left, Magnetization right) { - return new Magnetization(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Magnetization(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Magnetization operator -(Magnetization left, Magnetization right) { - return new Magnetization(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Magnetization(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -494,97 +469,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Magnetization left, Magnetization right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Magnetization left, Magnetization right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Magnetization left, Magnetization right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Magnetization left, Magnetization right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Magnetization other, Magnetization tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Magnetization left, Magnetization right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Magnetization other, Magnetization tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Magnetization left, Magnetization right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Magnetization other, Magnetization tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Magnetization otherQuantity)) + if (obj is not Magnetization otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Magnetization other, Magnetization tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Magnetization other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Magnetization. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Magnetization), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Magnetization otherQuantity)) throw new ArgumentException("Expected type Magnetization.", nameof(obj)); + if (obj is not Magnetization otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -596,146 +556,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Magnetization other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MagnetizationUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this Magnetization to another Magnetization with the unit representation . - /// - /// The unit to convert to. - /// A Magnetization with the specified unit. - public Magnetization ToUnit(MagnetizationUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Magnetization with the specified unit. - public Magnetization ToUnit(MagnetizationUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Magnetization), Unit, typeof(Magnetization), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Magnetization)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(MagnetizationUnit unit, [NotNullWhen(true)] out Magnetization? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Magnetization? convertedOrNull = (Unit, unit) switch - { - // MagnetizationUnit -> BaseUnit + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> MagnetizationUnit - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Magnetization ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not MagnetizationUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagnetizationUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is MagnetizationUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MagnetizationUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(MagnetizationUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(MagnetizationUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -750,7 +588,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Mass.g.cs b/UnitsNet/GeneratedCode/Quantities/Mass.g.cs index b334caf182..a0c2a6e246 100644 --- a/UnitsNet/GeneratedCode/Quantities/Mass.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Mass.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Mass : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -68,13 +67,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly MassUnit? _unit; /// @@ -119,7 +118,7 @@ public static MassInfo CreateDefault(Func>, } /// - /// The for is [M]. + /// The for is M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, 0, 0, 0, 0, 0); @@ -134,41 +133,91 @@ public static MassInfo CreateDefault(Func>, /// An of representing the default unit mappings for Mass. public static IEnumerable> GetDefaultMappings() { - yield return new (MassUnit.Centigram, "Centigram", "Centigrams", new BaseUnits(mass: MassUnit.Centigram)); - yield return new (MassUnit.Decagram, "Decagram", "Decagrams", new BaseUnits(mass: MassUnit.Decagram)); - yield return new (MassUnit.Decigram, "Decigram", "Decigrams", new BaseUnits(mass: MassUnit.Decigram)); - yield return new (MassUnit.EarthMass, "EarthMass", "EarthMasses", new BaseUnits(mass: MassUnit.EarthMass)); - yield return new (MassUnit.Femtogram, "Femtogram", "Femtograms", new BaseUnits(mass: MassUnit.Femtogram)); - yield return new (MassUnit.Grain, "Grain", "Grains", new BaseUnits(mass: MassUnit.Grain)); - yield return new (MassUnit.Gram, "Gram", "Grams", new BaseUnits(mass: MassUnit.Gram)); - yield return new (MassUnit.Hectogram, "Hectogram", "Hectograms", new BaseUnits(mass: MassUnit.Hectogram)); + yield return new (MassUnit.Centigram, "Centigram", "Centigrams", new BaseUnits(mass: MassUnit.Centigram), + 100000 + ); + yield return new (MassUnit.Decagram, "Decagram", "Decagrams", new BaseUnits(mass: MassUnit.Decagram), + 100 + ); + yield return new (MassUnit.Decigram, "Decigram", "Decigrams", new BaseUnits(mass: MassUnit.Decigram), + 10000 + ); + yield return new (MassUnit.EarthMass, "EarthMass", "EarthMasses", new BaseUnits(mass: MassUnit.EarthMass), + new QuantityValue(1, new BigInteger(59722) * QuantityValue.PowerOfTen(20)) + ); + yield return new (MassUnit.Femtogram, "Femtogram", "Femtograms", new BaseUnits(mass: MassUnit.Femtogram), + 1000000000000000000 + ); + yield return new (MassUnit.Grain, "Grain", "Grains", new BaseUnits(mass: MassUnit.Grain), + new QuantityValue(100000000000, 6479891) + ); + yield return new (MassUnit.Gram, "Gram", "Grams", new BaseUnits(mass: MassUnit.Gram), + 1000 + ); + yield return new (MassUnit.Hectogram, "Hectogram", "Hectograms", new BaseUnits(mass: MassUnit.Hectogram), + 10 + ); yield return new (MassUnit.Kilogram, "Kilogram", "Kilograms", new BaseUnits(mass: MassUnit.Kilogram)); - yield return new (MassUnit.Kilopound, "Kilopound", "Kilopounds", new BaseUnits(mass: MassUnit.Kilopound)); - yield return new (MassUnit.Kilotonne, "Kilotonne", "Kilotonnes", new BaseUnits(mass: MassUnit.Kilotonne)); - yield return new (MassUnit.LongHundredweight, "LongHundredweight", "LongHundredweight", new BaseUnits(mass: MassUnit.LongHundredweight)); - yield return new (MassUnit.LongTon, "LongTon", "LongTons", new BaseUnits(mass: MassUnit.LongTon)); - yield return new (MassUnit.Megapound, "Megapound", "Megapounds", new BaseUnits(mass: MassUnit.Megapound)); - yield return new (MassUnit.Megatonne, "Megatonne", "Megatonnes", new BaseUnits(mass: MassUnit.Megatonne)); - yield return new (MassUnit.Microgram, "Microgram", "Micrograms", new BaseUnits(mass: MassUnit.Microgram)); - yield return new (MassUnit.Milligram, "Milligram", "Milligrams", new BaseUnits(mass: MassUnit.Milligram)); - yield return new (MassUnit.Nanogram, "Nanogram", "Nanograms", new BaseUnits(mass: MassUnit.Nanogram)); - yield return new (MassUnit.Ounce, "Ounce", "Ounces", new BaseUnits(mass: MassUnit.Ounce)); - yield return new (MassUnit.Picogram, "Picogram", "Picograms", new BaseUnits(mass: MassUnit.Picogram)); - yield return new (MassUnit.Pound, "Pound", "Pounds", new BaseUnits(mass: MassUnit.Pound)); - yield return new (MassUnit.ShortHundredweight, "ShortHundredweight", "ShortHundredweight", new BaseUnits(mass: MassUnit.ShortHundredweight)); - yield return new (MassUnit.ShortTon, "ShortTon", "ShortTons", new BaseUnits(mass: MassUnit.ShortTon)); - yield return new (MassUnit.Slug, "Slug", "Slugs", new BaseUnits(mass: MassUnit.Slug)); - yield return new (MassUnit.SolarMass, "SolarMass", "SolarMasses", new BaseUnits(mass: MassUnit.SolarMass)); - yield return new (MassUnit.Stone, "Stone", "Stone", new BaseUnits(mass: MassUnit.Stone)); - yield return new (MassUnit.Tonne, "Tonne", "Tonnes", new BaseUnits(mass: MassUnit.Tonne)); + yield return new (MassUnit.Kilopound, "Kilopound", "Kilopounds", new BaseUnits(mass: MassUnit.Kilopound), + new QuantityValue(100000, 45359237) + ); + yield return new (MassUnit.Kilotonne, "Kilotonne", "Kilotonnes", new BaseUnits(mass: MassUnit.Kilotonne), + new QuantityValue(1, 1000000) + ); + yield return new (MassUnit.LongHundredweight, "LongHundredweight", "LongHundredweight", new BaseUnits(mass: MassUnit.LongHundredweight), + new QuantityValue(6250000, 317514659) + ); + yield return new (MassUnit.LongTon, "LongTon", "LongTons", new BaseUnits(mass: MassUnit.LongTon), + new QuantityValue(312500, 317514659) + ); + yield return new (MassUnit.Megapound, "Megapound", "Megapounds", new BaseUnits(mass: MassUnit.Megapound), + new QuantityValue(100, 45359237) + ); + yield return new (MassUnit.Megatonne, "Megatonne", "Megatonnes", new BaseUnits(mass: MassUnit.Megatonne), + new QuantityValue(1, 1000000000) + ); + yield return new (MassUnit.Microgram, "Microgram", "Micrograms", new BaseUnits(mass: MassUnit.Microgram), + 1000000000 + ); + yield return new (MassUnit.Milligram, "Milligram", "Milligrams", new BaseUnits(mass: MassUnit.Milligram), + 1000000 + ); + yield return new (MassUnit.Nanogram, "Nanogram", "Nanograms", new BaseUnits(mass: MassUnit.Nanogram), + 1000000000000 + ); + yield return new (MassUnit.Ounce, "Ounce", "Ounces", new BaseUnits(mass: MassUnit.Ounce), + new QuantityValue(1600000000, 45359237) + ); + yield return new (MassUnit.Picogram, "Picogram", "Picograms", new BaseUnits(mass: MassUnit.Picogram), + 1000000000000000 + ); + yield return new (MassUnit.Pound, "Pound", "Pounds", new BaseUnits(mass: MassUnit.Pound), + new QuantityValue(100000000, 45359237) + ); + yield return new (MassUnit.ShortHundredweight, "ShortHundredweight", "ShortHundredweight", new BaseUnits(mass: MassUnit.ShortHundredweight), + new QuantityValue(1000000, 45359237) + ); + yield return new (MassUnit.ShortTon, "ShortTon", "ShortTons", new BaseUnits(mass: MassUnit.ShortTon), + new QuantityValue(50000, 45359237) + ); + yield return new (MassUnit.Slug, "Slug", "Slugs", new BaseUnits(mass: MassUnit.Slug), + new QuantityValue(609600000000, 8896443230521) + ); + yield return new (MassUnit.SolarMass, "SolarMass", "SolarMasses", new BaseUnits(mass: MassUnit.SolarMass), + new QuantityValue(1, new BigInteger(198947) * QuantityValue.PowerOfTen(25)) + ); + yield return new (MassUnit.Stone, "Stone", "Stone", new BaseUnits(mass: MassUnit.Stone), + new QuantityValue(50000000, 317514659) + ); + yield return new (MassUnit.Tonne, "Tonne", "Tonnes", new BaseUnits(mass: MassUnit.Tonne), + new QuantityValue(1, 1000) + ); } } static Mass() { - Info = MassInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MassInfo.CreateDefault); } /// @@ -176,7 +225,7 @@ static Mass() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Mass(double value, MassUnit unit) + public Mass(QuantityValue value, MassUnit unit) { _value = value; _unit = unit; @@ -190,7 +239,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -201,7 +250,8 @@ public Mass(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -230,10 +280,8 @@ public Mass(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public MassUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -272,210 +320,144 @@ public Mass(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Centigrams => As(MassUnit.Centigram); + public QuantityValue Centigrams => this.As(MassUnit.Centigram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Decagrams => As(MassUnit.Decagram); + public QuantityValue Decagrams => this.As(MassUnit.Decagram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Decigrams => As(MassUnit.Decigram); + public QuantityValue Decigrams => this.As(MassUnit.Decigram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double EarthMasses => As(MassUnit.EarthMass); + public QuantityValue EarthMasses => this.As(MassUnit.EarthMass); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Femtograms => As(MassUnit.Femtogram); + public QuantityValue Femtograms => this.As(MassUnit.Femtogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Grains => As(MassUnit.Grain); + public QuantityValue Grains => this.As(MassUnit.Grain); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Grams => As(MassUnit.Gram); + public QuantityValue Grams => this.As(MassUnit.Gram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Hectograms => As(MassUnit.Hectogram); + public QuantityValue Hectograms => this.As(MassUnit.Hectogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilograms => As(MassUnit.Kilogram); + public QuantityValue Kilograms => this.As(MassUnit.Kilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilopounds => As(MassUnit.Kilopound); + public QuantityValue Kilopounds => this.As(MassUnit.Kilopound); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilotonnes => As(MassUnit.Kilotonne); + public QuantityValue Kilotonnes => this.As(MassUnit.Kilotonne); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double LongHundredweight => As(MassUnit.LongHundredweight); + public QuantityValue LongHundredweight => this.As(MassUnit.LongHundredweight); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double LongTons => As(MassUnit.LongTon); + public QuantityValue LongTons => this.As(MassUnit.LongTon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megapounds => As(MassUnit.Megapound); + public QuantityValue Megapounds => this.As(MassUnit.Megapound); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megatonnes => As(MassUnit.Megatonne); + public QuantityValue Megatonnes => this.As(MassUnit.Megatonne); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Micrograms => As(MassUnit.Microgram); + public QuantityValue Micrograms => this.As(MassUnit.Microgram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Milligrams => As(MassUnit.Milligram); + public QuantityValue Milligrams => this.As(MassUnit.Milligram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanograms => As(MassUnit.Nanogram); + public QuantityValue Nanograms => this.As(MassUnit.Nanogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Ounces => As(MassUnit.Ounce); + public QuantityValue Ounces => this.As(MassUnit.Ounce); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Picograms => As(MassUnit.Picogram); + public QuantityValue Picograms => this.As(MassUnit.Picogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Pounds => As(MassUnit.Pound); + public QuantityValue Pounds => this.As(MassUnit.Pound); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ShortHundredweight => As(MassUnit.ShortHundredweight); + public QuantityValue ShortHundredweight => this.As(MassUnit.ShortHundredweight); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ShortTons => As(MassUnit.ShortTon); + public QuantityValue ShortTons => this.As(MassUnit.ShortTon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Slugs => As(MassUnit.Slug); + public QuantityValue Slugs => this.As(MassUnit.Slug); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SolarMasses => As(MassUnit.SolarMass); + public QuantityValue SolarMasses => this.As(MassUnit.SolarMass); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Stone => As(MassUnit.Stone); + public QuantityValue Stone => this.As(MassUnit.Stone); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Tonnes => As(MassUnit.Tonne); + public QuantityValue Tonnes => this.As(MassUnit.Tonne); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: MassUnit -> BaseUnit - unitConverter.SetConversionFunction(MassUnit.Centigram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Decagram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Decigram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.EarthMass, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Femtogram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Grain, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Gram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Hectogram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Kilopound, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Kilotonne, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.LongHundredweight, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.LongTon, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Megapound, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Megatonne, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Microgram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Milligram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Nanogram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Ounce, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Picogram, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Pound, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.ShortHundredweight, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.ShortTon, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Slug, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.SolarMass, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Stone, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - unitConverter.SetConversionFunction(MassUnit.Tonne, MassUnit.Kilogram, quantity => quantity.ToUnit(MassUnit.Kilogram)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Kilogram, quantity => quantity); - - // Register in unit converter: BaseUnit -> MassUnit - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Centigram, quantity => quantity.ToUnit(MassUnit.Centigram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Decagram, quantity => quantity.ToUnit(MassUnit.Decagram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Decigram, quantity => quantity.ToUnit(MassUnit.Decigram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.EarthMass, quantity => quantity.ToUnit(MassUnit.EarthMass)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Femtogram, quantity => quantity.ToUnit(MassUnit.Femtogram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Grain, quantity => quantity.ToUnit(MassUnit.Grain)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Gram, quantity => quantity.ToUnit(MassUnit.Gram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Hectogram, quantity => quantity.ToUnit(MassUnit.Hectogram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Kilopound, quantity => quantity.ToUnit(MassUnit.Kilopound)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Kilotonne, quantity => quantity.ToUnit(MassUnit.Kilotonne)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.LongHundredweight, quantity => quantity.ToUnit(MassUnit.LongHundredweight)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.LongTon, quantity => quantity.ToUnit(MassUnit.LongTon)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Megapound, quantity => quantity.ToUnit(MassUnit.Megapound)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Megatonne, quantity => quantity.ToUnit(MassUnit.Megatonne)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Microgram, quantity => quantity.ToUnit(MassUnit.Microgram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Milligram, quantity => quantity.ToUnit(MassUnit.Milligram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Nanogram, quantity => quantity.ToUnit(MassUnit.Nanogram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Ounce, quantity => quantity.ToUnit(MassUnit.Ounce)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Picogram, quantity => quantity.ToUnit(MassUnit.Picogram)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Pound, quantity => quantity.ToUnit(MassUnit.Pound)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.ShortHundredweight, quantity => quantity.ToUnit(MassUnit.ShortHundredweight)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.ShortTon, quantity => quantity.ToUnit(MassUnit.ShortTon)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Slug, quantity => quantity.ToUnit(MassUnit.Slug)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.SolarMass, quantity => quantity.ToUnit(MassUnit.SolarMass)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Stone, quantity => quantity.ToUnit(MassUnit.Stone)); - unitConverter.SetConversionFunction(MassUnit.Kilogram, MassUnit.Tonne, quantity => quantity.ToUnit(MassUnit.Tonne)); - } - /// /// Get unit abbreviation string. /// @@ -504,7 +486,7 @@ public static string GetAbbreviation(MassUnit unit, IFormatProvider? provider) /// /// Creates a from . /// - public static Mass FromCentigrams(double value) + public static Mass FromCentigrams(QuantityValue value) { return new Mass(value, MassUnit.Centigram); } @@ -512,7 +494,7 @@ public static Mass FromCentigrams(double value) /// /// Creates a from . /// - public static Mass FromDecagrams(double value) + public static Mass FromDecagrams(QuantityValue value) { return new Mass(value, MassUnit.Decagram); } @@ -520,7 +502,7 @@ public static Mass FromDecagrams(double value) /// /// Creates a from . /// - public static Mass FromDecigrams(double value) + public static Mass FromDecigrams(QuantityValue value) { return new Mass(value, MassUnit.Decigram); } @@ -528,7 +510,7 @@ public static Mass FromDecigrams(double value) /// /// Creates a from . /// - public static Mass FromEarthMasses(double value) + public static Mass FromEarthMasses(QuantityValue value) { return new Mass(value, MassUnit.EarthMass); } @@ -536,7 +518,7 @@ public static Mass FromEarthMasses(double value) /// /// Creates a from . /// - public static Mass FromFemtograms(double value) + public static Mass FromFemtograms(QuantityValue value) { return new Mass(value, MassUnit.Femtogram); } @@ -544,7 +526,7 @@ public static Mass FromFemtograms(double value) /// /// Creates a from . /// - public static Mass FromGrains(double value) + public static Mass FromGrains(QuantityValue value) { return new Mass(value, MassUnit.Grain); } @@ -552,7 +534,7 @@ public static Mass FromGrains(double value) /// /// Creates a from . /// - public static Mass FromGrams(double value) + public static Mass FromGrams(QuantityValue value) { return new Mass(value, MassUnit.Gram); } @@ -560,7 +542,7 @@ public static Mass FromGrams(double value) /// /// Creates a from . /// - public static Mass FromHectograms(double value) + public static Mass FromHectograms(QuantityValue value) { return new Mass(value, MassUnit.Hectogram); } @@ -568,7 +550,7 @@ public static Mass FromHectograms(double value) /// /// Creates a from . /// - public static Mass FromKilograms(double value) + public static Mass FromKilograms(QuantityValue value) { return new Mass(value, MassUnit.Kilogram); } @@ -576,7 +558,7 @@ public static Mass FromKilograms(double value) /// /// Creates a from . /// - public static Mass FromKilopounds(double value) + public static Mass FromKilopounds(QuantityValue value) { return new Mass(value, MassUnit.Kilopound); } @@ -584,7 +566,7 @@ public static Mass FromKilopounds(double value) /// /// Creates a from . /// - public static Mass FromKilotonnes(double value) + public static Mass FromKilotonnes(QuantityValue value) { return new Mass(value, MassUnit.Kilotonne); } @@ -592,7 +574,7 @@ public static Mass FromKilotonnes(double value) /// /// Creates a from . /// - public static Mass FromLongHundredweight(double value) + public static Mass FromLongHundredweight(QuantityValue value) { return new Mass(value, MassUnit.LongHundredweight); } @@ -600,7 +582,7 @@ public static Mass FromLongHundredweight(double value) /// /// Creates a from . /// - public static Mass FromLongTons(double value) + public static Mass FromLongTons(QuantityValue value) { return new Mass(value, MassUnit.LongTon); } @@ -608,7 +590,7 @@ public static Mass FromLongTons(double value) /// /// Creates a from . /// - public static Mass FromMegapounds(double value) + public static Mass FromMegapounds(QuantityValue value) { return new Mass(value, MassUnit.Megapound); } @@ -616,7 +598,7 @@ public static Mass FromMegapounds(double value) /// /// Creates a from . /// - public static Mass FromMegatonnes(double value) + public static Mass FromMegatonnes(QuantityValue value) { return new Mass(value, MassUnit.Megatonne); } @@ -624,7 +606,7 @@ public static Mass FromMegatonnes(double value) /// /// Creates a from . /// - public static Mass FromMicrograms(double value) + public static Mass FromMicrograms(QuantityValue value) { return new Mass(value, MassUnit.Microgram); } @@ -632,7 +614,7 @@ public static Mass FromMicrograms(double value) /// /// Creates a from . /// - public static Mass FromMilligrams(double value) + public static Mass FromMilligrams(QuantityValue value) { return new Mass(value, MassUnit.Milligram); } @@ -640,7 +622,7 @@ public static Mass FromMilligrams(double value) /// /// Creates a from . /// - public static Mass FromNanograms(double value) + public static Mass FromNanograms(QuantityValue value) { return new Mass(value, MassUnit.Nanogram); } @@ -648,7 +630,7 @@ public static Mass FromNanograms(double value) /// /// Creates a from . /// - public static Mass FromOunces(double value) + public static Mass FromOunces(QuantityValue value) { return new Mass(value, MassUnit.Ounce); } @@ -656,7 +638,7 @@ public static Mass FromOunces(double value) /// /// Creates a from . /// - public static Mass FromPicograms(double value) + public static Mass FromPicograms(QuantityValue value) { return new Mass(value, MassUnit.Picogram); } @@ -664,7 +646,7 @@ public static Mass FromPicograms(double value) /// /// Creates a from . /// - public static Mass FromPounds(double value) + public static Mass FromPounds(QuantityValue value) { return new Mass(value, MassUnit.Pound); } @@ -672,7 +654,7 @@ public static Mass FromPounds(double value) /// /// Creates a from . /// - public static Mass FromShortHundredweight(double value) + public static Mass FromShortHundredweight(QuantityValue value) { return new Mass(value, MassUnit.ShortHundredweight); } @@ -680,7 +662,7 @@ public static Mass FromShortHundredweight(double value) /// /// Creates a from . /// - public static Mass FromShortTons(double value) + public static Mass FromShortTons(QuantityValue value) { return new Mass(value, MassUnit.ShortTon); } @@ -688,7 +670,7 @@ public static Mass FromShortTons(double value) /// /// Creates a from . /// - public static Mass FromSlugs(double value) + public static Mass FromSlugs(QuantityValue value) { return new Mass(value, MassUnit.Slug); } @@ -696,7 +678,7 @@ public static Mass FromSlugs(double value) /// /// Creates a from . /// - public static Mass FromSolarMasses(double value) + public static Mass FromSolarMasses(QuantityValue value) { return new Mass(value, MassUnit.SolarMass); } @@ -704,7 +686,7 @@ public static Mass FromSolarMasses(double value) /// /// Creates a from . /// - public static Mass FromStone(double value) + public static Mass FromStone(QuantityValue value) { return new Mass(value, MassUnit.Stone); } @@ -712,7 +694,7 @@ public static Mass FromStone(double value) /// /// Creates a from . /// - public static Mass FromTonnes(double value) + public static Mass FromTonnes(QuantityValue value) { return new Mass(value, MassUnit.Tonne); } @@ -723,7 +705,7 @@ public static Mass FromTonnes(double value) /// Value to convert from. /// Unit to convert from. /// Mass unit value. - public static Mass From(double value, MassUnit fromUnit) + public static Mass From(QuantityValue value, MassUnit fromUnit) { return new Mass(value, fromUnit); } @@ -784,10 +766,7 @@ public static Mass Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Mass Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -815,11 +794,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Mass result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Mass result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -840,7 +815,7 @@ public static MassUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -851,7 +826,7 @@ public static MassUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out MassUnit unit) { return TryParseUnit(str, null, out unit); @@ -866,7 +841,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out MassUnit uni /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out MassUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -885,35 +860,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Mass operator +(Mass left, Mass right) { - return new Mass(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Mass(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Mass operator -(Mass left, Mass right) { - return new Mass(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Mass(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -1025,97 +1000,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Mass left, Mass right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Mass left, Mass right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Mass left, Mass right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Mass left, Mass right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Mass other, Mass tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Mass left, Mass right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Mass other, Mass tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Mass left, Mass right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Mass other, Mass tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Mass otherQuantity)) + if (obj is not Mass otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Mass other, Mass tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Mass other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Mass. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Mass), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Mass otherQuantity)) throw new ArgumentException("Expected type Mass.", nameof(obj)); + if (obj is not Mass otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1127,198 +1087,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Mass other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Mass to another Mass with the unit representation . - /// - /// The unit to convert to. - /// A Mass with the specified unit. - public Mass ToUnit(MassUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Mass with the specified unit. - public Mass ToUnit(MassUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Mass), Unit, typeof(Mass), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Mass)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(MassUnit unit, [NotNullWhen(true)] out Mass? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Mass? convertedOrNull = (Unit, unit) switch - { - // MassUnit -> BaseUnit - (MassUnit.Centigram, MassUnit.Kilogram) => new Mass((_value / 1e3) * 1e-2d, MassUnit.Kilogram), - (MassUnit.Decagram, MassUnit.Kilogram) => new Mass((_value / 1e3) * 1e1d, MassUnit.Kilogram), - (MassUnit.Decigram, MassUnit.Kilogram) => new Mass((_value / 1e3) * 1e-1d, MassUnit.Kilogram), - (MassUnit.EarthMass, MassUnit.Kilogram) => new Mass(_value * 5.9722E+24, MassUnit.Kilogram), - (MassUnit.Femtogram, MassUnit.Kilogram) => new Mass((_value / 1e3) * 1e-15d, MassUnit.Kilogram), - (MassUnit.Grain, MassUnit.Kilogram) => new Mass(_value * 64.79891e-6, MassUnit.Kilogram), - (MassUnit.Gram, MassUnit.Kilogram) => new Mass(_value / 1e3, MassUnit.Kilogram), - (MassUnit.Hectogram, MassUnit.Kilogram) => new Mass((_value / 1e3) * 1e2d, MassUnit.Kilogram), - (MassUnit.Kilopound, MassUnit.Kilogram) => new Mass((_value * 0.45359237) * 1e3d, MassUnit.Kilogram), - (MassUnit.Kilotonne, MassUnit.Kilogram) => new Mass((_value * 1e3) * 1e3d, MassUnit.Kilogram), - (MassUnit.LongHundredweight, MassUnit.Kilogram) => new Mass(_value * 50.80234544, MassUnit.Kilogram), - (MassUnit.LongTon, MassUnit.Kilogram) => new Mass(_value * 1016.0469088, MassUnit.Kilogram), - (MassUnit.Megapound, MassUnit.Kilogram) => new Mass((_value * 0.45359237) * 1e6d, MassUnit.Kilogram), - (MassUnit.Megatonne, MassUnit.Kilogram) => new Mass((_value * 1e3) * 1e6d, MassUnit.Kilogram), - (MassUnit.Microgram, MassUnit.Kilogram) => new Mass((_value / 1e3) * 1e-6d, MassUnit.Kilogram), - (MassUnit.Milligram, MassUnit.Kilogram) => new Mass((_value / 1e3) * 1e-3d, MassUnit.Kilogram), - (MassUnit.Nanogram, MassUnit.Kilogram) => new Mass((_value / 1e3) * 1e-9d, MassUnit.Kilogram), - (MassUnit.Ounce, MassUnit.Kilogram) => new Mass(_value * 0.028349523125, MassUnit.Kilogram), - (MassUnit.Picogram, MassUnit.Kilogram) => new Mass((_value / 1e3) * 1e-12d, MassUnit.Kilogram), - (MassUnit.Pound, MassUnit.Kilogram) => new Mass(_value * 0.45359237, MassUnit.Kilogram), - (MassUnit.ShortHundredweight, MassUnit.Kilogram) => new Mass(_value * 45.359237, MassUnit.Kilogram), - (MassUnit.ShortTon, MassUnit.Kilogram) => new Mass(_value * 907.18474, MassUnit.Kilogram), - (MassUnit.Slug, MassUnit.Kilogram) => new Mass(_value * 0.45359237 * 9.80665 / 0.3048, MassUnit.Kilogram), - (MassUnit.SolarMass, MassUnit.Kilogram) => new Mass(_value * 1.98947e30, MassUnit.Kilogram), - (MassUnit.Stone, MassUnit.Kilogram) => new Mass(_value * 6.35029318, MassUnit.Kilogram), - (MassUnit.Tonne, MassUnit.Kilogram) => new Mass(_value * 1e3, MassUnit.Kilogram), - - // BaseUnit -> MassUnit - (MassUnit.Kilogram, MassUnit.Centigram) => new Mass((_value * 1e3) / 1e-2d, MassUnit.Centigram), - (MassUnit.Kilogram, MassUnit.Decagram) => new Mass((_value * 1e3) / 1e1d, MassUnit.Decagram), - (MassUnit.Kilogram, MassUnit.Decigram) => new Mass((_value * 1e3) / 1e-1d, MassUnit.Decigram), - (MassUnit.Kilogram, MassUnit.EarthMass) => new Mass(_value / 5.9722E+24, MassUnit.EarthMass), - (MassUnit.Kilogram, MassUnit.Femtogram) => new Mass((_value * 1e3) / 1e-15d, MassUnit.Femtogram), - (MassUnit.Kilogram, MassUnit.Grain) => new Mass(_value / 64.79891e-6, MassUnit.Grain), - (MassUnit.Kilogram, MassUnit.Gram) => new Mass(_value * 1e3, MassUnit.Gram), - (MassUnit.Kilogram, MassUnit.Hectogram) => new Mass((_value * 1e3) / 1e2d, MassUnit.Hectogram), - (MassUnit.Kilogram, MassUnit.Kilopound) => new Mass((_value / 0.45359237) / 1e3d, MassUnit.Kilopound), - (MassUnit.Kilogram, MassUnit.Kilotonne) => new Mass((_value / 1e3) / 1e3d, MassUnit.Kilotonne), - (MassUnit.Kilogram, MassUnit.LongHundredweight) => new Mass(_value / 50.80234544, MassUnit.LongHundredweight), - (MassUnit.Kilogram, MassUnit.LongTon) => new Mass(_value / 1016.0469088, MassUnit.LongTon), - (MassUnit.Kilogram, MassUnit.Megapound) => new Mass((_value / 0.45359237) / 1e6d, MassUnit.Megapound), - (MassUnit.Kilogram, MassUnit.Megatonne) => new Mass((_value / 1e3) / 1e6d, MassUnit.Megatonne), - (MassUnit.Kilogram, MassUnit.Microgram) => new Mass((_value * 1e3) / 1e-6d, MassUnit.Microgram), - (MassUnit.Kilogram, MassUnit.Milligram) => new Mass((_value * 1e3) / 1e-3d, MassUnit.Milligram), - (MassUnit.Kilogram, MassUnit.Nanogram) => new Mass((_value * 1e3) / 1e-9d, MassUnit.Nanogram), - (MassUnit.Kilogram, MassUnit.Ounce) => new Mass(_value / 0.028349523125, MassUnit.Ounce), - (MassUnit.Kilogram, MassUnit.Picogram) => new Mass((_value * 1e3) / 1e-12d, MassUnit.Picogram), - (MassUnit.Kilogram, MassUnit.Pound) => new Mass(_value / 0.45359237, MassUnit.Pound), - (MassUnit.Kilogram, MassUnit.ShortHundredweight) => new Mass(_value / 45.359237, MassUnit.ShortHundredweight), - (MassUnit.Kilogram, MassUnit.ShortTon) => new Mass(_value / 907.18474, MassUnit.ShortTon), - (MassUnit.Kilogram, MassUnit.Slug) => new Mass(_value * 0.3048 / (0.45359237 * 9.80665), MassUnit.Slug), - (MassUnit.Kilogram, MassUnit.SolarMass) => new Mass(_value / 1.98947e30, MassUnit.SolarMass), - (MassUnit.Kilogram, MassUnit.Stone) => new Mass(_value / 6.35029318, MassUnit.Stone), - (MassUnit.Kilogram, MassUnit.Tonne) => new Mass(_value / 1e3, MassUnit.Tonne), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Mass ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not MassUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(MassUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(MassUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1333,7 +1119,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs b/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs index fd87c94d15..ff4c19e2a9 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassConcentration.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Mass_concentration_(chemistry) /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct MassConcentration : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -60,13 +59,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly MassConcentrationUnit? _unit; /// @@ -111,7 +110,7 @@ public static MassConcentrationInfo CreateDefault(Func - /// The for is [L^-3][M]. + /// The for is L^-3M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-3, 1, 0, 0, 0, 0, 0); @@ -126,63 +125,157 @@ public static MassConcentrationInfo CreateDefault(FuncAn of representing the default unit mappings for MassConcentration. public static IEnumerable> GetDefaultMappings() { - yield return new (MassConcentrationUnit.CentigramPerDeciliter, "CentigramPerDeciliter", "CentigramsPerDeciliter", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.CentigramPerLiter, "CentigramPerLiter", "CentigramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Centigram)); - yield return new (MassConcentrationUnit.CentigramPerMicroliter, "CentigramPerMicroliter", "CentigramsPerMicroliter", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.CentigramPerMilliliter, "CentigramPerMilliliter", "CentigramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Centigram)); - yield return new (MassConcentrationUnit.DecigramPerDeciliter, "DecigramPerDeciliter", "DecigramsPerDeciliter", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.DecigramPerLiter, "DecigramPerLiter", "DecigramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Decigram)); - yield return new (MassConcentrationUnit.DecigramPerMicroliter, "DecigramPerMicroliter", "DecigramsPerMicroliter", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.DecigramPerMilliliter, "DecigramPerMilliliter", "DecigramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Decigram)); - yield return new (MassConcentrationUnit.GramPerCubicCentimeter, "GramPerCubicCentimeter", "GramsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram)); - yield return new (MassConcentrationUnit.GramPerCubicMeter, "GramPerCubicMeter", "GramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram)); - yield return new (MassConcentrationUnit.GramPerCubicMillimeter, "GramPerCubicMillimeter", "GramsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram)); - yield return new (MassConcentrationUnit.GramPerDeciliter, "GramPerDeciliter", "GramsPerDeciliter", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.GramPerLiter, "GramPerLiter", "GramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Gram)); - yield return new (MassConcentrationUnit.GramPerMicroliter, "GramPerMicroliter", "GramsPerMicroliter", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.GramPerMilliliter, "GramPerMilliliter", "GramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram)); - yield return new (MassConcentrationUnit.KilogramPerCubicCentimeter, "KilogramPerCubicCentimeter", "KilogramsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram)); + yield return new (MassConcentrationUnit.CentigramPerDeciliter, "CentigramPerDeciliter", "CentigramsPerDeciliter", BaseUnits.Undefined, + 10 + ); + yield return new (MassConcentrationUnit.CentigramPerLiter, "CentigramPerLiter", "CentigramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Centigram), + 100 + ); + yield return new (MassConcentrationUnit.CentigramPerMicroliter, "CentigramPerMicroliter", "CentigramsPerMicroliter", BaseUnits.Undefined, + new QuantityValue(1, 10000) + ); + yield return new (MassConcentrationUnit.CentigramPerMilliliter, "CentigramPerMilliliter", "CentigramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Centigram), + new QuantityValue(1, 10) + ); + yield return new (MassConcentrationUnit.DecigramPerDeciliter, "DecigramPerDeciliter", "DecigramsPerDeciliter", BaseUnits.Undefined, + 1 + ); + yield return new (MassConcentrationUnit.DecigramPerLiter, "DecigramPerLiter", "DecigramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Decigram), + 10 + ); + yield return new (MassConcentrationUnit.DecigramPerMicroliter, "DecigramPerMicroliter", "DecigramsPerMicroliter", BaseUnits.Undefined, + new QuantityValue(1, 100000) + ); + yield return new (MassConcentrationUnit.DecigramPerMilliliter, "DecigramPerMilliliter", "DecigramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Decigram), + new QuantityValue(1, 100) + ); + yield return new (MassConcentrationUnit.GramPerCubicCentimeter, "GramPerCubicCentimeter", "GramsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram), + new QuantityValue(1, 1000) + ); + yield return new (MassConcentrationUnit.GramPerCubicMeter, "GramPerCubicMeter", "GramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram), + 1000 + ); + yield return new (MassConcentrationUnit.GramPerCubicMillimeter, "GramPerCubicMillimeter", "GramsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram), + new QuantityValue(1, 1000000) + ); + yield return new (MassConcentrationUnit.GramPerDeciliter, "GramPerDeciliter", "GramsPerDeciliter", BaseUnits.Undefined, + new QuantityValue(1, 10) + ); + yield return new (MassConcentrationUnit.GramPerLiter, "GramPerLiter", "GramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Gram), + 1 + ); + yield return new (MassConcentrationUnit.GramPerMicroliter, "GramPerMicroliter", "GramsPerMicroliter", BaseUnits.Undefined, + new QuantityValue(1, 1000000) + ); + yield return new (MassConcentrationUnit.GramPerMilliliter, "GramPerMilliliter", "GramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram), + new QuantityValue(1, 1000) + ); + yield return new (MassConcentrationUnit.KilogramPerCubicCentimeter, "KilogramPerCubicCentimeter", "KilogramsPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram), + new QuantityValue(1, 1000000) + ); yield return new (MassConcentrationUnit.KilogramPerCubicMeter, "KilogramPerCubicMeter", "KilogramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram)); - yield return new (MassConcentrationUnit.KilogramPerCubicMillimeter, "KilogramPerCubicMillimeter", "KilogramsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram)); - yield return new (MassConcentrationUnit.KilogramPerLiter, "KilogramPerLiter", "KilogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram)); - yield return new (MassConcentrationUnit.KilopoundPerCubicFoot, "KilopoundPerCubicFoot", "KilopoundsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Kilopound)); - yield return new (MassConcentrationUnit.KilopoundPerCubicInch, "KilopoundPerCubicInch", "KilopoundsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Kilopound)); - yield return new (MassConcentrationUnit.MicrogramPerCubicMeter, "MicrogramPerCubicMeter", "MicrogramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram)); - yield return new (MassConcentrationUnit.MicrogramPerDeciliter, "MicrogramPerDeciliter", "MicrogramsPerDeciliter", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.MicrogramPerLiter, "MicrogramPerLiter", "MicrogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Microgram)); - yield return new (MassConcentrationUnit.MicrogramPerMicroliter, "MicrogramPerMicroliter", "MicrogramsPerMicroliter", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.MicrogramPerMilliliter, "MicrogramPerMilliliter", "MicrogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Microgram)); - yield return new (MassConcentrationUnit.MilligramPerCubicMeter, "MilligramPerCubicMeter", "MilligramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram)); - yield return new (MassConcentrationUnit.MilligramPerDeciliter, "MilligramPerDeciliter", "MilligramsPerDeciliter", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.MilligramPerLiter, "MilligramPerLiter", "MilligramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Milligram)); - yield return new (MassConcentrationUnit.MilligramPerMicroliter, "MilligramPerMicroliter", "MilligramsPerMicroliter", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.MilligramPerMilliliter, "MilligramPerMilliliter", "MilligramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Milligram)); - yield return new (MassConcentrationUnit.NanogramPerDeciliter, "NanogramPerDeciliter", "NanogramsPerDeciliter", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.NanogramPerLiter, "NanogramPerLiter", "NanogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Nanogram)); - yield return new (MassConcentrationUnit.NanogramPerMicroliter, "NanogramPerMicroliter", "NanogramsPerMicroliter", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.NanogramPerMilliliter, "NanogramPerMilliliter", "NanogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Nanogram)); - yield return new (MassConcentrationUnit.OuncePerImperialGallon, "OuncePerImperialGallon", "OuncesPerImperialGallon", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.OuncePerUSGallon, "OuncePerUSGallon", "OuncesPerUSGallon", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.PicogramPerDeciliter, "PicogramPerDeciliter", "PicogramsPerDeciliter", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.PicogramPerLiter, "PicogramPerLiter", "PicogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Picogram)); - yield return new (MassConcentrationUnit.PicogramPerMicroliter, "PicogramPerMicroliter", "PicogramsPerMicroliter", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.PicogramPerMilliliter, "PicogramPerMilliliter", "PicogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Picogram)); - yield return new (MassConcentrationUnit.PoundPerCubicFoot, "PoundPerCubicFoot", "PoundsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound)); - yield return new (MassConcentrationUnit.PoundPerCubicInch, "PoundPerCubicInch", "PoundsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound)); - yield return new (MassConcentrationUnit.PoundPerImperialGallon, "PoundPerImperialGallon", "PoundsPerImperialGallon", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.PoundPerUSGallon, "PoundPerUSGallon", "PoundsPerUSGallon", BaseUnits.Undefined); - yield return new (MassConcentrationUnit.SlugPerCubicFoot, "SlugPerCubicFoot", "SlugsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Slug)); - yield return new (MassConcentrationUnit.TonnePerCubicCentimeter, "TonnePerCubicCentimeter", "TonnesPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Tonne)); - yield return new (MassConcentrationUnit.TonnePerCubicMeter, "TonnePerCubicMeter", "TonnesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Tonne)); - yield return new (MassConcentrationUnit.TonnePerCubicMillimeter, "TonnePerCubicMillimeter", "TonnesPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Tonne)); + yield return new (MassConcentrationUnit.KilogramPerCubicMillimeter, "KilogramPerCubicMillimeter", "KilogramsPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram), + new QuantityValue(1, 1000000000) + ); + yield return new (MassConcentrationUnit.KilogramPerLiter, "KilogramPerLiter", "KilogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram), + new QuantityValue(1, 1000) + ); + yield return new (MassConcentrationUnit.KilopoundPerCubicFoot, "KilopoundPerCubicFoot", "KilopoundsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Kilopound), + new QuantityValue(221225364, 3543690390625) + ); + yield return new (MassConcentrationUnit.KilopoundPerCubicInch, "KilopoundPerCubicInch", "KilopoundsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Kilopound), + new QuantityValue(2048383, 56699046250000) + ); + yield return new (MassConcentrationUnit.MicrogramPerCubicMeter, "MicrogramPerCubicMeter", "MicrogramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram), + 1000000000 + ); + yield return new (MassConcentrationUnit.MicrogramPerDeciliter, "MicrogramPerDeciliter", "MicrogramsPerDeciliter", BaseUnits.Undefined, + 100000 + ); + yield return new (MassConcentrationUnit.MicrogramPerLiter, "MicrogramPerLiter", "MicrogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Microgram), + 1000000 + ); + yield return new (MassConcentrationUnit.MicrogramPerMicroliter, "MicrogramPerMicroliter", "MicrogramsPerMicroliter", BaseUnits.Undefined, + 1 + ); + yield return new (MassConcentrationUnit.MicrogramPerMilliliter, "MicrogramPerMilliliter", "MicrogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Microgram), + 1000 + ); + yield return new (MassConcentrationUnit.MilligramPerCubicMeter, "MilligramPerCubicMeter", "MilligramsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram), + 1000000 + ); + yield return new (MassConcentrationUnit.MilligramPerDeciliter, "MilligramPerDeciliter", "MilligramsPerDeciliter", BaseUnits.Undefined, + 100 + ); + yield return new (MassConcentrationUnit.MilligramPerLiter, "MilligramPerLiter", "MilligramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Milligram), + 1000 + ); + yield return new (MassConcentrationUnit.MilligramPerMicroliter, "MilligramPerMicroliter", "MilligramsPerMicroliter", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (MassConcentrationUnit.MilligramPerMilliliter, "MilligramPerMilliliter", "MilligramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Milligram), + 1 + ); + yield return new (MassConcentrationUnit.NanogramPerDeciliter, "NanogramPerDeciliter", "NanogramsPerDeciliter", BaseUnits.Undefined, + 100000000 + ); + yield return new (MassConcentrationUnit.NanogramPerLiter, "NanogramPerLiter", "NanogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Nanogram), + 1000000000 + ); + yield return new (MassConcentrationUnit.NanogramPerMicroliter, "NanogramPerMicroliter", "NanogramsPerMicroliter", BaseUnits.Undefined, + 1000 + ); + yield return new (MassConcentrationUnit.NanogramPerMilliliter, "NanogramPerMilliliter", "NanogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Nanogram), + 1000000 + ); + yield return new (MassConcentrationUnit.OuncePerImperialGallon, "OuncePerImperialGallon", "OuncesPerImperialGallon", BaseUnits.Undefined, + new QuantityValue(7273744, 45359237) + ); + yield return new (MassConcentrationUnit.OuncePerUSGallon, "OuncePerUSGallon", "OuncesPerUSGallon", BaseUnits.Undefined, + new QuantityValue(49161192, 368175625) + ); + yield return new (MassConcentrationUnit.PicogramPerDeciliter, "PicogramPerDeciliter", "PicogramsPerDeciliter", BaseUnits.Undefined, + 100000000000 + ); + yield return new (MassConcentrationUnit.PicogramPerLiter, "PicogramPerLiter", "PicogramsPerLiter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Picogram), + 1000000000000 + ); + yield return new (MassConcentrationUnit.PicogramPerMicroliter, "PicogramPerMicroliter", "PicogramsPerMicroliter", BaseUnits.Undefined, + 1000000 + ); + yield return new (MassConcentrationUnit.PicogramPerMilliliter, "PicogramPerMilliliter", "PicogramsPerMilliliter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Picogram), + 1000000000 + ); + yield return new (MassConcentrationUnit.PoundPerCubicFoot, "PoundPerCubicFoot", "PoundsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound), + new QuantityValue(1769802912, 28349523125) + ); + yield return new (MassConcentrationUnit.PoundPerCubicInch, "PoundPerCubicInch", "PoundsPerCubicInch", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound), + new QuantityValue(2048383, 56699046250) + ); + yield return new (MassConcentrationUnit.PoundPerImperialGallon, "PoundPerImperialGallon", "PoundsPerImperialGallon", BaseUnits.Undefined, + new QuantityValue(454609, 45359237) + ); + yield return new (MassConcentrationUnit.PoundPerUSGallon, "PoundPerUSGallon", "PoundsPerUSGallon", BaseUnits.Undefined, + new QuantityValue(6145149, 736351250) + ); + yield return new (MassConcentrationUnit.SlugPerCubicFoot, "SlugPerCubicFoot", "SlugsPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Slug), + new QuantityValue(10788718551552, 5560277019075625) + ); + yield return new (MassConcentrationUnit.TonnePerCubicCentimeter, "TonnePerCubicCentimeter", "TonnesPerCubicCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Tonne), + new QuantityValue(1, 1000000000) + ); + yield return new (MassConcentrationUnit.TonnePerCubicMeter, "TonnePerCubicMeter", "TonnesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Tonne), + new QuantityValue(1, 1000) + ); + yield return new (MassConcentrationUnit.TonnePerCubicMillimeter, "TonnePerCubicMillimeter", "TonnesPerCubicMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Tonne), + new QuantityValue(1, 1000000000000) + ); } } static MassConcentration() { - Info = MassConcentrationInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MassConcentrationInfo.CreateDefault); } /// @@ -190,7 +283,7 @@ static MassConcentration() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public MassConcentration(double value, MassConcentrationUnit unit) + public MassConcentration(QuantityValue value, MassConcentrationUnit unit) { _value = value; _unit = unit; @@ -204,7 +297,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -215,7 +308,8 @@ public MassConcentration(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -244,10 +338,8 @@ public MassConcentration(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public MassConcentrationUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -286,364 +378,254 @@ public MassConcentration(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentigramsPerDeciliter => As(MassConcentrationUnit.CentigramPerDeciliter); + public QuantityValue CentigramsPerDeciliter => this.As(MassConcentrationUnit.CentigramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentigramsPerLiter => As(MassConcentrationUnit.CentigramPerLiter); + public QuantityValue CentigramsPerLiter => this.As(MassConcentrationUnit.CentigramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentigramsPerMicroliter => As(MassConcentrationUnit.CentigramPerMicroliter); + public QuantityValue CentigramsPerMicroliter => this.As(MassConcentrationUnit.CentigramPerMicroliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentigramsPerMilliliter => As(MassConcentrationUnit.CentigramPerMilliliter); + public QuantityValue CentigramsPerMilliliter => this.As(MassConcentrationUnit.CentigramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecigramsPerDeciliter => As(MassConcentrationUnit.DecigramPerDeciliter); + public QuantityValue DecigramsPerDeciliter => this.As(MassConcentrationUnit.DecigramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecigramsPerLiter => As(MassConcentrationUnit.DecigramPerLiter); + public QuantityValue DecigramsPerLiter => this.As(MassConcentrationUnit.DecigramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecigramsPerMicroliter => As(MassConcentrationUnit.DecigramPerMicroliter); + public QuantityValue DecigramsPerMicroliter => this.As(MassConcentrationUnit.DecigramPerMicroliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecigramsPerMilliliter => As(MassConcentrationUnit.DecigramPerMilliliter); + public QuantityValue DecigramsPerMilliliter => this.As(MassConcentrationUnit.DecigramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerCubicCentimeter => As(MassConcentrationUnit.GramPerCubicCentimeter); + public QuantityValue GramsPerCubicCentimeter => this.As(MassConcentrationUnit.GramPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerCubicMeter => As(MassConcentrationUnit.GramPerCubicMeter); + public QuantityValue GramsPerCubicMeter => this.As(MassConcentrationUnit.GramPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerCubicMillimeter => As(MassConcentrationUnit.GramPerCubicMillimeter); + public QuantityValue GramsPerCubicMillimeter => this.As(MassConcentrationUnit.GramPerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerDeciliter => As(MassConcentrationUnit.GramPerDeciliter); + public QuantityValue GramsPerDeciliter => this.As(MassConcentrationUnit.GramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerLiter => As(MassConcentrationUnit.GramPerLiter); + public QuantityValue GramsPerLiter => this.As(MassConcentrationUnit.GramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerMicroliter => As(MassConcentrationUnit.GramPerMicroliter); + public QuantityValue GramsPerMicroliter => this.As(MassConcentrationUnit.GramPerMicroliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerMilliliter => As(MassConcentrationUnit.GramPerMilliliter); + public QuantityValue GramsPerMilliliter => this.As(MassConcentrationUnit.GramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerCubicCentimeter => As(MassConcentrationUnit.KilogramPerCubicCentimeter); + public QuantityValue KilogramsPerCubicCentimeter => this.As(MassConcentrationUnit.KilogramPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerCubicMeter => As(MassConcentrationUnit.KilogramPerCubicMeter); + public QuantityValue KilogramsPerCubicMeter => this.As(MassConcentrationUnit.KilogramPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerCubicMillimeter => As(MassConcentrationUnit.KilogramPerCubicMillimeter); + public QuantityValue KilogramsPerCubicMillimeter => this.As(MassConcentrationUnit.KilogramPerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerLiter => As(MassConcentrationUnit.KilogramPerLiter); + public QuantityValue KilogramsPerLiter => this.As(MassConcentrationUnit.KilogramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsPerCubicFoot => As(MassConcentrationUnit.KilopoundPerCubicFoot); + public QuantityValue KilopoundsPerCubicFoot => this.As(MassConcentrationUnit.KilopoundPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsPerCubicInch => As(MassConcentrationUnit.KilopoundPerCubicInch); + public QuantityValue KilopoundsPerCubicInch => this.As(MassConcentrationUnit.KilopoundPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerCubicMeter => As(MassConcentrationUnit.MicrogramPerCubicMeter); + public QuantityValue MicrogramsPerCubicMeter => this.As(MassConcentrationUnit.MicrogramPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerDeciliter => As(MassConcentrationUnit.MicrogramPerDeciliter); + public QuantityValue MicrogramsPerDeciliter => this.As(MassConcentrationUnit.MicrogramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerLiter => As(MassConcentrationUnit.MicrogramPerLiter); + public QuantityValue MicrogramsPerLiter => this.As(MassConcentrationUnit.MicrogramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerMicroliter => As(MassConcentrationUnit.MicrogramPerMicroliter); + public QuantityValue MicrogramsPerMicroliter => this.As(MassConcentrationUnit.MicrogramPerMicroliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerMilliliter => As(MassConcentrationUnit.MicrogramPerMilliliter); + public QuantityValue MicrogramsPerMilliliter => this.As(MassConcentrationUnit.MicrogramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerCubicMeter => As(MassConcentrationUnit.MilligramPerCubicMeter); + public QuantityValue MilligramsPerCubicMeter => this.As(MassConcentrationUnit.MilligramPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerDeciliter => As(MassConcentrationUnit.MilligramPerDeciliter); + public QuantityValue MilligramsPerDeciliter => this.As(MassConcentrationUnit.MilligramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerLiter => As(MassConcentrationUnit.MilligramPerLiter); + public QuantityValue MilligramsPerLiter => this.As(MassConcentrationUnit.MilligramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerMicroliter => As(MassConcentrationUnit.MilligramPerMicroliter); + public QuantityValue MilligramsPerMicroliter => this.As(MassConcentrationUnit.MilligramPerMicroliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerMilliliter => As(MassConcentrationUnit.MilligramPerMilliliter); + public QuantityValue MilligramsPerMilliliter => this.As(MassConcentrationUnit.MilligramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanogramsPerDeciliter => As(MassConcentrationUnit.NanogramPerDeciliter); + public QuantityValue NanogramsPerDeciliter => this.As(MassConcentrationUnit.NanogramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanogramsPerLiter => As(MassConcentrationUnit.NanogramPerLiter); + public QuantityValue NanogramsPerLiter => this.As(MassConcentrationUnit.NanogramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanogramsPerMicroliter => As(MassConcentrationUnit.NanogramPerMicroliter); + public QuantityValue NanogramsPerMicroliter => this.As(MassConcentrationUnit.NanogramPerMicroliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanogramsPerMilliliter => As(MassConcentrationUnit.NanogramPerMilliliter); + public QuantityValue NanogramsPerMilliliter => this.As(MassConcentrationUnit.NanogramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double OuncesPerImperialGallon => As(MassConcentrationUnit.OuncePerImperialGallon); + public QuantityValue OuncesPerImperialGallon => this.As(MassConcentrationUnit.OuncePerImperialGallon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double OuncesPerUSGallon => As(MassConcentrationUnit.OuncePerUSGallon); + public QuantityValue OuncesPerUSGallon => this.As(MassConcentrationUnit.OuncePerUSGallon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicogramsPerDeciliter => As(MassConcentrationUnit.PicogramPerDeciliter); + public QuantityValue PicogramsPerDeciliter => this.As(MassConcentrationUnit.PicogramPerDeciliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicogramsPerLiter => As(MassConcentrationUnit.PicogramPerLiter); + public QuantityValue PicogramsPerLiter => this.As(MassConcentrationUnit.PicogramPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicogramsPerMicroliter => As(MassConcentrationUnit.PicogramPerMicroliter); + public QuantityValue PicogramsPerMicroliter => this.As(MassConcentrationUnit.PicogramPerMicroliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicogramsPerMilliliter => As(MassConcentrationUnit.PicogramPerMilliliter); + public QuantityValue PicogramsPerMilliliter => this.As(MassConcentrationUnit.PicogramPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerCubicFoot => As(MassConcentrationUnit.PoundPerCubicFoot); + public QuantityValue PoundsPerCubicFoot => this.As(MassConcentrationUnit.PoundPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerCubicInch => As(MassConcentrationUnit.PoundPerCubicInch); + public QuantityValue PoundsPerCubicInch => this.As(MassConcentrationUnit.PoundPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerImperialGallon => As(MassConcentrationUnit.PoundPerImperialGallon); + public QuantityValue PoundsPerImperialGallon => this.As(MassConcentrationUnit.PoundPerImperialGallon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerUSGallon => As(MassConcentrationUnit.PoundPerUSGallon); + public QuantityValue PoundsPerUSGallon => this.As(MassConcentrationUnit.PoundPerUSGallon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SlugsPerCubicFoot => As(MassConcentrationUnit.SlugPerCubicFoot); + public QuantityValue SlugsPerCubicFoot => this.As(MassConcentrationUnit.SlugPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesPerCubicCentimeter => As(MassConcentrationUnit.TonnePerCubicCentimeter); + public QuantityValue TonnesPerCubicCentimeter => this.As(MassConcentrationUnit.TonnePerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesPerCubicMeter => As(MassConcentrationUnit.TonnePerCubicMeter); + public QuantityValue TonnesPerCubicMeter => this.As(MassConcentrationUnit.TonnePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesPerCubicMillimeter => As(MassConcentrationUnit.TonnePerCubicMillimeter); + public QuantityValue TonnesPerCubicMillimeter => this.As(MassConcentrationUnit.TonnePerCubicMillimeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: MassConcentrationUnit -> BaseUnit - unitConverter.SetConversionFunction(MassConcentrationUnit.CentigramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.CentigramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.CentigramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.CentigramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.DecigramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.DecigramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.DecigramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.DecigramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.GramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilopoundPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilopoundPerCubicInch, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.MicrogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.MicrogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.MicrogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.MicrogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.MicrogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.MilligramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.MilligramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.MilligramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.MilligramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.MilligramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.NanogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.NanogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.NanogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.NanogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.OuncePerImperialGallon, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.OuncePerUSGallon, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.PicogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.PicogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.PicogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.PicogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.PoundPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.PoundPerCubicInch, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.PoundPerImperialGallon, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.PoundPerUSGallon, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.SlugPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.TonnePerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.TonnePerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.TonnePerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> MassConcentrationUnit - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.CentigramPerDeciliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.CentigramPerLiter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.CentigramPerMicroliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.CentigramPerMilliliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.DecigramPerDeciliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.DecigramPerLiter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.DecigramPerMicroliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.DecigramPerMilliliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicCentimeter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerCubicCentimeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicMillimeter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerCubicMillimeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerDeciliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerLiter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerMicroliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.GramPerMilliliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicCentimeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicCentimeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMillimeter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerCubicMillimeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.KilogramPerLiter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilopoundPerCubicFoot, quantity => quantity.ToUnit(MassConcentrationUnit.KilopoundPerCubicFoot)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilopoundPerCubicInch, quantity => quantity.ToUnit(MassConcentrationUnit.KilopoundPerCubicInch)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.MicrogramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.MicrogramPerDeciliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.MicrogramPerLiter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.MicrogramPerMicroliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.MicrogramPerMilliliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.MilligramPerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.MilligramPerDeciliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.MilligramPerLiter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.MilligramPerMicroliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.MilligramPerMilliliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.NanogramPerDeciliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.NanogramPerLiter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.NanogramPerMicroliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.NanogramPerMilliliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.OuncePerImperialGallon, quantity => quantity.ToUnit(MassConcentrationUnit.OuncePerImperialGallon)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.OuncePerUSGallon, quantity => quantity.ToUnit(MassConcentrationUnit.OuncePerUSGallon)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerDeciliter, quantity => quantity.ToUnit(MassConcentrationUnit.PicogramPerDeciliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerLiter, quantity => quantity.ToUnit(MassConcentrationUnit.PicogramPerLiter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerMicroliter, quantity => quantity.ToUnit(MassConcentrationUnit.PicogramPerMicroliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerMilliliter, quantity => quantity.ToUnit(MassConcentrationUnit.PicogramPerMilliliter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerCubicFoot, quantity => quantity.ToUnit(MassConcentrationUnit.PoundPerCubicFoot)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerCubicInch, quantity => quantity.ToUnit(MassConcentrationUnit.PoundPerCubicInch)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerImperialGallon, quantity => quantity.ToUnit(MassConcentrationUnit.PoundPerImperialGallon)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerUSGallon, quantity => quantity.ToUnit(MassConcentrationUnit.PoundPerUSGallon)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.SlugPerCubicFoot, quantity => quantity.ToUnit(MassConcentrationUnit.SlugPerCubicFoot)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicCentimeter, quantity => quantity.ToUnit(MassConcentrationUnit.TonnePerCubicCentimeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicMeter, quantity => quantity.ToUnit(MassConcentrationUnit.TonnePerCubicMeter)); - unitConverter.SetConversionFunction(MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicMillimeter, quantity => quantity.ToUnit(MassConcentrationUnit.TonnePerCubicMillimeter)); - } - /// /// Get unit abbreviation string. /// @@ -672,7 +654,7 @@ public static string GetAbbreviation(MassConcentrationUnit unit, IFormatProvider /// /// Creates a from . /// - public static MassConcentration FromCentigramsPerDeciliter(double value) + public static MassConcentration FromCentigramsPerDeciliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.CentigramPerDeciliter); } @@ -680,7 +662,7 @@ public static MassConcentration FromCentigramsPerDeciliter(double value) /// /// Creates a from . /// - public static MassConcentration FromCentigramsPerLiter(double value) + public static MassConcentration FromCentigramsPerLiter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.CentigramPerLiter); } @@ -688,7 +670,7 @@ public static MassConcentration FromCentigramsPerLiter(double value) /// /// Creates a from . /// - public static MassConcentration FromCentigramsPerMicroliter(double value) + public static MassConcentration FromCentigramsPerMicroliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.CentigramPerMicroliter); } @@ -696,7 +678,7 @@ public static MassConcentration FromCentigramsPerMicroliter(double value) /// /// Creates a from . /// - public static MassConcentration FromCentigramsPerMilliliter(double value) + public static MassConcentration FromCentigramsPerMilliliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.CentigramPerMilliliter); } @@ -704,7 +686,7 @@ public static MassConcentration FromCentigramsPerMilliliter(double value) /// /// Creates a from . /// - public static MassConcentration FromDecigramsPerDeciliter(double value) + public static MassConcentration FromDecigramsPerDeciliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.DecigramPerDeciliter); } @@ -712,7 +694,7 @@ public static MassConcentration FromDecigramsPerDeciliter(double value) /// /// Creates a from . /// - public static MassConcentration FromDecigramsPerLiter(double value) + public static MassConcentration FromDecigramsPerLiter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.DecigramPerLiter); } @@ -720,7 +702,7 @@ public static MassConcentration FromDecigramsPerLiter(double value) /// /// Creates a from . /// - public static MassConcentration FromDecigramsPerMicroliter(double value) + public static MassConcentration FromDecigramsPerMicroliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.DecigramPerMicroliter); } @@ -728,7 +710,7 @@ public static MassConcentration FromDecigramsPerMicroliter(double value) /// /// Creates a from . /// - public static MassConcentration FromDecigramsPerMilliliter(double value) + public static MassConcentration FromDecigramsPerMilliliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.DecigramPerMilliliter); } @@ -736,7 +718,7 @@ public static MassConcentration FromDecigramsPerMilliliter(double value) /// /// Creates a from . /// - public static MassConcentration FromGramsPerCubicCentimeter(double value) + public static MassConcentration FromGramsPerCubicCentimeter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.GramPerCubicCentimeter); } @@ -744,7 +726,7 @@ public static MassConcentration FromGramsPerCubicCentimeter(double value) /// /// Creates a from . /// - public static MassConcentration FromGramsPerCubicMeter(double value) + public static MassConcentration FromGramsPerCubicMeter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.GramPerCubicMeter); } @@ -752,7 +734,7 @@ public static MassConcentration FromGramsPerCubicMeter(double value) /// /// Creates a from . /// - public static MassConcentration FromGramsPerCubicMillimeter(double value) + public static MassConcentration FromGramsPerCubicMillimeter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.GramPerCubicMillimeter); } @@ -760,7 +742,7 @@ public static MassConcentration FromGramsPerCubicMillimeter(double value) /// /// Creates a from . /// - public static MassConcentration FromGramsPerDeciliter(double value) + public static MassConcentration FromGramsPerDeciliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.GramPerDeciliter); } @@ -768,7 +750,7 @@ public static MassConcentration FromGramsPerDeciliter(double value) /// /// Creates a from . /// - public static MassConcentration FromGramsPerLiter(double value) + public static MassConcentration FromGramsPerLiter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.GramPerLiter); } @@ -776,7 +758,7 @@ public static MassConcentration FromGramsPerLiter(double value) /// /// Creates a from . /// - public static MassConcentration FromGramsPerMicroliter(double value) + public static MassConcentration FromGramsPerMicroliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.GramPerMicroliter); } @@ -784,7 +766,7 @@ public static MassConcentration FromGramsPerMicroliter(double value) /// /// Creates a from . /// - public static MassConcentration FromGramsPerMilliliter(double value) + public static MassConcentration FromGramsPerMilliliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.GramPerMilliliter); } @@ -792,7 +774,7 @@ public static MassConcentration FromGramsPerMilliliter(double value) /// /// Creates a from . /// - public static MassConcentration FromKilogramsPerCubicCentimeter(double value) + public static MassConcentration FromKilogramsPerCubicCentimeter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.KilogramPerCubicCentimeter); } @@ -800,7 +782,7 @@ public static MassConcentration FromKilogramsPerCubicCentimeter(double value) /// /// Creates a from . /// - public static MassConcentration FromKilogramsPerCubicMeter(double value) + public static MassConcentration FromKilogramsPerCubicMeter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.KilogramPerCubicMeter); } @@ -808,7 +790,7 @@ public static MassConcentration FromKilogramsPerCubicMeter(double value) /// /// Creates a from . /// - public static MassConcentration FromKilogramsPerCubicMillimeter(double value) + public static MassConcentration FromKilogramsPerCubicMillimeter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.KilogramPerCubicMillimeter); } @@ -816,7 +798,7 @@ public static MassConcentration FromKilogramsPerCubicMillimeter(double value) /// /// Creates a from . /// - public static MassConcentration FromKilogramsPerLiter(double value) + public static MassConcentration FromKilogramsPerLiter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.KilogramPerLiter); } @@ -824,7 +806,7 @@ public static MassConcentration FromKilogramsPerLiter(double value) /// /// Creates a from . /// - public static MassConcentration FromKilopoundsPerCubicFoot(double value) + public static MassConcentration FromKilopoundsPerCubicFoot(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.KilopoundPerCubicFoot); } @@ -832,7 +814,7 @@ public static MassConcentration FromKilopoundsPerCubicFoot(double value) /// /// Creates a from . /// - public static MassConcentration FromKilopoundsPerCubicInch(double value) + public static MassConcentration FromKilopoundsPerCubicInch(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.KilopoundPerCubicInch); } @@ -840,7 +822,7 @@ public static MassConcentration FromKilopoundsPerCubicInch(double value) /// /// Creates a from . /// - public static MassConcentration FromMicrogramsPerCubicMeter(double value) + public static MassConcentration FromMicrogramsPerCubicMeter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.MicrogramPerCubicMeter); } @@ -848,7 +830,7 @@ public static MassConcentration FromMicrogramsPerCubicMeter(double value) /// /// Creates a from . /// - public static MassConcentration FromMicrogramsPerDeciliter(double value) + public static MassConcentration FromMicrogramsPerDeciliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.MicrogramPerDeciliter); } @@ -856,7 +838,7 @@ public static MassConcentration FromMicrogramsPerDeciliter(double value) /// /// Creates a from . /// - public static MassConcentration FromMicrogramsPerLiter(double value) + public static MassConcentration FromMicrogramsPerLiter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.MicrogramPerLiter); } @@ -864,7 +846,7 @@ public static MassConcentration FromMicrogramsPerLiter(double value) /// /// Creates a from . /// - public static MassConcentration FromMicrogramsPerMicroliter(double value) + public static MassConcentration FromMicrogramsPerMicroliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.MicrogramPerMicroliter); } @@ -872,7 +854,7 @@ public static MassConcentration FromMicrogramsPerMicroliter(double value) /// /// Creates a from . /// - public static MassConcentration FromMicrogramsPerMilliliter(double value) + public static MassConcentration FromMicrogramsPerMilliliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.MicrogramPerMilliliter); } @@ -880,7 +862,7 @@ public static MassConcentration FromMicrogramsPerMilliliter(double value) /// /// Creates a from . /// - public static MassConcentration FromMilligramsPerCubicMeter(double value) + public static MassConcentration FromMilligramsPerCubicMeter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.MilligramPerCubicMeter); } @@ -888,7 +870,7 @@ public static MassConcentration FromMilligramsPerCubicMeter(double value) /// /// Creates a from . /// - public static MassConcentration FromMilligramsPerDeciliter(double value) + public static MassConcentration FromMilligramsPerDeciliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.MilligramPerDeciliter); } @@ -896,7 +878,7 @@ public static MassConcentration FromMilligramsPerDeciliter(double value) /// /// Creates a from . /// - public static MassConcentration FromMilligramsPerLiter(double value) + public static MassConcentration FromMilligramsPerLiter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.MilligramPerLiter); } @@ -904,7 +886,7 @@ public static MassConcentration FromMilligramsPerLiter(double value) /// /// Creates a from . /// - public static MassConcentration FromMilligramsPerMicroliter(double value) + public static MassConcentration FromMilligramsPerMicroliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.MilligramPerMicroliter); } @@ -912,7 +894,7 @@ public static MassConcentration FromMilligramsPerMicroliter(double value) /// /// Creates a from . /// - public static MassConcentration FromMilligramsPerMilliliter(double value) + public static MassConcentration FromMilligramsPerMilliliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.MilligramPerMilliliter); } @@ -920,7 +902,7 @@ public static MassConcentration FromMilligramsPerMilliliter(double value) /// /// Creates a from . /// - public static MassConcentration FromNanogramsPerDeciliter(double value) + public static MassConcentration FromNanogramsPerDeciliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.NanogramPerDeciliter); } @@ -928,7 +910,7 @@ public static MassConcentration FromNanogramsPerDeciliter(double value) /// /// Creates a from . /// - public static MassConcentration FromNanogramsPerLiter(double value) + public static MassConcentration FromNanogramsPerLiter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.NanogramPerLiter); } @@ -936,7 +918,7 @@ public static MassConcentration FromNanogramsPerLiter(double value) /// /// Creates a from . /// - public static MassConcentration FromNanogramsPerMicroliter(double value) + public static MassConcentration FromNanogramsPerMicroliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.NanogramPerMicroliter); } @@ -944,7 +926,7 @@ public static MassConcentration FromNanogramsPerMicroliter(double value) /// /// Creates a from . /// - public static MassConcentration FromNanogramsPerMilliliter(double value) + public static MassConcentration FromNanogramsPerMilliliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.NanogramPerMilliliter); } @@ -952,7 +934,7 @@ public static MassConcentration FromNanogramsPerMilliliter(double value) /// /// Creates a from . /// - public static MassConcentration FromOuncesPerImperialGallon(double value) + public static MassConcentration FromOuncesPerImperialGallon(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.OuncePerImperialGallon); } @@ -960,7 +942,7 @@ public static MassConcentration FromOuncesPerImperialGallon(double value) /// /// Creates a from . /// - public static MassConcentration FromOuncesPerUSGallon(double value) + public static MassConcentration FromOuncesPerUSGallon(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.OuncePerUSGallon); } @@ -968,7 +950,7 @@ public static MassConcentration FromOuncesPerUSGallon(double value) /// /// Creates a from . /// - public static MassConcentration FromPicogramsPerDeciliter(double value) + public static MassConcentration FromPicogramsPerDeciliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.PicogramPerDeciliter); } @@ -976,7 +958,7 @@ public static MassConcentration FromPicogramsPerDeciliter(double value) /// /// Creates a from . /// - public static MassConcentration FromPicogramsPerLiter(double value) + public static MassConcentration FromPicogramsPerLiter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.PicogramPerLiter); } @@ -984,7 +966,7 @@ public static MassConcentration FromPicogramsPerLiter(double value) /// /// Creates a from . /// - public static MassConcentration FromPicogramsPerMicroliter(double value) + public static MassConcentration FromPicogramsPerMicroliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.PicogramPerMicroliter); } @@ -992,7 +974,7 @@ public static MassConcentration FromPicogramsPerMicroliter(double value) /// /// Creates a from . /// - public static MassConcentration FromPicogramsPerMilliliter(double value) + public static MassConcentration FromPicogramsPerMilliliter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.PicogramPerMilliliter); } @@ -1000,7 +982,7 @@ public static MassConcentration FromPicogramsPerMilliliter(double value) /// /// Creates a from . /// - public static MassConcentration FromPoundsPerCubicFoot(double value) + public static MassConcentration FromPoundsPerCubicFoot(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.PoundPerCubicFoot); } @@ -1008,7 +990,7 @@ public static MassConcentration FromPoundsPerCubicFoot(double value) /// /// Creates a from . /// - public static MassConcentration FromPoundsPerCubicInch(double value) + public static MassConcentration FromPoundsPerCubicInch(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.PoundPerCubicInch); } @@ -1016,7 +998,7 @@ public static MassConcentration FromPoundsPerCubicInch(double value) /// /// Creates a from . /// - public static MassConcentration FromPoundsPerImperialGallon(double value) + public static MassConcentration FromPoundsPerImperialGallon(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.PoundPerImperialGallon); } @@ -1024,7 +1006,7 @@ public static MassConcentration FromPoundsPerImperialGallon(double value) /// /// Creates a from . /// - public static MassConcentration FromPoundsPerUSGallon(double value) + public static MassConcentration FromPoundsPerUSGallon(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.PoundPerUSGallon); } @@ -1032,7 +1014,7 @@ public static MassConcentration FromPoundsPerUSGallon(double value) /// /// Creates a from . /// - public static MassConcentration FromSlugsPerCubicFoot(double value) + public static MassConcentration FromSlugsPerCubicFoot(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.SlugPerCubicFoot); } @@ -1040,7 +1022,7 @@ public static MassConcentration FromSlugsPerCubicFoot(double value) /// /// Creates a from . /// - public static MassConcentration FromTonnesPerCubicCentimeter(double value) + public static MassConcentration FromTonnesPerCubicCentimeter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.TonnePerCubicCentimeter); } @@ -1048,7 +1030,7 @@ public static MassConcentration FromTonnesPerCubicCentimeter(double value) /// /// Creates a from . /// - public static MassConcentration FromTonnesPerCubicMeter(double value) + public static MassConcentration FromTonnesPerCubicMeter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.TonnePerCubicMeter); } @@ -1056,7 +1038,7 @@ public static MassConcentration FromTonnesPerCubicMeter(double value) /// /// Creates a from . /// - public static MassConcentration FromTonnesPerCubicMillimeter(double value) + public static MassConcentration FromTonnesPerCubicMillimeter(QuantityValue value) { return new MassConcentration(value, MassConcentrationUnit.TonnePerCubicMillimeter); } @@ -1067,7 +1049,7 @@ public static MassConcentration FromTonnesPerCubicMillimeter(double value) /// Value to convert from. /// Unit to convert from. /// MassConcentration unit value. - public static MassConcentration From(double value, MassConcentrationUnit fromUnit) + public static MassConcentration From(QuantityValue value, MassConcentrationUnit fromUnit) { return new MassConcentration(value, fromUnit); } @@ -1128,10 +1110,7 @@ public static MassConcentration Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static MassConcentration Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -1159,11 +1138,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out MassConcentratio /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out MassConcentration result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -1184,7 +1159,7 @@ public static MassConcentrationUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -1195,7 +1170,7 @@ public static MassConcentrationUnit ParseUnit(string str, IFormatProvider? provi return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out MassConcentrationUnit unit) { return TryParseUnit(str, null, out unit); @@ -1210,7 +1185,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out MassConcentr /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out MassConcentrationUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -1229,35 +1204,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static MassConcentration operator +(MassConcentration left, MassConcentration right) { - return new MassConcentration(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new MassConcentration(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static MassConcentration operator -(MassConcentration left, MassConcentration right) { - return new MassConcentration(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new MassConcentration(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -1303,97 +1278,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(MassConcentration left, MassConcentration right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(MassConcentration left, MassConcentration right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(MassConcentration left, MassConcentration right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(MassConcentration left, MassConcentration right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MassConcentration other, MassConcentration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(MassConcentration left, MassConcentration right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MassConcentration other, MassConcentration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(MassConcentration left, MassConcentration right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MassConcentration other, MassConcentration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is MassConcentration otherQuantity)) + if (obj is not MassConcentration otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MassConcentration other, MassConcentration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(MassConcentration other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current MassConcentration. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(MassConcentration), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MassConcentration otherQuantity)) throw new ArgumentException("Expected type MassConcentration.", nameof(obj)); + if (obj is not MassConcentration otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1405,242 +1365,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MassConcentration other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassConcentrationUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this MassConcentration to another MassConcentration with the unit representation . - /// - /// The unit to convert to. - /// A MassConcentration with the specified unit. - public MassConcentration ToUnit(MassConcentrationUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A MassConcentration with the specified unit. - public MassConcentration ToUnit(MassConcentrationUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(MassConcentration), Unit, typeof(MassConcentration), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (MassConcentration)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(MassConcentrationUnit unit, [NotNullWhen(true)] out MassConcentration? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - MassConcentration? convertedOrNull = (Unit, unit) switch - { - // MassConcentrationUnit -> BaseUnit - (MassConcentrationUnit.CentigramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-1) * 1e-2d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.CentigramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value) * 1e-2d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.CentigramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-6) * 1e-2d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.CentigramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-3) * 1e-2d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.DecigramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-1) * 1e-1d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.DecigramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value) * 1e-1d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.DecigramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-6) * 1e-1d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.DecigramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-3) * 1e-1d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.GramPerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 1e-3, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.GramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 1e3, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.GramPerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 1e-6, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.GramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 1e-1, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.GramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.GramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 1e-6, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.GramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 1e-3, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.KilogramPerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-3) * 1e3d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.KilogramPerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-6) * 1e3d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.KilogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value) * 1e3d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.KilopoundPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value * 0.45359237 / 0.028316846592) * 1e3d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.KilopoundPerCubicInch, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value * 0.45359237 / 1.6387064e-5) * 1e3d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.MicrogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e3) * 1e-6d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.MicrogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-1) * 1e-6d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.MicrogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value) * 1e-6d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.MicrogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-6) * 1e-6d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.MicrogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-3) * 1e-6d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.MilligramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e3) * 1e-3d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.MilligramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-1) * 1e-3d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.MilligramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value) * 1e-3d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.MilligramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-6) * 1e-3d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.MilligramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-3) * 1e-3d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.NanogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-1) * 1e-9d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.NanogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value) * 1e-9d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.NanogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-6) * 1e-9d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.NanogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-3) * 1e-9d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.OuncePerImperialGallon, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value * 0.028349523125 / 0.00454609, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.OuncePerUSGallon, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value * 0.028349523125 / 0.003785411784, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.PicogramPerDeciliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-1) * 1e-12d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.PicogramPerLiter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value) * 1e-12d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.PicogramPerMicroliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-6) * 1e-12d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.PicogramPerMilliliter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration((_value / 1e-3) * 1e-12d, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.PoundPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value * 0.45359237 / 0.028316846592, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.PoundPerCubicInch, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value * 0.45359237 / 1.6387064e-5, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.PoundPerImperialGallon, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value * 0.45359237 / 0.00454609, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.PoundPerUSGallon, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value * 0.45359237 / 0.003785411784, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.SlugPerCubicFoot, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value * (0.45359237 * 9.80665) / (0.3048 * 0.028316846592), MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.TonnePerCubicCentimeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 1e-9, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.TonnePerCubicMeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 0.001, MassConcentrationUnit.KilogramPerCubicMeter), - (MassConcentrationUnit.TonnePerCubicMillimeter, MassConcentrationUnit.KilogramPerCubicMeter) => new MassConcentration(_value / 1e-12, MassConcentrationUnit.KilogramPerCubicMeter), - - // BaseUnit -> MassConcentrationUnit - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerDeciliter) => new MassConcentration((_value * 1e-1) / 1e-2d, MassConcentrationUnit.CentigramPerDeciliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerLiter) => new MassConcentration((_value) / 1e-2d, MassConcentrationUnit.CentigramPerLiter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerMicroliter) => new MassConcentration((_value * 1e-6) / 1e-2d, MassConcentrationUnit.CentigramPerMicroliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.CentigramPerMilliliter) => new MassConcentration((_value * 1e-3) / 1e-2d, MassConcentrationUnit.CentigramPerMilliliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerDeciliter) => new MassConcentration((_value * 1e-1) / 1e-1d, MassConcentrationUnit.DecigramPerDeciliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerLiter) => new MassConcentration((_value) / 1e-1d, MassConcentrationUnit.DecigramPerLiter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerMicroliter) => new MassConcentration((_value * 1e-6) / 1e-1d, MassConcentrationUnit.DecigramPerMicroliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.DecigramPerMilliliter) => new MassConcentration((_value * 1e-3) / 1e-1d, MassConcentrationUnit.DecigramPerMilliliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicCentimeter) => new MassConcentration(_value * 1e-3, MassConcentrationUnit.GramPerCubicCentimeter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicMeter) => new MassConcentration(_value * 1e3, MassConcentrationUnit.GramPerCubicMeter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerCubicMillimeter) => new MassConcentration(_value * 1e-6, MassConcentrationUnit.GramPerCubicMillimeter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerDeciliter) => new MassConcentration(_value * 1e-1, MassConcentrationUnit.GramPerDeciliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerLiter) => new MassConcentration(_value, MassConcentrationUnit.GramPerLiter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerMicroliter) => new MassConcentration(_value * 1e-6, MassConcentrationUnit.GramPerMicroliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.GramPerMilliliter) => new MassConcentration(_value * 1e-3, MassConcentrationUnit.GramPerMilliliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicCentimeter) => new MassConcentration((_value * 1e-3) / 1e3d, MassConcentrationUnit.KilogramPerCubicCentimeter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerCubicMillimeter) => new MassConcentration((_value * 1e-6) / 1e3d, MassConcentrationUnit.KilogramPerCubicMillimeter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilogramPerLiter) => new MassConcentration((_value) / 1e3d, MassConcentrationUnit.KilogramPerLiter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilopoundPerCubicFoot) => new MassConcentration((_value * 0.028316846592 / 0.45359237) / 1e3d, MassConcentrationUnit.KilopoundPerCubicFoot), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.KilopoundPerCubicInch) => new MassConcentration((_value * 1.6387064e-5 / 0.45359237) / 1e3d, MassConcentrationUnit.KilopoundPerCubicInch), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerCubicMeter) => new MassConcentration((_value * 1e3) / 1e-6d, MassConcentrationUnit.MicrogramPerCubicMeter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerDeciliter) => new MassConcentration((_value * 1e-1) / 1e-6d, MassConcentrationUnit.MicrogramPerDeciliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerLiter) => new MassConcentration((_value) / 1e-6d, MassConcentrationUnit.MicrogramPerLiter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerMicroliter) => new MassConcentration((_value * 1e-6) / 1e-6d, MassConcentrationUnit.MicrogramPerMicroliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MicrogramPerMilliliter) => new MassConcentration((_value * 1e-3) / 1e-6d, MassConcentrationUnit.MicrogramPerMilliliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerCubicMeter) => new MassConcentration((_value * 1e3) / 1e-3d, MassConcentrationUnit.MilligramPerCubicMeter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerDeciliter) => new MassConcentration((_value * 1e-1) / 1e-3d, MassConcentrationUnit.MilligramPerDeciliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerLiter) => new MassConcentration((_value) / 1e-3d, MassConcentrationUnit.MilligramPerLiter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerMicroliter) => new MassConcentration((_value * 1e-6) / 1e-3d, MassConcentrationUnit.MilligramPerMicroliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.MilligramPerMilliliter) => new MassConcentration((_value * 1e-3) / 1e-3d, MassConcentrationUnit.MilligramPerMilliliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerDeciliter) => new MassConcentration((_value * 1e-1) / 1e-9d, MassConcentrationUnit.NanogramPerDeciliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerLiter) => new MassConcentration((_value) / 1e-9d, MassConcentrationUnit.NanogramPerLiter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerMicroliter) => new MassConcentration((_value * 1e-6) / 1e-9d, MassConcentrationUnit.NanogramPerMicroliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.NanogramPerMilliliter) => new MassConcentration((_value * 1e-3) / 1e-9d, MassConcentrationUnit.NanogramPerMilliliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.OuncePerImperialGallon) => new MassConcentration(_value * 0.00454609 / 0.028349523125, MassConcentrationUnit.OuncePerImperialGallon), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.OuncePerUSGallon) => new MassConcentration(_value * 0.003785411784 / 0.028349523125, MassConcentrationUnit.OuncePerUSGallon), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerDeciliter) => new MassConcentration((_value * 1e-1) / 1e-12d, MassConcentrationUnit.PicogramPerDeciliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerLiter) => new MassConcentration((_value) / 1e-12d, MassConcentrationUnit.PicogramPerLiter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerMicroliter) => new MassConcentration((_value * 1e-6) / 1e-12d, MassConcentrationUnit.PicogramPerMicroliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PicogramPerMilliliter) => new MassConcentration((_value * 1e-3) / 1e-12d, MassConcentrationUnit.PicogramPerMilliliter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerCubicFoot) => new MassConcentration(_value * 0.028316846592 / 0.45359237, MassConcentrationUnit.PoundPerCubicFoot), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerCubicInch) => new MassConcentration(_value * 1.6387064e-5 / 0.45359237, MassConcentrationUnit.PoundPerCubicInch), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerImperialGallon) => new MassConcentration(_value * 0.00454609 / 0.45359237, MassConcentrationUnit.PoundPerImperialGallon), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.PoundPerUSGallon) => new MassConcentration(_value * 0.003785411784 / 0.45359237, MassConcentrationUnit.PoundPerUSGallon), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.SlugPerCubicFoot) => new MassConcentration(_value * (0.3048 * 0.028316846592) / (0.45359237 * 9.80665), MassConcentrationUnit.SlugPerCubicFoot), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicCentimeter) => new MassConcentration(_value * 1e-9, MassConcentrationUnit.TonnePerCubicCentimeter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicMeter) => new MassConcentration(_value * 0.001, MassConcentrationUnit.TonnePerCubicMeter), - (MassConcentrationUnit.KilogramPerCubicMeter, MassConcentrationUnit.TonnePerCubicMillimeter) => new MassConcentration(_value * 1e-12, MassConcentrationUnit.TonnePerCubicMillimeter), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public MassConcentration ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not MassConcentrationUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassConcentrationUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(MassConcentrationUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(MassConcentrationUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1655,7 +1397,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs index 6bee66571e..59abfea4a7 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFlow.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct MassFlow : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -62,13 +61,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly MassFlowUnit? _unit; /// @@ -113,7 +112,7 @@ public static MassFlowInfo CreateDefault(Func - /// The for is [T^-1][M]. + /// The for is T^-1M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, -1, 0, 0, 0, 0); @@ -128,47 +127,109 @@ public static MassFlowInfo CreateDefault(FuncAn of representing the default unit mappings for MassFlow. public static IEnumerable> GetDefaultMappings() { - yield return new (MassFlowUnit.CentigramPerDay, "CentigramPerDay", "CentigramsPerDay", new BaseUnits(mass: MassUnit.Centigram, time: DurationUnit.Day)); - yield return new (MassFlowUnit.CentigramPerSecond, "CentigramPerSecond", "CentigramsPerSecond", new BaseUnits(mass: MassUnit.Centigram, time: DurationUnit.Second)); - yield return new (MassFlowUnit.DecagramPerDay, "DecagramPerDay", "DecagramsPerDay", new BaseUnits(mass: MassUnit.Decagram, time: DurationUnit.Day)); - yield return new (MassFlowUnit.DecagramPerSecond, "DecagramPerSecond", "DecagramsPerSecond", new BaseUnits(mass: MassUnit.Decagram, time: DurationUnit.Second)); - yield return new (MassFlowUnit.DecigramPerDay, "DecigramPerDay", "DecigramsPerDay", new BaseUnits(mass: MassUnit.Decigram, time: DurationUnit.Day)); - yield return new (MassFlowUnit.DecigramPerSecond, "DecigramPerSecond", "DecigramsPerSecond", new BaseUnits(mass: MassUnit.Decigram, time: DurationUnit.Second)); - yield return new (MassFlowUnit.GramPerDay, "GramPerDay", "GramsPerDay", new BaseUnits(mass: MassUnit.Gram, time: DurationUnit.Day)); - yield return new (MassFlowUnit.GramPerHour, "GramPerHour", "GramsPerHour", new BaseUnits(mass: MassUnit.Gram, time: DurationUnit.Hour)); + yield return new (MassFlowUnit.CentigramPerDay, "CentigramPerDay", "CentigramsPerDay", new BaseUnits(mass: MassUnit.Centigram, time: DurationUnit.Day), + 8640000 + ); + yield return new (MassFlowUnit.CentigramPerSecond, "CentigramPerSecond", "CentigramsPerSecond", new BaseUnits(mass: MassUnit.Centigram, time: DurationUnit.Second), + 100 + ); + yield return new (MassFlowUnit.DecagramPerDay, "DecagramPerDay", "DecagramsPerDay", new BaseUnits(mass: MassUnit.Decagram, time: DurationUnit.Day), + 8640 + ); + yield return new (MassFlowUnit.DecagramPerSecond, "DecagramPerSecond", "DecagramsPerSecond", new BaseUnits(mass: MassUnit.Decagram, time: DurationUnit.Second), + new QuantityValue(1, 10) + ); + yield return new (MassFlowUnit.DecigramPerDay, "DecigramPerDay", "DecigramsPerDay", new BaseUnits(mass: MassUnit.Decigram, time: DurationUnit.Day), + 864000 + ); + yield return new (MassFlowUnit.DecigramPerSecond, "DecigramPerSecond", "DecigramsPerSecond", new BaseUnits(mass: MassUnit.Decigram, time: DurationUnit.Second), + 10 + ); + yield return new (MassFlowUnit.GramPerDay, "GramPerDay", "GramsPerDay", new BaseUnits(mass: MassUnit.Gram, time: DurationUnit.Day), + 86400 + ); + yield return new (MassFlowUnit.GramPerHour, "GramPerHour", "GramsPerHour", new BaseUnits(mass: MassUnit.Gram, time: DurationUnit.Hour), + 3600 + ); yield return new (MassFlowUnit.GramPerSecond, "GramPerSecond", "GramsPerSecond", new BaseUnits(mass: MassUnit.Gram, time: DurationUnit.Second)); - yield return new (MassFlowUnit.HectogramPerDay, "HectogramPerDay", "HectogramsPerDay", new BaseUnits(mass: MassUnit.Hectogram, time: DurationUnit.Day)); - yield return new (MassFlowUnit.HectogramPerSecond, "HectogramPerSecond", "HectogramsPerSecond", new BaseUnits(mass: MassUnit.Hectogram, time: DurationUnit.Second)); - yield return new (MassFlowUnit.KilogramPerDay, "KilogramPerDay", "KilogramsPerDay", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Day)); - yield return new (MassFlowUnit.KilogramPerHour, "KilogramPerHour", "KilogramsPerHour", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Hour)); - yield return new (MassFlowUnit.KilogramPerMinute, "KilogramPerMinute", "KilogramsPerMinute", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Minute)); - yield return new (MassFlowUnit.KilogramPerSecond, "KilogramPerSecond", "KilogramsPerSecond", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (MassFlowUnit.MegagramPerDay, "MegagramPerDay", "MegagramsPerDay", BaseUnits.Undefined); - yield return new (MassFlowUnit.MegapoundPerDay, "MegapoundPerDay", "MegapoundsPerDay", new BaseUnits(mass: MassUnit.Megapound, time: DurationUnit.Day)); - yield return new (MassFlowUnit.MegapoundPerHour, "MegapoundPerHour", "MegapoundsPerHour", new BaseUnits(mass: MassUnit.Megapound, time: DurationUnit.Hour)); - yield return new (MassFlowUnit.MegapoundPerMinute, "MegapoundPerMinute", "MegapoundsPerMinute", new BaseUnits(mass: MassUnit.Megapound, time: DurationUnit.Minute)); - yield return new (MassFlowUnit.MegapoundPerSecond, "MegapoundPerSecond", "MegapoundsPerSecond", new BaseUnits(mass: MassUnit.Megapound, time: DurationUnit.Second)); - yield return new (MassFlowUnit.MicrogramPerDay, "MicrogramPerDay", "MicrogramsPerDay", new BaseUnits(mass: MassUnit.Microgram, time: DurationUnit.Day)); - yield return new (MassFlowUnit.MicrogramPerSecond, "MicrogramPerSecond", "MicrogramsPerSecond", new BaseUnits(mass: MassUnit.Microgram, time: DurationUnit.Second)); - yield return new (MassFlowUnit.MilligramPerDay, "MilligramPerDay", "MilligramsPerDay", new BaseUnits(mass: MassUnit.Milligram, time: DurationUnit.Day)); - yield return new (MassFlowUnit.MilligramPerSecond, "MilligramPerSecond", "MilligramsPerSecond", new BaseUnits(mass: MassUnit.Milligram, time: DurationUnit.Second)); - yield return new (MassFlowUnit.NanogramPerDay, "NanogramPerDay", "NanogramsPerDay", new BaseUnits(mass: MassUnit.Nanogram, time: DurationUnit.Day)); - yield return new (MassFlowUnit.NanogramPerSecond, "NanogramPerSecond", "NanogramsPerSecond", new BaseUnits(mass: MassUnit.Nanogram, time: DurationUnit.Second)); - yield return new (MassFlowUnit.PoundPerDay, "PoundPerDay", "PoundsPerDay", new BaseUnits(mass: MassUnit.Pound, time: DurationUnit.Day)); - yield return new (MassFlowUnit.PoundPerHour, "PoundPerHour", "PoundsPerHour", new BaseUnits(mass: MassUnit.Pound, time: DurationUnit.Hour)); - yield return new (MassFlowUnit.PoundPerMinute, "PoundPerMinute", "PoundsPerMinute", new BaseUnits(mass: MassUnit.Pound, time: DurationUnit.Minute)); - yield return new (MassFlowUnit.PoundPerSecond, "PoundPerSecond", "PoundsPerSecond", new BaseUnits(mass: MassUnit.Pound, time: DurationUnit.Second)); - yield return new (MassFlowUnit.ShortTonPerHour, "ShortTonPerHour", "ShortTonsPerHour", new BaseUnits(mass: MassUnit.ShortTon, time: DurationUnit.Hour)); - yield return new (MassFlowUnit.TonnePerDay, "TonnePerDay", "TonnesPerDay", new BaseUnits(mass: MassUnit.Tonne, time: DurationUnit.Day)); - yield return new (MassFlowUnit.TonnePerHour, "TonnePerHour", "TonnesPerHour", new BaseUnits(mass: MassUnit.Tonne, time: DurationUnit.Hour)); + yield return new (MassFlowUnit.HectogramPerDay, "HectogramPerDay", "HectogramsPerDay", new BaseUnits(mass: MassUnit.Hectogram, time: DurationUnit.Day), + 864 + ); + yield return new (MassFlowUnit.HectogramPerSecond, "HectogramPerSecond", "HectogramsPerSecond", new BaseUnits(mass: MassUnit.Hectogram, time: DurationUnit.Second), + new QuantityValue(1, 100) + ); + yield return new (MassFlowUnit.KilogramPerDay, "KilogramPerDay", "KilogramsPerDay", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Day), + new QuantityValue(432, 5) + ); + yield return new (MassFlowUnit.KilogramPerHour, "KilogramPerHour", "KilogramsPerHour", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Hour), + new QuantityValue(18, 5) + ); + yield return new (MassFlowUnit.KilogramPerMinute, "KilogramPerMinute", "KilogramsPerMinute", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Minute), + new QuantityValue(3, 50) + ); + yield return new (MassFlowUnit.KilogramPerSecond, "KilogramPerSecond", "KilogramsPerSecond", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000) + ); + yield return new (MassFlowUnit.MegagramPerDay, "MegagramPerDay", "MegagramsPerDay", BaseUnits.Undefined, + new QuantityValue(54, 625) + ); + yield return new (MassFlowUnit.MegapoundPerDay, "MegapoundPerDay", "MegapoundsPerDay", new BaseUnits(mass: MassUnit.Megapound, time: DurationUnit.Day), + new QuantityValue(8640, 45359237) + ); + yield return new (MassFlowUnit.MegapoundPerHour, "MegapoundPerHour", "MegapoundsPerHour", new BaseUnits(mass: MassUnit.Megapound, time: DurationUnit.Hour), + new QuantityValue(360, 45359237) + ); + yield return new (MassFlowUnit.MegapoundPerMinute, "MegapoundPerMinute", "MegapoundsPerMinute", new BaseUnits(mass: MassUnit.Megapound, time: DurationUnit.Minute), + new QuantityValue(6, 45359237) + ); + yield return new (MassFlowUnit.MegapoundPerSecond, "MegapoundPerSecond", "MegapoundsPerSecond", new BaseUnits(mass: MassUnit.Megapound, time: DurationUnit.Second), + new QuantityValue(1, 453592370) + ); + yield return new (MassFlowUnit.MicrogramPerDay, "MicrogramPerDay", "MicrogramsPerDay", new BaseUnits(mass: MassUnit.Microgram, time: DurationUnit.Day), + 86400000000 + ); + yield return new (MassFlowUnit.MicrogramPerSecond, "MicrogramPerSecond", "MicrogramsPerSecond", new BaseUnits(mass: MassUnit.Microgram, time: DurationUnit.Second), + 1000000 + ); + yield return new (MassFlowUnit.MilligramPerDay, "MilligramPerDay", "MilligramsPerDay", new BaseUnits(mass: MassUnit.Milligram, time: DurationUnit.Day), + 86400000 + ); + yield return new (MassFlowUnit.MilligramPerSecond, "MilligramPerSecond", "MilligramsPerSecond", new BaseUnits(mass: MassUnit.Milligram, time: DurationUnit.Second), + 1000 + ); + yield return new (MassFlowUnit.NanogramPerDay, "NanogramPerDay", "NanogramsPerDay", new BaseUnits(mass: MassUnit.Nanogram, time: DurationUnit.Day), + 86400000000000 + ); + yield return new (MassFlowUnit.NanogramPerSecond, "NanogramPerSecond", "NanogramsPerSecond", new BaseUnits(mass: MassUnit.Nanogram, time: DurationUnit.Second), + 1000000000 + ); + yield return new (MassFlowUnit.PoundPerDay, "PoundPerDay", "PoundsPerDay", new BaseUnits(mass: MassUnit.Pound, time: DurationUnit.Day), + new QuantityValue(8640000000, 45359237) + ); + yield return new (MassFlowUnit.PoundPerHour, "PoundPerHour", "PoundsPerHour", new BaseUnits(mass: MassUnit.Pound, time: DurationUnit.Hour), + new QuantityValue(360000000, 45359237) + ); + yield return new (MassFlowUnit.PoundPerMinute, "PoundPerMinute", "PoundsPerMinute", new BaseUnits(mass: MassUnit.Pound, time: DurationUnit.Minute), + new QuantityValue(6000000, 45359237) + ); + yield return new (MassFlowUnit.PoundPerSecond, "PoundPerSecond", "PoundsPerSecond", new BaseUnits(mass: MassUnit.Pound, time: DurationUnit.Second), + new QuantityValue(100000, 45359237) + ); + yield return new (MassFlowUnit.ShortTonPerHour, "ShortTonPerHour", "ShortTonsPerHour", new BaseUnits(mass: MassUnit.ShortTon, time: DurationUnit.Hour), + new QuantityValue(180000, 45359237) + ); + yield return new (MassFlowUnit.TonnePerDay, "TonnePerDay", "TonnesPerDay", new BaseUnits(mass: MassUnit.Tonne, time: DurationUnit.Day), + new QuantityValue(54, 625) + ); + yield return new (MassFlowUnit.TonnePerHour, "TonnePerHour", "TonnesPerHour", new BaseUnits(mass: MassUnit.Tonne, time: DurationUnit.Hour), + new QuantityValue(9, 2500) + ); } } static MassFlow() { - Info = MassFlowInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MassFlowInfo.CreateDefault); } /// @@ -176,7 +237,7 @@ static MassFlow() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public MassFlow(double value, MassFlowUnit unit) + public MassFlow(QuantityValue value, MassFlowUnit unit) { _value = value; _unit = unit; @@ -190,7 +251,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -201,7 +262,8 @@ public MassFlow(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -230,10 +292,8 @@ public MassFlow(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public MassFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -272,252 +332,174 @@ public MassFlow(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentigramsPerDay => As(MassFlowUnit.CentigramPerDay); + public QuantityValue CentigramsPerDay => this.As(MassFlowUnit.CentigramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentigramsPerSecond => As(MassFlowUnit.CentigramPerSecond); + public QuantityValue CentigramsPerSecond => this.As(MassFlowUnit.CentigramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecagramsPerDay => As(MassFlowUnit.DecagramPerDay); + public QuantityValue DecagramsPerDay => this.As(MassFlowUnit.DecagramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecagramsPerSecond => As(MassFlowUnit.DecagramPerSecond); + public QuantityValue DecagramsPerSecond => this.As(MassFlowUnit.DecagramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecigramsPerDay => As(MassFlowUnit.DecigramPerDay); + public QuantityValue DecigramsPerDay => this.As(MassFlowUnit.DecigramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecigramsPerSecond => As(MassFlowUnit.DecigramPerSecond); + public QuantityValue DecigramsPerSecond => this.As(MassFlowUnit.DecigramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerDay => As(MassFlowUnit.GramPerDay); + public QuantityValue GramsPerDay => this.As(MassFlowUnit.GramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerHour => As(MassFlowUnit.GramPerHour); + public QuantityValue GramsPerHour => this.As(MassFlowUnit.GramPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerSecond => As(MassFlowUnit.GramPerSecond); + public QuantityValue GramsPerSecond => this.As(MassFlowUnit.GramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HectogramsPerDay => As(MassFlowUnit.HectogramPerDay); + public QuantityValue HectogramsPerDay => this.As(MassFlowUnit.HectogramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HectogramsPerSecond => As(MassFlowUnit.HectogramPerSecond); + public QuantityValue HectogramsPerSecond => this.As(MassFlowUnit.HectogramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerDay => As(MassFlowUnit.KilogramPerDay); + public QuantityValue KilogramsPerDay => this.As(MassFlowUnit.KilogramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerHour => As(MassFlowUnit.KilogramPerHour); + public QuantityValue KilogramsPerHour => this.As(MassFlowUnit.KilogramPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerMinute => As(MassFlowUnit.KilogramPerMinute); + public QuantityValue KilogramsPerMinute => this.As(MassFlowUnit.KilogramPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerSecond => As(MassFlowUnit.KilogramPerSecond); + public QuantityValue KilogramsPerSecond => this.As(MassFlowUnit.KilogramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegagramsPerDay => As(MassFlowUnit.MegagramPerDay); + public QuantityValue MegagramsPerDay => this.As(MassFlowUnit.MegagramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegapoundsPerDay => As(MassFlowUnit.MegapoundPerDay); + public QuantityValue MegapoundsPerDay => this.As(MassFlowUnit.MegapoundPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegapoundsPerHour => As(MassFlowUnit.MegapoundPerHour); + public QuantityValue MegapoundsPerHour => this.As(MassFlowUnit.MegapoundPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegapoundsPerMinute => As(MassFlowUnit.MegapoundPerMinute); + public QuantityValue MegapoundsPerMinute => this.As(MassFlowUnit.MegapoundPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegapoundsPerSecond => As(MassFlowUnit.MegapoundPerSecond); + public QuantityValue MegapoundsPerSecond => this.As(MassFlowUnit.MegapoundPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerDay => As(MassFlowUnit.MicrogramPerDay); + public QuantityValue MicrogramsPerDay => this.As(MassFlowUnit.MicrogramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerSecond => As(MassFlowUnit.MicrogramPerSecond); + public QuantityValue MicrogramsPerSecond => this.As(MassFlowUnit.MicrogramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerDay => As(MassFlowUnit.MilligramPerDay); + public QuantityValue MilligramsPerDay => this.As(MassFlowUnit.MilligramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerSecond => As(MassFlowUnit.MilligramPerSecond); + public QuantityValue MilligramsPerSecond => this.As(MassFlowUnit.MilligramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanogramsPerDay => As(MassFlowUnit.NanogramPerDay); + public QuantityValue NanogramsPerDay => this.As(MassFlowUnit.NanogramPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanogramsPerSecond => As(MassFlowUnit.NanogramPerSecond); + public QuantityValue NanogramsPerSecond => this.As(MassFlowUnit.NanogramPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerDay => As(MassFlowUnit.PoundPerDay); + public QuantityValue PoundsPerDay => this.As(MassFlowUnit.PoundPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerHour => As(MassFlowUnit.PoundPerHour); + public QuantityValue PoundsPerHour => this.As(MassFlowUnit.PoundPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerMinute => As(MassFlowUnit.PoundPerMinute); + public QuantityValue PoundsPerMinute => this.As(MassFlowUnit.PoundPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerSecond => As(MassFlowUnit.PoundPerSecond); + public QuantityValue PoundsPerSecond => this.As(MassFlowUnit.PoundPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ShortTonsPerHour => As(MassFlowUnit.ShortTonPerHour); + public QuantityValue ShortTonsPerHour => this.As(MassFlowUnit.ShortTonPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesPerDay => As(MassFlowUnit.TonnePerDay); + public QuantityValue TonnesPerDay => this.As(MassFlowUnit.TonnePerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesPerHour => As(MassFlowUnit.TonnePerHour); + public QuantityValue TonnesPerHour => this.As(MassFlowUnit.TonnePerHour); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: MassFlowUnit -> BaseUnit - unitConverter.SetConversionFunction(MassFlowUnit.CentigramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.CentigramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.DecagramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.DecagramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.DecigramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.DecigramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.HectogramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.HectogramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.KilogramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.KilogramPerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.KilogramPerMinute, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.KilogramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.MegagramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.MegapoundPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.MegapoundPerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.MegapoundPerMinute, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.MegapoundPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.MicrogramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.MicrogramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.MilligramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.MilligramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.NanogramPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.NanogramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.PoundPerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.PoundPerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.PoundPerMinute, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.PoundPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.ShortTonPerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.TonnePerDay, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.TonnePerHour, MassFlowUnit.GramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.GramPerSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.GramPerSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> MassFlowUnit - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.CentigramPerDay, quantity => quantity.ToUnit(MassFlowUnit.CentigramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.CentigramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.CentigramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.DecagramPerDay, quantity => quantity.ToUnit(MassFlowUnit.DecagramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.DecagramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.DecagramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.DecigramPerDay, quantity => quantity.ToUnit(MassFlowUnit.DecigramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.DecigramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.DecigramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.GramPerDay, quantity => quantity.ToUnit(MassFlowUnit.GramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.GramPerHour, quantity => quantity.ToUnit(MassFlowUnit.GramPerHour)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.HectogramPerDay, quantity => quantity.ToUnit(MassFlowUnit.HectogramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.HectogramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.HectogramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerDay, quantity => quantity.ToUnit(MassFlowUnit.KilogramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerHour, quantity => quantity.ToUnit(MassFlowUnit.KilogramPerHour)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerMinute, quantity => quantity.ToUnit(MassFlowUnit.KilogramPerMinute)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.KilogramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MegagramPerDay, quantity => quantity.ToUnit(MassFlowUnit.MegagramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerDay, quantity => quantity.ToUnit(MassFlowUnit.MegapoundPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerHour, quantity => quantity.ToUnit(MassFlowUnit.MegapoundPerHour)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerMinute, quantity => quantity.ToUnit(MassFlowUnit.MegapoundPerMinute)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerSecond, quantity => quantity.ToUnit(MassFlowUnit.MegapoundPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MicrogramPerDay, quantity => quantity.ToUnit(MassFlowUnit.MicrogramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MicrogramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.MicrogramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MilligramPerDay, quantity => quantity.ToUnit(MassFlowUnit.MilligramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.MilligramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.MilligramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.NanogramPerDay, quantity => quantity.ToUnit(MassFlowUnit.NanogramPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.NanogramPerSecond, quantity => quantity.ToUnit(MassFlowUnit.NanogramPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerDay, quantity => quantity.ToUnit(MassFlowUnit.PoundPerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerHour, quantity => quantity.ToUnit(MassFlowUnit.PoundPerHour)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerMinute, quantity => quantity.ToUnit(MassFlowUnit.PoundPerMinute)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerSecond, quantity => quantity.ToUnit(MassFlowUnit.PoundPerSecond)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.ShortTonPerHour, quantity => quantity.ToUnit(MassFlowUnit.ShortTonPerHour)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.TonnePerDay, quantity => quantity.ToUnit(MassFlowUnit.TonnePerDay)); - unitConverter.SetConversionFunction(MassFlowUnit.GramPerSecond, MassFlowUnit.TonnePerHour, quantity => quantity.ToUnit(MassFlowUnit.TonnePerHour)); - } - /// /// Get unit abbreviation string. /// @@ -546,7 +528,7 @@ public static string GetAbbreviation(MassFlowUnit unit, IFormatProvider? provide /// /// Creates a from . /// - public static MassFlow FromCentigramsPerDay(double value) + public static MassFlow FromCentigramsPerDay(QuantityValue value) { return new MassFlow(value, MassFlowUnit.CentigramPerDay); } @@ -554,7 +536,7 @@ public static MassFlow FromCentigramsPerDay(double value) /// /// Creates a from . /// - public static MassFlow FromCentigramsPerSecond(double value) + public static MassFlow FromCentigramsPerSecond(QuantityValue value) { return new MassFlow(value, MassFlowUnit.CentigramPerSecond); } @@ -562,7 +544,7 @@ public static MassFlow FromCentigramsPerSecond(double value) /// /// Creates a from . /// - public static MassFlow FromDecagramsPerDay(double value) + public static MassFlow FromDecagramsPerDay(QuantityValue value) { return new MassFlow(value, MassFlowUnit.DecagramPerDay); } @@ -570,7 +552,7 @@ public static MassFlow FromDecagramsPerDay(double value) /// /// Creates a from . /// - public static MassFlow FromDecagramsPerSecond(double value) + public static MassFlow FromDecagramsPerSecond(QuantityValue value) { return new MassFlow(value, MassFlowUnit.DecagramPerSecond); } @@ -578,7 +560,7 @@ public static MassFlow FromDecagramsPerSecond(double value) /// /// Creates a from . /// - public static MassFlow FromDecigramsPerDay(double value) + public static MassFlow FromDecigramsPerDay(QuantityValue value) { return new MassFlow(value, MassFlowUnit.DecigramPerDay); } @@ -586,7 +568,7 @@ public static MassFlow FromDecigramsPerDay(double value) /// /// Creates a from . /// - public static MassFlow FromDecigramsPerSecond(double value) + public static MassFlow FromDecigramsPerSecond(QuantityValue value) { return new MassFlow(value, MassFlowUnit.DecigramPerSecond); } @@ -594,7 +576,7 @@ public static MassFlow FromDecigramsPerSecond(double value) /// /// Creates a from . /// - public static MassFlow FromGramsPerDay(double value) + public static MassFlow FromGramsPerDay(QuantityValue value) { return new MassFlow(value, MassFlowUnit.GramPerDay); } @@ -602,7 +584,7 @@ public static MassFlow FromGramsPerDay(double value) /// /// Creates a from . /// - public static MassFlow FromGramsPerHour(double value) + public static MassFlow FromGramsPerHour(QuantityValue value) { return new MassFlow(value, MassFlowUnit.GramPerHour); } @@ -610,7 +592,7 @@ public static MassFlow FromGramsPerHour(double value) /// /// Creates a from . /// - public static MassFlow FromGramsPerSecond(double value) + public static MassFlow FromGramsPerSecond(QuantityValue value) { return new MassFlow(value, MassFlowUnit.GramPerSecond); } @@ -618,7 +600,7 @@ public static MassFlow FromGramsPerSecond(double value) /// /// Creates a from . /// - public static MassFlow FromHectogramsPerDay(double value) + public static MassFlow FromHectogramsPerDay(QuantityValue value) { return new MassFlow(value, MassFlowUnit.HectogramPerDay); } @@ -626,7 +608,7 @@ public static MassFlow FromHectogramsPerDay(double value) /// /// Creates a from . /// - public static MassFlow FromHectogramsPerSecond(double value) + public static MassFlow FromHectogramsPerSecond(QuantityValue value) { return new MassFlow(value, MassFlowUnit.HectogramPerSecond); } @@ -634,7 +616,7 @@ public static MassFlow FromHectogramsPerSecond(double value) /// /// Creates a from . /// - public static MassFlow FromKilogramsPerDay(double value) + public static MassFlow FromKilogramsPerDay(QuantityValue value) { return new MassFlow(value, MassFlowUnit.KilogramPerDay); } @@ -642,7 +624,7 @@ public static MassFlow FromKilogramsPerDay(double value) /// /// Creates a from . /// - public static MassFlow FromKilogramsPerHour(double value) + public static MassFlow FromKilogramsPerHour(QuantityValue value) { return new MassFlow(value, MassFlowUnit.KilogramPerHour); } @@ -650,7 +632,7 @@ public static MassFlow FromKilogramsPerHour(double value) /// /// Creates a from . /// - public static MassFlow FromKilogramsPerMinute(double value) + public static MassFlow FromKilogramsPerMinute(QuantityValue value) { return new MassFlow(value, MassFlowUnit.KilogramPerMinute); } @@ -658,7 +640,7 @@ public static MassFlow FromKilogramsPerMinute(double value) /// /// Creates a from . /// - public static MassFlow FromKilogramsPerSecond(double value) + public static MassFlow FromKilogramsPerSecond(QuantityValue value) { return new MassFlow(value, MassFlowUnit.KilogramPerSecond); } @@ -666,7 +648,7 @@ public static MassFlow FromKilogramsPerSecond(double value) /// /// Creates a from . /// - public static MassFlow FromMegagramsPerDay(double value) + public static MassFlow FromMegagramsPerDay(QuantityValue value) { return new MassFlow(value, MassFlowUnit.MegagramPerDay); } @@ -674,7 +656,7 @@ public static MassFlow FromMegagramsPerDay(double value) /// /// Creates a from . /// - public static MassFlow FromMegapoundsPerDay(double value) + public static MassFlow FromMegapoundsPerDay(QuantityValue value) { return new MassFlow(value, MassFlowUnit.MegapoundPerDay); } @@ -682,7 +664,7 @@ public static MassFlow FromMegapoundsPerDay(double value) /// /// Creates a from . /// - public static MassFlow FromMegapoundsPerHour(double value) + public static MassFlow FromMegapoundsPerHour(QuantityValue value) { return new MassFlow(value, MassFlowUnit.MegapoundPerHour); } @@ -690,7 +672,7 @@ public static MassFlow FromMegapoundsPerHour(double value) /// /// Creates a from . /// - public static MassFlow FromMegapoundsPerMinute(double value) + public static MassFlow FromMegapoundsPerMinute(QuantityValue value) { return new MassFlow(value, MassFlowUnit.MegapoundPerMinute); } @@ -698,7 +680,7 @@ public static MassFlow FromMegapoundsPerMinute(double value) /// /// Creates a from . /// - public static MassFlow FromMegapoundsPerSecond(double value) + public static MassFlow FromMegapoundsPerSecond(QuantityValue value) { return new MassFlow(value, MassFlowUnit.MegapoundPerSecond); } @@ -706,7 +688,7 @@ public static MassFlow FromMegapoundsPerSecond(double value) /// /// Creates a from . /// - public static MassFlow FromMicrogramsPerDay(double value) + public static MassFlow FromMicrogramsPerDay(QuantityValue value) { return new MassFlow(value, MassFlowUnit.MicrogramPerDay); } @@ -714,7 +696,7 @@ public static MassFlow FromMicrogramsPerDay(double value) /// /// Creates a from . /// - public static MassFlow FromMicrogramsPerSecond(double value) + public static MassFlow FromMicrogramsPerSecond(QuantityValue value) { return new MassFlow(value, MassFlowUnit.MicrogramPerSecond); } @@ -722,7 +704,7 @@ public static MassFlow FromMicrogramsPerSecond(double value) /// /// Creates a from . /// - public static MassFlow FromMilligramsPerDay(double value) + public static MassFlow FromMilligramsPerDay(QuantityValue value) { return new MassFlow(value, MassFlowUnit.MilligramPerDay); } @@ -730,7 +712,7 @@ public static MassFlow FromMilligramsPerDay(double value) /// /// Creates a from . /// - public static MassFlow FromMilligramsPerSecond(double value) + public static MassFlow FromMilligramsPerSecond(QuantityValue value) { return new MassFlow(value, MassFlowUnit.MilligramPerSecond); } @@ -738,7 +720,7 @@ public static MassFlow FromMilligramsPerSecond(double value) /// /// Creates a from . /// - public static MassFlow FromNanogramsPerDay(double value) + public static MassFlow FromNanogramsPerDay(QuantityValue value) { return new MassFlow(value, MassFlowUnit.NanogramPerDay); } @@ -746,7 +728,7 @@ public static MassFlow FromNanogramsPerDay(double value) /// /// Creates a from . /// - public static MassFlow FromNanogramsPerSecond(double value) + public static MassFlow FromNanogramsPerSecond(QuantityValue value) { return new MassFlow(value, MassFlowUnit.NanogramPerSecond); } @@ -754,7 +736,7 @@ public static MassFlow FromNanogramsPerSecond(double value) /// /// Creates a from . /// - public static MassFlow FromPoundsPerDay(double value) + public static MassFlow FromPoundsPerDay(QuantityValue value) { return new MassFlow(value, MassFlowUnit.PoundPerDay); } @@ -762,7 +744,7 @@ public static MassFlow FromPoundsPerDay(double value) /// /// Creates a from . /// - public static MassFlow FromPoundsPerHour(double value) + public static MassFlow FromPoundsPerHour(QuantityValue value) { return new MassFlow(value, MassFlowUnit.PoundPerHour); } @@ -770,7 +752,7 @@ public static MassFlow FromPoundsPerHour(double value) /// /// Creates a from . /// - public static MassFlow FromPoundsPerMinute(double value) + public static MassFlow FromPoundsPerMinute(QuantityValue value) { return new MassFlow(value, MassFlowUnit.PoundPerMinute); } @@ -778,7 +760,7 @@ public static MassFlow FromPoundsPerMinute(double value) /// /// Creates a from . /// - public static MassFlow FromPoundsPerSecond(double value) + public static MassFlow FromPoundsPerSecond(QuantityValue value) { return new MassFlow(value, MassFlowUnit.PoundPerSecond); } @@ -786,7 +768,7 @@ public static MassFlow FromPoundsPerSecond(double value) /// /// Creates a from . /// - public static MassFlow FromShortTonsPerHour(double value) + public static MassFlow FromShortTonsPerHour(QuantityValue value) { return new MassFlow(value, MassFlowUnit.ShortTonPerHour); } @@ -794,7 +776,7 @@ public static MassFlow FromShortTonsPerHour(double value) /// /// Creates a from . /// - public static MassFlow FromTonnesPerDay(double value) + public static MassFlow FromTonnesPerDay(QuantityValue value) { return new MassFlow(value, MassFlowUnit.TonnePerDay); } @@ -802,7 +784,7 @@ public static MassFlow FromTonnesPerDay(double value) /// /// Creates a from . /// - public static MassFlow FromTonnesPerHour(double value) + public static MassFlow FromTonnesPerHour(QuantityValue value) { return new MassFlow(value, MassFlowUnit.TonnePerHour); } @@ -813,7 +795,7 @@ public static MassFlow FromTonnesPerHour(double value) /// Value to convert from. /// Unit to convert from. /// MassFlow unit value. - public static MassFlow From(double value, MassFlowUnit fromUnit) + public static MassFlow From(QuantityValue value, MassFlowUnit fromUnit) { return new MassFlow(value, fromUnit); } @@ -874,10 +856,7 @@ public static MassFlow Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static MassFlow Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -905,11 +884,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out MassFlow result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out MassFlow result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -930,7 +905,7 @@ public static MassFlowUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -941,7 +916,7 @@ public static MassFlowUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out MassFlowUnit unit) { return TryParseUnit(str, null, out unit); @@ -956,7 +931,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out MassFlowUnit /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out MassFlowUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -975,35 +950,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static MassFlow operator +(MassFlow left, MassFlow right) { - return new MassFlow(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new MassFlow(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static MassFlow operator -(MassFlow left, MassFlow right) { - return new MassFlow(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new MassFlow(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -1079,97 +1054,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(MassFlow left, MassFlow right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(MassFlow left, MassFlow right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(MassFlow left, MassFlow right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(MassFlow left, MassFlow right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MassFlow other, MassFlow tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(MassFlow left, MassFlow right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MassFlow other, MassFlow tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(MassFlow left, MassFlow right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MassFlow other, MassFlow tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is MassFlow otherQuantity)) + if (obj is not MassFlow otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MassFlow other, MassFlow tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(MassFlow other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current MassFlow. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(MassFlow), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MassFlow otherQuantity)) throw new ArgumentException("Expected type MassFlow.", nameof(obj)); + if (obj is not MassFlow otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1181,210 +1141,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MassFlow other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassFlowUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this MassFlow to another MassFlow with the unit representation . - /// - /// The unit to convert to. - /// A MassFlow with the specified unit. - public MassFlow ToUnit(MassFlowUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A MassFlow with the specified unit. - public MassFlow ToUnit(MassFlowUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(MassFlow), Unit, typeof(MassFlow), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (MassFlow)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(MassFlowUnit unit, [NotNullWhen(true)] out MassFlow? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - MassFlow? convertedOrNull = (Unit, unit) switch - { - // MassFlowUnit -> BaseUnit - (MassFlowUnit.CentigramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e-2d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.CentigramPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value) * 1e-2d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.DecagramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e1d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.DecagramPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value) * 1e1d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.DecigramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e-1d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.DecigramPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value) * 1e-1d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.GramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow(_value / 86400, MassFlowUnit.GramPerSecond), - (MassFlowUnit.GramPerHour, MassFlowUnit.GramPerSecond) => new MassFlow(_value / 3600, MassFlowUnit.GramPerSecond), - (MassFlowUnit.HectogramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e2d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.HectogramPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value) * 1e2d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.KilogramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e3d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.KilogramPerHour, MassFlowUnit.GramPerSecond) => new MassFlow(_value / 3.6, MassFlowUnit.GramPerSecond), - (MassFlowUnit.KilogramPerMinute, MassFlowUnit.GramPerSecond) => new MassFlow(_value / 0.06, MassFlowUnit.GramPerSecond), - (MassFlowUnit.KilogramPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value) * 1e3d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.MegagramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e6d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.MegapoundPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value * 453.59237 / 86400) * 1e6d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.MegapoundPerHour, MassFlowUnit.GramPerSecond) => new MassFlow((_value * 453.59237 / 3600) * 1e6d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.MegapoundPerMinute, MassFlowUnit.GramPerSecond) => new MassFlow((_value * 453.59237 / 60) * 1e6d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.MegapoundPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value * 453.59237) * 1e6d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.MicrogramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e-6d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.MicrogramPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value) * 1e-6d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.MilligramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e-3d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.MilligramPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value) * 1e-3d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.NanogramPerDay, MassFlowUnit.GramPerSecond) => new MassFlow((_value / 86400) * 1e-9d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.NanogramPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow((_value) * 1e-9d, MassFlowUnit.GramPerSecond), - (MassFlowUnit.PoundPerDay, MassFlowUnit.GramPerSecond) => new MassFlow(_value * 453.59237 / 86400, MassFlowUnit.GramPerSecond), - (MassFlowUnit.PoundPerHour, MassFlowUnit.GramPerSecond) => new MassFlow(_value * 453.59237 / 3600, MassFlowUnit.GramPerSecond), - (MassFlowUnit.PoundPerMinute, MassFlowUnit.GramPerSecond) => new MassFlow(_value * 453.59237 / 60, MassFlowUnit.GramPerSecond), - (MassFlowUnit.PoundPerSecond, MassFlowUnit.GramPerSecond) => new MassFlow(_value * 453.59237, MassFlowUnit.GramPerSecond), - (MassFlowUnit.ShortTonPerHour, MassFlowUnit.GramPerSecond) => new MassFlow(_value * 907.18474 / 3.6, MassFlowUnit.GramPerSecond), - (MassFlowUnit.TonnePerDay, MassFlowUnit.GramPerSecond) => new MassFlow(_value / 0.0864000, MassFlowUnit.GramPerSecond), - (MassFlowUnit.TonnePerHour, MassFlowUnit.GramPerSecond) => new MassFlow(_value * 1000 / 3.6, MassFlowUnit.GramPerSecond), - - // BaseUnit -> MassFlowUnit - (MassFlowUnit.GramPerSecond, MassFlowUnit.CentigramPerDay) => new MassFlow((_value * 86400) / 1e-2d, MassFlowUnit.CentigramPerDay), - (MassFlowUnit.GramPerSecond, MassFlowUnit.CentigramPerSecond) => new MassFlow((_value) / 1e-2d, MassFlowUnit.CentigramPerSecond), - (MassFlowUnit.GramPerSecond, MassFlowUnit.DecagramPerDay) => new MassFlow((_value * 86400) / 1e1d, MassFlowUnit.DecagramPerDay), - (MassFlowUnit.GramPerSecond, MassFlowUnit.DecagramPerSecond) => new MassFlow((_value) / 1e1d, MassFlowUnit.DecagramPerSecond), - (MassFlowUnit.GramPerSecond, MassFlowUnit.DecigramPerDay) => new MassFlow((_value * 86400) / 1e-1d, MassFlowUnit.DecigramPerDay), - (MassFlowUnit.GramPerSecond, MassFlowUnit.DecigramPerSecond) => new MassFlow((_value) / 1e-1d, MassFlowUnit.DecigramPerSecond), - (MassFlowUnit.GramPerSecond, MassFlowUnit.GramPerDay) => new MassFlow(_value * 86400, MassFlowUnit.GramPerDay), - (MassFlowUnit.GramPerSecond, MassFlowUnit.GramPerHour) => new MassFlow(_value * 3600, MassFlowUnit.GramPerHour), - (MassFlowUnit.GramPerSecond, MassFlowUnit.HectogramPerDay) => new MassFlow((_value * 86400) / 1e2d, MassFlowUnit.HectogramPerDay), - (MassFlowUnit.GramPerSecond, MassFlowUnit.HectogramPerSecond) => new MassFlow((_value) / 1e2d, MassFlowUnit.HectogramPerSecond), - (MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerDay) => new MassFlow((_value * 86400) / 1e3d, MassFlowUnit.KilogramPerDay), - (MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerHour) => new MassFlow(_value * 3.6, MassFlowUnit.KilogramPerHour), - (MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerMinute) => new MassFlow(_value * 0.06, MassFlowUnit.KilogramPerMinute), - (MassFlowUnit.GramPerSecond, MassFlowUnit.KilogramPerSecond) => new MassFlow((_value) / 1e3d, MassFlowUnit.KilogramPerSecond), - (MassFlowUnit.GramPerSecond, MassFlowUnit.MegagramPerDay) => new MassFlow((_value * 86400) / 1e6d, MassFlowUnit.MegagramPerDay), - (MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerDay) => new MassFlow((_value * 86400 / 453.59237) / 1e6d, MassFlowUnit.MegapoundPerDay), - (MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerHour) => new MassFlow((_value * 3600 / 453.59237) / 1e6d, MassFlowUnit.MegapoundPerHour), - (MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerMinute) => new MassFlow((_value * 60 / 453.59237) / 1e6d, MassFlowUnit.MegapoundPerMinute), - (MassFlowUnit.GramPerSecond, MassFlowUnit.MegapoundPerSecond) => new MassFlow((_value / 453.59237) / 1e6d, MassFlowUnit.MegapoundPerSecond), - (MassFlowUnit.GramPerSecond, MassFlowUnit.MicrogramPerDay) => new MassFlow((_value * 86400) / 1e-6d, MassFlowUnit.MicrogramPerDay), - (MassFlowUnit.GramPerSecond, MassFlowUnit.MicrogramPerSecond) => new MassFlow((_value) / 1e-6d, MassFlowUnit.MicrogramPerSecond), - (MassFlowUnit.GramPerSecond, MassFlowUnit.MilligramPerDay) => new MassFlow((_value * 86400) / 1e-3d, MassFlowUnit.MilligramPerDay), - (MassFlowUnit.GramPerSecond, MassFlowUnit.MilligramPerSecond) => new MassFlow((_value) / 1e-3d, MassFlowUnit.MilligramPerSecond), - (MassFlowUnit.GramPerSecond, MassFlowUnit.NanogramPerDay) => new MassFlow((_value * 86400) / 1e-9d, MassFlowUnit.NanogramPerDay), - (MassFlowUnit.GramPerSecond, MassFlowUnit.NanogramPerSecond) => new MassFlow((_value) / 1e-9d, MassFlowUnit.NanogramPerSecond), - (MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerDay) => new MassFlow(_value * 86400 / 453.59237, MassFlowUnit.PoundPerDay), - (MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerHour) => new MassFlow(_value * 3600 / 453.59237, MassFlowUnit.PoundPerHour), - (MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerMinute) => new MassFlow(_value * 60 / 453.59237, MassFlowUnit.PoundPerMinute), - (MassFlowUnit.GramPerSecond, MassFlowUnit.PoundPerSecond) => new MassFlow(_value / 453.59237, MassFlowUnit.PoundPerSecond), - (MassFlowUnit.GramPerSecond, MassFlowUnit.ShortTonPerHour) => new MassFlow(_value * 3.6 / 907.18474, MassFlowUnit.ShortTonPerHour), - (MassFlowUnit.GramPerSecond, MassFlowUnit.TonnePerDay) => new MassFlow(_value * 0.0864000, MassFlowUnit.TonnePerDay), - (MassFlowUnit.GramPerSecond, MassFlowUnit.TonnePerHour) => new MassFlow(_value * 3.6 / 1000, MassFlowUnit.TonnePerHour), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public MassFlow ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not MassFlowUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFlowUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(MassFlowUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(MassFlowUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1399,7 +1173,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs index 2c5916a9ec..140689c4dc 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFlux.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// Mass flux is the mass flow rate per unit area. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct MassFlux : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -55,13 +54,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly MassFluxUnit? _unit; /// @@ -106,7 +105,7 @@ public static MassFluxInfo CreateDefault(Func - /// The for is [T^-1][L^-2][M]. + /// The for is T^-1L^-2M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 1, -1, 0, 0, 0, 0); @@ -121,26 +120,46 @@ public static MassFluxInfo CreateDefault(FuncAn of representing the default unit mappings for MassFlux. public static IEnumerable> GetDefaultMappings() { - yield return new (MassFluxUnit.GramPerHourPerSquareCentimeter, "GramPerHourPerSquareCentimeter", "GramsPerHourPerSquareCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram, time: DurationUnit.Hour)); - yield return new (MassFluxUnit.GramPerHourPerSquareMeter, "GramPerHourPerSquareMeter", "GramsPerHourPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Hour)); - yield return new (MassFluxUnit.GramPerHourPerSquareMillimeter, "GramPerHourPerSquareMillimeter", "GramsPerHourPerSquareMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram, time: DurationUnit.Hour)); - yield return new (MassFluxUnit.GramPerSecondPerSquareCentimeter, "GramPerSecondPerSquareCentimeter", "GramsPerSecondPerSquareCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram, time: DurationUnit.Second)); - yield return new (MassFluxUnit.GramPerSecondPerSquareMeter, "GramPerSecondPerSquareMeter", "GramsPerSecondPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second)); - yield return new (MassFluxUnit.GramPerSecondPerSquareMillimeter, "GramPerSecondPerSquareMillimeter", "GramsPerSecondPerSquareMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram, time: DurationUnit.Second)); - yield return new (MassFluxUnit.KilogramPerHourPerSquareCentimeter, "KilogramPerHourPerSquareCentimeter", "KilogramsPerHourPerSquareCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram, time: DurationUnit.Hour)); - yield return new (MassFluxUnit.KilogramPerHourPerSquareMeter, "KilogramPerHourPerSquareMeter", "KilogramsPerHourPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Hour)); - yield return new (MassFluxUnit.KilogramPerHourPerSquareMillimeter, "KilogramPerHourPerSquareMillimeter", "KilogramsPerHourPerSquareMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Hour)); - yield return new (MassFluxUnit.KilogramPerSecondPerSquareCentimeter, "KilogramPerSecondPerSquareCentimeter", "KilogramsPerSecondPerSquareCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); + yield return new (MassFluxUnit.GramPerHourPerSquareCentimeter, "GramPerHourPerSquareCentimeter", "GramsPerHourPerSquareCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram, time: DurationUnit.Hour), + 360 + ); + yield return new (MassFluxUnit.GramPerHourPerSquareMeter, "GramPerHourPerSquareMeter", "GramsPerHourPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Hour), + 3600000 + ); + yield return new (MassFluxUnit.GramPerHourPerSquareMillimeter, "GramPerHourPerSquareMillimeter", "GramsPerHourPerSquareMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram, time: DurationUnit.Hour), + new QuantityValue(18, 5) + ); + yield return new (MassFluxUnit.GramPerSecondPerSquareCentimeter, "GramPerSecondPerSquareCentimeter", "GramsPerSecondPerSquareCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram, time: DurationUnit.Second), + new QuantityValue(1, 10) + ); + yield return new (MassFluxUnit.GramPerSecondPerSquareMeter, "GramPerSecondPerSquareMeter", "GramsPerSecondPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second), + 1000 + ); + yield return new (MassFluxUnit.GramPerSecondPerSquareMillimeter, "GramPerSecondPerSquareMillimeter", "GramsPerSecondPerSquareMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram, time: DurationUnit.Second), + new QuantityValue(1, 1000) + ); + yield return new (MassFluxUnit.KilogramPerHourPerSquareCentimeter, "KilogramPerHourPerSquareCentimeter", "KilogramsPerHourPerSquareCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram, time: DurationUnit.Hour), + new QuantityValue(9, 25) + ); + yield return new (MassFluxUnit.KilogramPerHourPerSquareMeter, "KilogramPerHourPerSquareMeter", "KilogramsPerHourPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Hour), + 3600 + ); + yield return new (MassFluxUnit.KilogramPerHourPerSquareMillimeter, "KilogramPerHourPerSquareMillimeter", "KilogramsPerHourPerSquareMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Hour), + new QuantityValue(9, 2500) + ); + yield return new (MassFluxUnit.KilogramPerSecondPerSquareCentimeter, "KilogramPerSecondPerSquareCentimeter", "KilogramsPerSecondPerSquareCentimeter", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 10000) + ); yield return new (MassFluxUnit.KilogramPerSecondPerSquareMeter, "KilogramPerSecondPerSquareMeter", "KilogramsPerSecondPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (MassFluxUnit.KilogramPerSecondPerSquareMillimeter, "KilogramPerSecondPerSquareMillimeter", "KilogramsPerSecondPerSquareMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); + yield return new (MassFluxUnit.KilogramPerSecondPerSquareMillimeter, "KilogramPerSecondPerSquareMillimeter", "KilogramsPerSecondPerSquareMillimeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); } } static MassFlux() { - Info = MassFluxInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MassFluxInfo.CreateDefault); } /// @@ -148,7 +167,7 @@ static MassFlux() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public MassFlux(double value, MassFluxUnit unit) + public MassFlux(QuantityValue value, MassFluxUnit unit) { _value = value; _unit = unit; @@ -162,7 +181,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -173,7 +192,8 @@ public MassFlux(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -202,10 +222,8 @@ public MassFlux(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public MassFluxUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -244,105 +262,69 @@ public MassFlux(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerHourPerSquareCentimeter => As(MassFluxUnit.GramPerHourPerSquareCentimeter); + public QuantityValue GramsPerHourPerSquareCentimeter => this.As(MassFluxUnit.GramPerHourPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerHourPerSquareMeter => As(MassFluxUnit.GramPerHourPerSquareMeter); + public QuantityValue GramsPerHourPerSquareMeter => this.As(MassFluxUnit.GramPerHourPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerHourPerSquareMillimeter => As(MassFluxUnit.GramPerHourPerSquareMillimeter); + public QuantityValue GramsPerHourPerSquareMillimeter => this.As(MassFluxUnit.GramPerHourPerSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerSecondPerSquareCentimeter => As(MassFluxUnit.GramPerSecondPerSquareCentimeter); + public QuantityValue GramsPerSecondPerSquareCentimeter => this.As(MassFluxUnit.GramPerSecondPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerSecondPerSquareMeter => As(MassFluxUnit.GramPerSecondPerSquareMeter); + public QuantityValue GramsPerSecondPerSquareMeter => this.As(MassFluxUnit.GramPerSecondPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerSecondPerSquareMillimeter => As(MassFluxUnit.GramPerSecondPerSquareMillimeter); + public QuantityValue GramsPerSecondPerSquareMillimeter => this.As(MassFluxUnit.GramPerSecondPerSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerHourPerSquareCentimeter => As(MassFluxUnit.KilogramPerHourPerSquareCentimeter); + public QuantityValue KilogramsPerHourPerSquareCentimeter => this.As(MassFluxUnit.KilogramPerHourPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerHourPerSquareMeter => As(MassFluxUnit.KilogramPerHourPerSquareMeter); + public QuantityValue KilogramsPerHourPerSquareMeter => this.As(MassFluxUnit.KilogramPerHourPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerHourPerSquareMillimeter => As(MassFluxUnit.KilogramPerHourPerSquareMillimeter); + public QuantityValue KilogramsPerHourPerSquareMillimeter => this.As(MassFluxUnit.KilogramPerHourPerSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerSecondPerSquareCentimeter => As(MassFluxUnit.KilogramPerSecondPerSquareCentimeter); + public QuantityValue KilogramsPerSecondPerSquareCentimeter => this.As(MassFluxUnit.KilogramPerSecondPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerSecondPerSquareMeter => As(MassFluxUnit.KilogramPerSecondPerSquareMeter); + public QuantityValue KilogramsPerSecondPerSquareMeter => this.As(MassFluxUnit.KilogramPerSecondPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerSecondPerSquareMillimeter => As(MassFluxUnit.KilogramPerSecondPerSquareMillimeter); + public QuantityValue KilogramsPerSecondPerSquareMillimeter => this.As(MassFluxUnit.KilogramPerSecondPerSquareMillimeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: MassFluxUnit -> BaseUnit - unitConverter.SetConversionFunction(MassFluxUnit.GramPerHourPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); - unitConverter.SetConversionFunction(MassFluxUnit.GramPerHourPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); - unitConverter.SetConversionFunction(MassFluxUnit.GramPerHourPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); - unitConverter.SetConversionFunction(MassFluxUnit.GramPerSecondPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); - unitConverter.SetConversionFunction(MassFluxUnit.GramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); - unitConverter.SetConversionFunction(MassFluxUnit.GramPerSecondPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerHourPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerHourPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerHourPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> MassFluxUnit - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareCentimeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerHourPerSquareCentimeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerHourPerSquareMeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareMillimeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerHourPerSquareMillimeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareCentimeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerSecondPerSquareCentimeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerSecondPerSquareMeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareMillimeter, quantity => quantity.ToUnit(MassFluxUnit.GramPerSecondPerSquareMillimeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareCentimeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerHourPerSquareCentimeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareMeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerHourPerSquareMeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareMillimeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerHourPerSquareMillimeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareCentimeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareCentimeter)); - unitConverter.SetConversionFunction(MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMillimeter, quantity => quantity.ToUnit(MassFluxUnit.KilogramPerSecondPerSquareMillimeter)); - } - /// /// Get unit abbreviation string. /// @@ -371,7 +353,7 @@ public static string GetAbbreviation(MassFluxUnit unit, IFormatProvider? provide /// /// Creates a from . /// - public static MassFlux FromGramsPerHourPerSquareCentimeter(double value) + public static MassFlux FromGramsPerHourPerSquareCentimeter(QuantityValue value) { return new MassFlux(value, MassFluxUnit.GramPerHourPerSquareCentimeter); } @@ -379,7 +361,7 @@ public static MassFlux FromGramsPerHourPerSquareCentimeter(double value) /// /// Creates a from . /// - public static MassFlux FromGramsPerHourPerSquareMeter(double value) + public static MassFlux FromGramsPerHourPerSquareMeter(QuantityValue value) { return new MassFlux(value, MassFluxUnit.GramPerHourPerSquareMeter); } @@ -387,7 +369,7 @@ public static MassFlux FromGramsPerHourPerSquareMeter(double value) /// /// Creates a from . /// - public static MassFlux FromGramsPerHourPerSquareMillimeter(double value) + public static MassFlux FromGramsPerHourPerSquareMillimeter(QuantityValue value) { return new MassFlux(value, MassFluxUnit.GramPerHourPerSquareMillimeter); } @@ -395,7 +377,7 @@ public static MassFlux FromGramsPerHourPerSquareMillimeter(double value) /// /// Creates a from . /// - public static MassFlux FromGramsPerSecondPerSquareCentimeter(double value) + public static MassFlux FromGramsPerSecondPerSquareCentimeter(QuantityValue value) { return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareCentimeter); } @@ -403,7 +385,7 @@ public static MassFlux FromGramsPerSecondPerSquareCentimeter(double value) /// /// Creates a from . /// - public static MassFlux FromGramsPerSecondPerSquareMeter(double value) + public static MassFlux FromGramsPerSecondPerSquareMeter(QuantityValue value) { return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareMeter); } @@ -411,7 +393,7 @@ public static MassFlux FromGramsPerSecondPerSquareMeter(double value) /// /// Creates a from . /// - public static MassFlux FromGramsPerSecondPerSquareMillimeter(double value) + public static MassFlux FromGramsPerSecondPerSquareMillimeter(QuantityValue value) { return new MassFlux(value, MassFluxUnit.GramPerSecondPerSquareMillimeter); } @@ -419,7 +401,7 @@ public static MassFlux FromGramsPerSecondPerSquareMillimeter(double value) /// /// Creates a from . /// - public static MassFlux FromKilogramsPerHourPerSquareCentimeter(double value) + public static MassFlux FromKilogramsPerHourPerSquareCentimeter(QuantityValue value) { return new MassFlux(value, MassFluxUnit.KilogramPerHourPerSquareCentimeter); } @@ -427,7 +409,7 @@ public static MassFlux FromKilogramsPerHourPerSquareCentimeter(double value) /// /// Creates a from . /// - public static MassFlux FromKilogramsPerHourPerSquareMeter(double value) + public static MassFlux FromKilogramsPerHourPerSquareMeter(QuantityValue value) { return new MassFlux(value, MassFluxUnit.KilogramPerHourPerSquareMeter); } @@ -435,7 +417,7 @@ public static MassFlux FromKilogramsPerHourPerSquareMeter(double value) /// /// Creates a from . /// - public static MassFlux FromKilogramsPerHourPerSquareMillimeter(double value) + public static MassFlux FromKilogramsPerHourPerSquareMillimeter(QuantityValue value) { return new MassFlux(value, MassFluxUnit.KilogramPerHourPerSquareMillimeter); } @@ -443,7 +425,7 @@ public static MassFlux FromKilogramsPerHourPerSquareMillimeter(double value) /// /// Creates a from . /// - public static MassFlux FromKilogramsPerSecondPerSquareCentimeter(double value) + public static MassFlux FromKilogramsPerSecondPerSquareCentimeter(QuantityValue value) { return new MassFlux(value, MassFluxUnit.KilogramPerSecondPerSquareCentimeter); } @@ -451,7 +433,7 @@ public static MassFlux FromKilogramsPerSecondPerSquareCentimeter(double value) /// /// Creates a from . /// - public static MassFlux FromKilogramsPerSecondPerSquareMeter(double value) + public static MassFlux FromKilogramsPerSecondPerSquareMeter(QuantityValue value) { return new MassFlux(value, MassFluxUnit.KilogramPerSecondPerSquareMeter); } @@ -459,7 +441,7 @@ public static MassFlux FromKilogramsPerSecondPerSquareMeter(double value) /// /// Creates a from . /// - public static MassFlux FromKilogramsPerSecondPerSquareMillimeter(double value) + public static MassFlux FromKilogramsPerSecondPerSquareMillimeter(QuantityValue value) { return new MassFlux(value, MassFluxUnit.KilogramPerSecondPerSquareMillimeter); } @@ -470,7 +452,7 @@ public static MassFlux FromKilogramsPerSecondPerSquareMillimeter(double value) /// Value to convert from. /// Unit to convert from. /// MassFlux unit value. - public static MassFlux From(double value, MassFluxUnit fromUnit) + public static MassFlux From(QuantityValue value, MassFluxUnit fromUnit) { return new MassFlux(value, fromUnit); } @@ -531,10 +513,7 @@ public static MassFlux Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static MassFlux Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -562,11 +541,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out MassFlux result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out MassFlux result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -587,7 +562,7 @@ public static MassFluxUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -598,7 +573,7 @@ public static MassFluxUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out MassFluxUnit unit) { return TryParseUnit(str, null, out unit); @@ -613,7 +588,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out MassFluxUnit /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out MassFluxUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -632,35 +607,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static MassFlux operator +(MassFlux left, MassFlux right) { - return new MassFlux(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new MassFlux(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static MassFlux operator -(MassFlux left, MassFlux right) { - return new MassFlux(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new MassFlux(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -694,97 +669,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(MassFlux left, MassFlux right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(MassFlux left, MassFlux right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(MassFlux left, MassFlux right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(MassFlux left, MassFlux right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MassFlux other, MassFlux tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(MassFlux left, MassFlux right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MassFlux other, MassFlux tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(MassFlux left, MassFlux right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MassFlux other, MassFlux tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is MassFlux otherQuantity)) + if (obj is not MassFlux otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MassFlux other, MassFlux tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(MassFlux other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current MassFlux. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(MassFlux), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MassFlux otherQuantity)) throw new ArgumentException("Expected type MassFlux.", nameof(obj)); + if (obj is not MassFlux otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -796,168 +756,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MassFlux other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassFluxUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this MassFlux to another MassFlux with the unit representation . - /// - /// The unit to convert to. - /// A MassFlux with the specified unit. - public MassFlux ToUnit(MassFluxUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A MassFlux with the specified unit. - public MassFlux ToUnit(MassFluxUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(MassFlux), Unit, typeof(MassFlux), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (MassFlux)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(MassFluxUnit unit, [NotNullWhen(true)] out MassFlux? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - MassFlux? convertedOrNull = (Unit, unit) switch - { - // MassFluxUnit -> BaseUnit - (MassFluxUnit.GramPerHourPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux(_value / 3.6e2, MassFluxUnit.KilogramPerSecondPerSquareMeter), - (MassFluxUnit.GramPerHourPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux(_value / 3.6e6, MassFluxUnit.KilogramPerSecondPerSquareMeter), - (MassFluxUnit.GramPerHourPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux(_value / 3.6e0, MassFluxUnit.KilogramPerSecondPerSquareMeter), - (MassFluxUnit.GramPerSecondPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux(_value / 1e-1, MassFluxUnit.KilogramPerSecondPerSquareMeter), - (MassFluxUnit.GramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux(_value / 1e3, MassFluxUnit.KilogramPerSecondPerSquareMeter), - (MassFluxUnit.GramPerSecondPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux(_value / 1e-3, MassFluxUnit.KilogramPerSecondPerSquareMeter), - (MassFluxUnit.KilogramPerHourPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux((_value / 3.6e2) * 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMeter), - (MassFluxUnit.KilogramPerHourPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux((_value / 3.6e6) * 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMeter), - (MassFluxUnit.KilogramPerHourPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux((_value / 3.6e0) * 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMeter), - (MassFluxUnit.KilogramPerSecondPerSquareCentimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux((_value / 1e-1) * 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMeter), - (MassFluxUnit.KilogramPerSecondPerSquareMillimeter, MassFluxUnit.KilogramPerSecondPerSquareMeter) => new MassFlux((_value / 1e-3) * 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMeter), - - // BaseUnit -> MassFluxUnit - (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareCentimeter) => new MassFlux(_value * 3.6e2, MassFluxUnit.GramPerHourPerSquareCentimeter), - (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareMeter) => new MassFlux(_value * 3.6e6, MassFluxUnit.GramPerHourPerSquareMeter), - (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerHourPerSquareMillimeter) => new MassFlux(_value * 3.6e0, MassFluxUnit.GramPerHourPerSquareMillimeter), - (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareCentimeter) => new MassFlux(_value * 1e-1, MassFluxUnit.GramPerSecondPerSquareCentimeter), - (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareMeter) => new MassFlux(_value * 1e3, MassFluxUnit.GramPerSecondPerSquareMeter), - (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.GramPerSecondPerSquareMillimeter) => new MassFlux(_value * 1e-3, MassFluxUnit.GramPerSecondPerSquareMillimeter), - (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareCentimeter) => new MassFlux((_value * 3.6e2) / 1e3d, MassFluxUnit.KilogramPerHourPerSquareCentimeter), - (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareMeter) => new MassFlux((_value * 3.6e6) / 1e3d, MassFluxUnit.KilogramPerHourPerSquareMeter), - (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerHourPerSquareMillimeter) => new MassFlux((_value * 3.6e0) / 1e3d, MassFluxUnit.KilogramPerHourPerSquareMillimeter), - (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareCentimeter) => new MassFlux((_value * 1e-1) / 1e3d, MassFluxUnit.KilogramPerSecondPerSquareCentimeter), - (MassFluxUnit.KilogramPerSecondPerSquareMeter, MassFluxUnit.KilogramPerSecondPerSquareMillimeter) => new MassFlux((_value * 1e-3) / 1e3d, MassFluxUnit.KilogramPerSecondPerSquareMillimeter), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public MassFlux ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not MassFluxUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFluxUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(MassFluxUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(MassFluxUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -972,7 +788,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs b/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs index 29f4fecb97..f1d32f77a5 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassFraction.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Mass_fraction_(chemistry) /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct MassFraction : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -56,13 +55,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly MassFractionUnit? _unit; /// @@ -122,38 +121,82 @@ public static MassFractionInfo CreateDefault(FuncAn of representing the default unit mappings for MassFraction. public static IEnumerable> GetDefaultMappings() { - yield return new (MassFractionUnit.CentigramPerGram, "CentigramPerGram", "CentigramsPerGram", BaseUnits.Undefined); - yield return new (MassFractionUnit.CentigramPerKilogram, "CentigramPerKilogram", "CentigramsPerKilogram", BaseUnits.Undefined); - yield return new (MassFractionUnit.DecagramPerGram, "DecagramPerGram", "DecagramsPerGram", BaseUnits.Undefined); - yield return new (MassFractionUnit.DecagramPerKilogram, "DecagramPerKilogram", "DecagramsPerKilogram", BaseUnits.Undefined); - yield return new (MassFractionUnit.DecigramPerGram, "DecigramPerGram", "DecigramsPerGram", BaseUnits.Undefined); - yield return new (MassFractionUnit.DecigramPerKilogram, "DecigramPerKilogram", "DecigramsPerKilogram", BaseUnits.Undefined); + yield return new (MassFractionUnit.CentigramPerGram, "CentigramPerGram", "CentigramsPerGram", BaseUnits.Undefined, + 100 + ); + yield return new (MassFractionUnit.CentigramPerKilogram, "CentigramPerKilogram", "CentigramsPerKilogram", BaseUnits.Undefined, + 100000 + ); + yield return new (MassFractionUnit.DecagramPerGram, "DecagramPerGram", "DecagramsPerGram", BaseUnits.Undefined, + new QuantityValue(1, 10) + ); + yield return new (MassFractionUnit.DecagramPerKilogram, "DecagramPerKilogram", "DecagramsPerKilogram", BaseUnits.Undefined, + 100 + ); + yield return new (MassFractionUnit.DecigramPerGram, "DecigramPerGram", "DecigramsPerGram", BaseUnits.Undefined, + 10 + ); + yield return new (MassFractionUnit.DecigramPerKilogram, "DecigramPerKilogram", "DecigramsPerKilogram", BaseUnits.Undefined, + 10000 + ); yield return new (MassFractionUnit.DecimalFraction, "DecimalFraction", "DecimalFractions", BaseUnits.Undefined); - yield return new (MassFractionUnit.GramPerGram, "GramPerGram", "GramsPerGram", BaseUnits.Undefined); - yield return new (MassFractionUnit.GramPerKilogram, "GramPerKilogram", "GramsPerKilogram", BaseUnits.Undefined); - yield return new (MassFractionUnit.HectogramPerGram, "HectogramPerGram", "HectogramsPerGram", BaseUnits.Undefined); - yield return new (MassFractionUnit.HectogramPerKilogram, "HectogramPerKilogram", "HectogramsPerKilogram", BaseUnits.Undefined); - yield return new (MassFractionUnit.KilogramPerGram, "KilogramPerGram", "KilogramsPerGram", BaseUnits.Undefined); - yield return new (MassFractionUnit.KilogramPerKilogram, "KilogramPerKilogram", "KilogramsPerKilogram", BaseUnits.Undefined); - yield return new (MassFractionUnit.MicrogramPerGram, "MicrogramPerGram", "MicrogramsPerGram", BaseUnits.Undefined); - yield return new (MassFractionUnit.MicrogramPerKilogram, "MicrogramPerKilogram", "MicrogramsPerKilogram", BaseUnits.Undefined); - yield return new (MassFractionUnit.MilligramPerGram, "MilligramPerGram", "MilligramsPerGram", BaseUnits.Undefined); - yield return new (MassFractionUnit.MilligramPerKilogram, "MilligramPerKilogram", "MilligramsPerKilogram", BaseUnits.Undefined); - yield return new (MassFractionUnit.NanogramPerGram, "NanogramPerGram", "NanogramsPerGram", BaseUnits.Undefined); - yield return new (MassFractionUnit.NanogramPerKilogram, "NanogramPerKilogram", "NanogramsPerKilogram", BaseUnits.Undefined); - yield return new (MassFractionUnit.PartPerBillion, "PartPerBillion", "PartsPerBillion", BaseUnits.Undefined); - yield return new (MassFractionUnit.PartPerMillion, "PartPerMillion", "PartsPerMillion", BaseUnits.Undefined); - yield return new (MassFractionUnit.PartPerThousand, "PartPerThousand", "PartsPerThousand", BaseUnits.Undefined); - yield return new (MassFractionUnit.PartPerTrillion, "PartPerTrillion", "PartsPerTrillion", BaseUnits.Undefined); - yield return new (MassFractionUnit.Percent, "Percent", "Percent", BaseUnits.Undefined); + yield return new (MassFractionUnit.GramPerGram, "GramPerGram", "GramsPerGram", BaseUnits.Undefined, + 1 + ); + yield return new (MassFractionUnit.GramPerKilogram, "GramPerKilogram", "GramsPerKilogram", BaseUnits.Undefined, + 1000 + ); + yield return new (MassFractionUnit.HectogramPerGram, "HectogramPerGram", "HectogramsPerGram", BaseUnits.Undefined, + new QuantityValue(1, 100) + ); + yield return new (MassFractionUnit.HectogramPerKilogram, "HectogramPerKilogram", "HectogramsPerKilogram", BaseUnits.Undefined, + 10 + ); + yield return new (MassFractionUnit.KilogramPerGram, "KilogramPerGram", "KilogramsPerGram", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (MassFractionUnit.KilogramPerKilogram, "KilogramPerKilogram", "KilogramsPerKilogram", BaseUnits.Undefined, + 1 + ); + yield return new (MassFractionUnit.MicrogramPerGram, "MicrogramPerGram", "MicrogramsPerGram", BaseUnits.Undefined, + 1000000 + ); + yield return new (MassFractionUnit.MicrogramPerKilogram, "MicrogramPerKilogram", "MicrogramsPerKilogram", BaseUnits.Undefined, + 1000000000 + ); + yield return new (MassFractionUnit.MilligramPerGram, "MilligramPerGram", "MilligramsPerGram", BaseUnits.Undefined, + 1000 + ); + yield return new (MassFractionUnit.MilligramPerKilogram, "MilligramPerKilogram", "MilligramsPerKilogram", BaseUnits.Undefined, + 1000000 + ); + yield return new (MassFractionUnit.NanogramPerGram, "NanogramPerGram", "NanogramsPerGram", BaseUnits.Undefined, + 1000000000 + ); + yield return new (MassFractionUnit.NanogramPerKilogram, "NanogramPerKilogram", "NanogramsPerKilogram", BaseUnits.Undefined, + 1000000000000 + ); + yield return new (MassFractionUnit.PartPerBillion, "PartPerBillion", "PartsPerBillion", BaseUnits.Undefined, + 1000000000 + ); + yield return new (MassFractionUnit.PartPerMillion, "PartPerMillion", "PartsPerMillion", BaseUnits.Undefined, + 1000000 + ); + yield return new (MassFractionUnit.PartPerThousand, "PartPerThousand", "PartsPerThousand", BaseUnits.Undefined, + 1000 + ); + yield return new (MassFractionUnit.PartPerTrillion, "PartPerTrillion", "PartsPerTrillion", BaseUnits.Undefined, + 1000000000000 + ); + yield return new (MassFractionUnit.Percent, "Percent", "Percent", BaseUnits.Undefined, + 100 + ); } } static MassFraction() { - Info = MassFractionInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MassFractionInfo.CreateDefault); } /// @@ -161,7 +204,7 @@ static MassFraction() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public MassFraction(double value, MassFractionUnit unit) + public MassFraction(QuantityValue value, MassFractionUnit unit) { _value = value; _unit = unit; @@ -172,7 +215,8 @@ public MassFraction(double value, MassFractionUnit unit) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -201,10 +245,8 @@ public MassFraction(double value, MassFractionUnit unit) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public MassFractionUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -243,189 +285,129 @@ public MassFraction(double value, MassFractionUnit unit) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentigramsPerGram => As(MassFractionUnit.CentigramPerGram); + public QuantityValue CentigramsPerGram => this.As(MassFractionUnit.CentigramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentigramsPerKilogram => As(MassFractionUnit.CentigramPerKilogram); + public QuantityValue CentigramsPerKilogram => this.As(MassFractionUnit.CentigramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecagramsPerGram => As(MassFractionUnit.DecagramPerGram); + public QuantityValue DecagramsPerGram => this.As(MassFractionUnit.DecagramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecagramsPerKilogram => As(MassFractionUnit.DecagramPerKilogram); + public QuantityValue DecagramsPerKilogram => this.As(MassFractionUnit.DecagramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecigramsPerGram => As(MassFractionUnit.DecigramPerGram); + public QuantityValue DecigramsPerGram => this.As(MassFractionUnit.DecigramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecigramsPerKilogram => As(MassFractionUnit.DecigramPerKilogram); + public QuantityValue DecigramsPerKilogram => this.As(MassFractionUnit.DecigramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecimalFractions => As(MassFractionUnit.DecimalFraction); + public QuantityValue DecimalFractions => this.As(MassFractionUnit.DecimalFraction); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerGram => As(MassFractionUnit.GramPerGram); + public QuantityValue GramsPerGram => this.As(MassFractionUnit.GramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerKilogram => As(MassFractionUnit.GramPerKilogram); + public QuantityValue GramsPerKilogram => this.As(MassFractionUnit.GramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HectogramsPerGram => As(MassFractionUnit.HectogramPerGram); + public QuantityValue HectogramsPerGram => this.As(MassFractionUnit.HectogramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HectogramsPerKilogram => As(MassFractionUnit.HectogramPerKilogram); + public QuantityValue HectogramsPerKilogram => this.As(MassFractionUnit.HectogramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerGram => As(MassFractionUnit.KilogramPerGram); + public QuantityValue KilogramsPerGram => this.As(MassFractionUnit.KilogramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerKilogram => As(MassFractionUnit.KilogramPerKilogram); + public QuantityValue KilogramsPerKilogram => this.As(MassFractionUnit.KilogramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerGram => As(MassFractionUnit.MicrogramPerGram); + public QuantityValue MicrogramsPerGram => this.As(MassFractionUnit.MicrogramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerKilogram => As(MassFractionUnit.MicrogramPerKilogram); + public QuantityValue MicrogramsPerKilogram => this.As(MassFractionUnit.MicrogramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerGram => As(MassFractionUnit.MilligramPerGram); + public QuantityValue MilligramsPerGram => this.As(MassFractionUnit.MilligramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerKilogram => As(MassFractionUnit.MilligramPerKilogram); + public QuantityValue MilligramsPerKilogram => this.As(MassFractionUnit.MilligramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanogramsPerGram => As(MassFractionUnit.NanogramPerGram); + public QuantityValue NanogramsPerGram => this.As(MassFractionUnit.NanogramPerGram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanogramsPerKilogram => As(MassFractionUnit.NanogramPerKilogram); + public QuantityValue NanogramsPerKilogram => this.As(MassFractionUnit.NanogramPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PartsPerBillion => As(MassFractionUnit.PartPerBillion); + public QuantityValue PartsPerBillion => this.As(MassFractionUnit.PartPerBillion); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PartsPerMillion => As(MassFractionUnit.PartPerMillion); + public QuantityValue PartsPerMillion => this.As(MassFractionUnit.PartPerMillion); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PartsPerThousand => As(MassFractionUnit.PartPerThousand); + public QuantityValue PartsPerThousand => this.As(MassFractionUnit.PartPerThousand); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PartsPerTrillion => As(MassFractionUnit.PartPerTrillion); + public QuantityValue PartsPerTrillion => this.As(MassFractionUnit.PartPerTrillion); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Percent => As(MassFractionUnit.Percent); + public QuantityValue Percent => this.As(MassFractionUnit.Percent); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: MassFractionUnit -> BaseUnit - unitConverter.SetConversionFunction(MassFractionUnit.CentigramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.CentigramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.DecagramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.DecagramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.DecigramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.DecigramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.GramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.GramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.HectogramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.HectogramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.KilogramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.KilogramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.MicrogramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.MicrogramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.MilligramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.MilligramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.NanogramPerGram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.NanogramPerKilogram, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.PartPerBillion, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.PartPerMillion, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.PartPerThousand, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.PartPerTrillion, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - unitConverter.SetConversionFunction(MassFractionUnit.Percent, MassFractionUnit.DecimalFraction, quantity => quantity.ToUnit(MassFractionUnit.DecimalFraction)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.DecimalFraction, quantity => quantity); - - // Register in unit converter: BaseUnit -> MassFractionUnit - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.CentigramPerGram, quantity => quantity.ToUnit(MassFractionUnit.CentigramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.CentigramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.CentigramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.DecagramPerGram, quantity => quantity.ToUnit(MassFractionUnit.DecagramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.DecagramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.DecagramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.DecigramPerGram, quantity => quantity.ToUnit(MassFractionUnit.DecigramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.DecigramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.DecigramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.GramPerGram, quantity => quantity.ToUnit(MassFractionUnit.GramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.GramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.GramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.HectogramPerGram, quantity => quantity.ToUnit(MassFractionUnit.HectogramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.HectogramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.HectogramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.KilogramPerGram, quantity => quantity.ToUnit(MassFractionUnit.KilogramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.KilogramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.KilogramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.MicrogramPerGram, quantity => quantity.ToUnit(MassFractionUnit.MicrogramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.MicrogramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.MicrogramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.MilligramPerGram, quantity => quantity.ToUnit(MassFractionUnit.MilligramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.MilligramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.MilligramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.NanogramPerGram, quantity => quantity.ToUnit(MassFractionUnit.NanogramPerGram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.NanogramPerKilogram, quantity => quantity.ToUnit(MassFractionUnit.NanogramPerKilogram)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerBillion, quantity => quantity.ToUnit(MassFractionUnit.PartPerBillion)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerMillion, quantity => quantity.ToUnit(MassFractionUnit.PartPerMillion)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerThousand, quantity => quantity.ToUnit(MassFractionUnit.PartPerThousand)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerTrillion, quantity => quantity.ToUnit(MassFractionUnit.PartPerTrillion)); - unitConverter.SetConversionFunction(MassFractionUnit.DecimalFraction, MassFractionUnit.Percent, quantity => quantity.ToUnit(MassFractionUnit.Percent)); - } - /// /// Get unit abbreviation string. /// @@ -454,7 +436,7 @@ public static string GetAbbreviation(MassFractionUnit unit, IFormatProvider? pro /// /// Creates a from . /// - public static MassFraction FromCentigramsPerGram(double value) + public static MassFraction FromCentigramsPerGram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.CentigramPerGram); } @@ -462,7 +444,7 @@ public static MassFraction FromCentigramsPerGram(double value) /// /// Creates a from . /// - public static MassFraction FromCentigramsPerKilogram(double value) + public static MassFraction FromCentigramsPerKilogram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.CentigramPerKilogram); } @@ -470,7 +452,7 @@ public static MassFraction FromCentigramsPerKilogram(double value) /// /// Creates a from . /// - public static MassFraction FromDecagramsPerGram(double value) + public static MassFraction FromDecagramsPerGram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.DecagramPerGram); } @@ -478,7 +460,7 @@ public static MassFraction FromDecagramsPerGram(double value) /// /// Creates a from . /// - public static MassFraction FromDecagramsPerKilogram(double value) + public static MassFraction FromDecagramsPerKilogram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.DecagramPerKilogram); } @@ -486,7 +468,7 @@ public static MassFraction FromDecagramsPerKilogram(double value) /// /// Creates a from . /// - public static MassFraction FromDecigramsPerGram(double value) + public static MassFraction FromDecigramsPerGram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.DecigramPerGram); } @@ -494,7 +476,7 @@ public static MassFraction FromDecigramsPerGram(double value) /// /// Creates a from . /// - public static MassFraction FromDecigramsPerKilogram(double value) + public static MassFraction FromDecigramsPerKilogram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.DecigramPerKilogram); } @@ -502,7 +484,7 @@ public static MassFraction FromDecigramsPerKilogram(double value) /// /// Creates a from . /// - public static MassFraction FromDecimalFractions(double value) + public static MassFraction FromDecimalFractions(QuantityValue value) { return new MassFraction(value, MassFractionUnit.DecimalFraction); } @@ -510,7 +492,7 @@ public static MassFraction FromDecimalFractions(double value) /// /// Creates a from . /// - public static MassFraction FromGramsPerGram(double value) + public static MassFraction FromGramsPerGram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.GramPerGram); } @@ -518,7 +500,7 @@ public static MassFraction FromGramsPerGram(double value) /// /// Creates a from . /// - public static MassFraction FromGramsPerKilogram(double value) + public static MassFraction FromGramsPerKilogram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.GramPerKilogram); } @@ -526,7 +508,7 @@ public static MassFraction FromGramsPerKilogram(double value) /// /// Creates a from . /// - public static MassFraction FromHectogramsPerGram(double value) + public static MassFraction FromHectogramsPerGram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.HectogramPerGram); } @@ -534,7 +516,7 @@ public static MassFraction FromHectogramsPerGram(double value) /// /// Creates a from . /// - public static MassFraction FromHectogramsPerKilogram(double value) + public static MassFraction FromHectogramsPerKilogram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.HectogramPerKilogram); } @@ -542,7 +524,7 @@ public static MassFraction FromHectogramsPerKilogram(double value) /// /// Creates a from . /// - public static MassFraction FromKilogramsPerGram(double value) + public static MassFraction FromKilogramsPerGram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.KilogramPerGram); } @@ -550,7 +532,7 @@ public static MassFraction FromKilogramsPerGram(double value) /// /// Creates a from . /// - public static MassFraction FromKilogramsPerKilogram(double value) + public static MassFraction FromKilogramsPerKilogram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.KilogramPerKilogram); } @@ -558,7 +540,7 @@ public static MassFraction FromKilogramsPerKilogram(double value) /// /// Creates a from . /// - public static MassFraction FromMicrogramsPerGram(double value) + public static MassFraction FromMicrogramsPerGram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.MicrogramPerGram); } @@ -566,7 +548,7 @@ public static MassFraction FromMicrogramsPerGram(double value) /// /// Creates a from . /// - public static MassFraction FromMicrogramsPerKilogram(double value) + public static MassFraction FromMicrogramsPerKilogram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.MicrogramPerKilogram); } @@ -574,7 +556,7 @@ public static MassFraction FromMicrogramsPerKilogram(double value) /// /// Creates a from . /// - public static MassFraction FromMilligramsPerGram(double value) + public static MassFraction FromMilligramsPerGram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.MilligramPerGram); } @@ -582,7 +564,7 @@ public static MassFraction FromMilligramsPerGram(double value) /// /// Creates a from . /// - public static MassFraction FromMilligramsPerKilogram(double value) + public static MassFraction FromMilligramsPerKilogram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.MilligramPerKilogram); } @@ -590,7 +572,7 @@ public static MassFraction FromMilligramsPerKilogram(double value) /// /// Creates a from . /// - public static MassFraction FromNanogramsPerGram(double value) + public static MassFraction FromNanogramsPerGram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.NanogramPerGram); } @@ -598,7 +580,7 @@ public static MassFraction FromNanogramsPerGram(double value) /// /// Creates a from . /// - public static MassFraction FromNanogramsPerKilogram(double value) + public static MassFraction FromNanogramsPerKilogram(QuantityValue value) { return new MassFraction(value, MassFractionUnit.NanogramPerKilogram); } @@ -606,7 +588,7 @@ public static MassFraction FromNanogramsPerKilogram(double value) /// /// Creates a from . /// - public static MassFraction FromPartsPerBillion(double value) + public static MassFraction FromPartsPerBillion(QuantityValue value) { return new MassFraction(value, MassFractionUnit.PartPerBillion); } @@ -614,7 +596,7 @@ public static MassFraction FromPartsPerBillion(double value) /// /// Creates a from . /// - public static MassFraction FromPartsPerMillion(double value) + public static MassFraction FromPartsPerMillion(QuantityValue value) { return new MassFraction(value, MassFractionUnit.PartPerMillion); } @@ -622,7 +604,7 @@ public static MassFraction FromPartsPerMillion(double value) /// /// Creates a from . /// - public static MassFraction FromPartsPerThousand(double value) + public static MassFraction FromPartsPerThousand(QuantityValue value) { return new MassFraction(value, MassFractionUnit.PartPerThousand); } @@ -630,7 +612,7 @@ public static MassFraction FromPartsPerThousand(double value) /// /// Creates a from . /// - public static MassFraction FromPartsPerTrillion(double value) + public static MassFraction FromPartsPerTrillion(QuantityValue value) { return new MassFraction(value, MassFractionUnit.PartPerTrillion); } @@ -638,7 +620,7 @@ public static MassFraction FromPartsPerTrillion(double value) /// /// Creates a from . /// - public static MassFraction FromPercent(double value) + public static MassFraction FromPercent(QuantityValue value) { return new MassFraction(value, MassFractionUnit.Percent); } @@ -649,7 +631,7 @@ public static MassFraction FromPercent(double value) /// Value to convert from. /// Unit to convert from. /// MassFraction unit value. - public static MassFraction From(double value, MassFractionUnit fromUnit) + public static MassFraction From(QuantityValue value, MassFractionUnit fromUnit) { return new MassFraction(value, fromUnit); } @@ -710,10 +692,7 @@ public static MassFraction Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static MassFraction Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -741,11 +720,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out MassFraction res /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out MassFraction result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -766,7 +741,7 @@ public static MassFractionUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -777,7 +752,7 @@ public static MassFractionUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out MassFractionUnit unit) { return TryParseUnit(str, null, out unit); @@ -792,7 +767,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out MassFraction /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out MassFractionUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -811,35 +786,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static MassFraction operator +(MassFraction left, MassFraction right) { - return new MassFraction(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new MassFraction(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static MassFraction operator -(MassFraction left, MassFraction right) { - return new MassFraction(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new MassFraction(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -861,97 +836,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(MassFraction left, MassFraction right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(MassFraction left, MassFraction right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(MassFraction left, MassFraction right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(MassFraction left, MassFraction right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MassFraction other, MassFraction tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(MassFraction left, MassFraction right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MassFraction other, MassFraction tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(MassFraction left, MassFraction right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MassFraction other, MassFraction tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is MassFraction otherQuantity)) + if (obj is not MassFraction otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MassFraction other, MassFraction tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(MassFraction other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current MassFraction. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(MassFraction), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MassFraction otherQuantity)) throw new ArgumentException("Expected type MassFraction.", nameof(obj)); + if (obj is not MassFraction otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -963,192 +923,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MassFraction other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassFractionUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this MassFraction to another MassFraction with the unit representation . - /// - /// The unit to convert to. - /// A MassFraction with the specified unit. - public MassFraction ToUnit(MassFractionUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A MassFraction with the specified unit. - public MassFraction ToUnit(MassFractionUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(MassFraction), Unit, typeof(MassFraction), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (MassFraction)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(MassFractionUnit unit, [NotNullWhen(true)] out MassFraction? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - MassFraction? convertedOrNull = (Unit, unit) switch - { - // MassFractionUnit -> BaseUnit - (MassFractionUnit.CentigramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction((_value) * 1e-2d, MassFractionUnit.DecimalFraction), - (MassFractionUnit.CentigramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction((_value / 1e3) * 1e-2d, MassFractionUnit.DecimalFraction), - (MassFractionUnit.DecagramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction((_value) * 1e1d, MassFractionUnit.DecimalFraction), - (MassFractionUnit.DecagramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction((_value / 1e3) * 1e1d, MassFractionUnit.DecimalFraction), - (MassFractionUnit.DecigramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction((_value) * 1e-1d, MassFractionUnit.DecimalFraction), - (MassFractionUnit.DecigramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction((_value / 1e3) * 1e-1d, MassFractionUnit.DecimalFraction), - (MassFractionUnit.GramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction(_value, MassFractionUnit.DecimalFraction), - (MassFractionUnit.GramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction(_value / 1e3, MassFractionUnit.DecimalFraction), - (MassFractionUnit.HectogramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction((_value) * 1e2d, MassFractionUnit.DecimalFraction), - (MassFractionUnit.HectogramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction((_value / 1e3) * 1e2d, MassFractionUnit.DecimalFraction), - (MassFractionUnit.KilogramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction((_value) * 1e3d, MassFractionUnit.DecimalFraction), - (MassFractionUnit.KilogramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction((_value / 1e3) * 1e3d, MassFractionUnit.DecimalFraction), - (MassFractionUnit.MicrogramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction((_value) * 1e-6d, MassFractionUnit.DecimalFraction), - (MassFractionUnit.MicrogramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction((_value / 1e3) * 1e-6d, MassFractionUnit.DecimalFraction), - (MassFractionUnit.MilligramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction((_value) * 1e-3d, MassFractionUnit.DecimalFraction), - (MassFractionUnit.MilligramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction((_value / 1e3) * 1e-3d, MassFractionUnit.DecimalFraction), - (MassFractionUnit.NanogramPerGram, MassFractionUnit.DecimalFraction) => new MassFraction((_value) * 1e-9d, MassFractionUnit.DecimalFraction), - (MassFractionUnit.NanogramPerKilogram, MassFractionUnit.DecimalFraction) => new MassFraction((_value / 1e3) * 1e-9d, MassFractionUnit.DecimalFraction), - (MassFractionUnit.PartPerBillion, MassFractionUnit.DecimalFraction) => new MassFraction(_value / 1e9, MassFractionUnit.DecimalFraction), - (MassFractionUnit.PartPerMillion, MassFractionUnit.DecimalFraction) => new MassFraction(_value / 1e6, MassFractionUnit.DecimalFraction), - (MassFractionUnit.PartPerThousand, MassFractionUnit.DecimalFraction) => new MassFraction(_value / 1e3, MassFractionUnit.DecimalFraction), - (MassFractionUnit.PartPerTrillion, MassFractionUnit.DecimalFraction) => new MassFraction(_value / 1e12, MassFractionUnit.DecimalFraction), - (MassFractionUnit.Percent, MassFractionUnit.DecimalFraction) => new MassFraction(_value / 1e2, MassFractionUnit.DecimalFraction), - - // BaseUnit -> MassFractionUnit - (MassFractionUnit.DecimalFraction, MassFractionUnit.CentigramPerGram) => new MassFraction((_value) / 1e-2d, MassFractionUnit.CentigramPerGram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.CentigramPerKilogram) => new MassFraction((_value * 1e3) / 1e-2d, MassFractionUnit.CentigramPerKilogram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.DecagramPerGram) => new MassFraction((_value) / 1e1d, MassFractionUnit.DecagramPerGram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.DecagramPerKilogram) => new MassFraction((_value * 1e3) / 1e1d, MassFractionUnit.DecagramPerKilogram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.DecigramPerGram) => new MassFraction((_value) / 1e-1d, MassFractionUnit.DecigramPerGram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.DecigramPerKilogram) => new MassFraction((_value * 1e3) / 1e-1d, MassFractionUnit.DecigramPerKilogram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.GramPerGram) => new MassFraction(_value, MassFractionUnit.GramPerGram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.GramPerKilogram) => new MassFraction(_value * 1e3, MassFractionUnit.GramPerKilogram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.HectogramPerGram) => new MassFraction((_value) / 1e2d, MassFractionUnit.HectogramPerGram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.HectogramPerKilogram) => new MassFraction((_value * 1e3) / 1e2d, MassFractionUnit.HectogramPerKilogram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.KilogramPerGram) => new MassFraction((_value) / 1e3d, MassFractionUnit.KilogramPerGram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.KilogramPerKilogram) => new MassFraction((_value * 1e3) / 1e3d, MassFractionUnit.KilogramPerKilogram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.MicrogramPerGram) => new MassFraction((_value) / 1e-6d, MassFractionUnit.MicrogramPerGram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.MicrogramPerKilogram) => new MassFraction((_value * 1e3) / 1e-6d, MassFractionUnit.MicrogramPerKilogram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.MilligramPerGram) => new MassFraction((_value) / 1e-3d, MassFractionUnit.MilligramPerGram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.MilligramPerKilogram) => new MassFraction((_value * 1e3) / 1e-3d, MassFractionUnit.MilligramPerKilogram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.NanogramPerGram) => new MassFraction((_value) / 1e-9d, MassFractionUnit.NanogramPerGram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.NanogramPerKilogram) => new MassFraction((_value * 1e3) / 1e-9d, MassFractionUnit.NanogramPerKilogram), - (MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerBillion) => new MassFraction(_value * 1e9, MassFractionUnit.PartPerBillion), - (MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerMillion) => new MassFraction(_value * 1e6, MassFractionUnit.PartPerMillion), - (MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerThousand) => new MassFraction(_value * 1e3, MassFractionUnit.PartPerThousand), - (MassFractionUnit.DecimalFraction, MassFractionUnit.PartPerTrillion) => new MassFraction(_value * 1e12, MassFractionUnit.PartPerTrillion), - (MassFractionUnit.DecimalFraction, MassFractionUnit.Percent) => new MassFraction(_value * 1e2, MassFractionUnit.Percent), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public MassFraction ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not MassFractionUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassFractionUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(MassFractionUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(MassFractionUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1163,7 +955,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs index dc91d1b23b..3d97f935f9 100644 --- a/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MassMomentOfInertia.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// A property of body reflects how its mass is distributed with regard to an axis. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct MassMomentOfInertia : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly MassMomentOfInertiaUnit? _unit; /// @@ -101,7 +100,7 @@ public static MassMomentOfInertiaInfo CreateDefault(Func - /// The for is [L^2][M]. + /// The for is L^2M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, 0, 0, 0, 0, 0); @@ -116,42 +115,94 @@ public static MassMomentOfInertiaInfo CreateDefault(FuncAn of representing the default unit mappings for MassMomentOfInertia. public static IEnumerable> GetDefaultMappings() { - yield return new (MassMomentOfInertiaUnit.GramSquareCentimeter, "GramSquareCentimeter", "GramSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram)); - yield return new (MassMomentOfInertiaUnit.GramSquareDecimeter, "GramSquareDecimeter", "GramSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Gram)); - yield return new (MassMomentOfInertiaUnit.GramSquareMeter, "GramSquareMeter", "GramSquareMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram)); - yield return new (MassMomentOfInertiaUnit.GramSquareMillimeter, "GramSquareMillimeter", "GramSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram)); - yield return new (MassMomentOfInertiaUnit.KilogramSquareCentimeter, "KilogramSquareCentimeter", "KilogramSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram)); - yield return new (MassMomentOfInertiaUnit.KilogramSquareDecimeter, "KilogramSquareDecimeter", "KilogramSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram)); + yield return new (MassMomentOfInertiaUnit.GramSquareCentimeter, "GramSquareCentimeter", "GramSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Gram), + 10000000 + ); + yield return new (MassMomentOfInertiaUnit.GramSquareDecimeter, "GramSquareDecimeter", "GramSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Gram), + 100000 + ); + yield return new (MassMomentOfInertiaUnit.GramSquareMeter, "GramSquareMeter", "GramSquareMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram), + 1000 + ); + yield return new (MassMomentOfInertiaUnit.GramSquareMillimeter, "GramSquareMillimeter", "GramSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Gram), + 1000000000 + ); + yield return new (MassMomentOfInertiaUnit.KilogramSquareCentimeter, "KilogramSquareCentimeter", "KilogramSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram), + 10000 + ); + yield return new (MassMomentOfInertiaUnit.KilogramSquareDecimeter, "KilogramSquareDecimeter", "KilogramSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram), + 100 + ); yield return new (MassMomentOfInertiaUnit.KilogramSquareMeter, "KilogramSquareMeter", "KilogramSquareMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram)); - yield return new (MassMomentOfInertiaUnit.KilogramSquareMillimeter, "KilogramSquareMillimeter", "KilogramSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram)); - yield return new (MassMomentOfInertiaUnit.KilotonneSquareCentimeter, "KilotonneSquareCentimeter", "KilotonneSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilotonne)); - yield return new (MassMomentOfInertiaUnit.KilotonneSquareDecimeter, "KilotonneSquareDecimeter", "KilotonneSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilotonne)); - yield return new (MassMomentOfInertiaUnit.KilotonneSquareMeter, "KilotonneSquareMeter", "KilotonneSquareMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilotonne)); - yield return new (MassMomentOfInertiaUnit.KilotonneSquareMillimeter, "KilotonneSquareMillimeter", "KilotonneSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilotonne)); - yield return new (MassMomentOfInertiaUnit.MegatonneSquareCentimeter, "MegatonneSquareCentimeter", "MegatonneSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Megatonne)); - yield return new (MassMomentOfInertiaUnit.MegatonneSquareDecimeter, "MegatonneSquareDecimeter", "MegatonneSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Megatonne)); - yield return new (MassMomentOfInertiaUnit.MegatonneSquareMeter, "MegatonneSquareMeter", "MegatonneSquareMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Megatonne)); - yield return new (MassMomentOfInertiaUnit.MegatonneSquareMillimeter, "MegatonneSquareMillimeter", "MegatonneSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Megatonne)); - yield return new (MassMomentOfInertiaUnit.MilligramSquareCentimeter, "MilligramSquareCentimeter", "MilligramSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Milligram)); - yield return new (MassMomentOfInertiaUnit.MilligramSquareDecimeter, "MilligramSquareDecimeter", "MilligramSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Milligram)); - yield return new (MassMomentOfInertiaUnit.MilligramSquareMeter, "MilligramSquareMeter", "MilligramSquareMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram)); - yield return new (MassMomentOfInertiaUnit.MilligramSquareMillimeter, "MilligramSquareMillimeter", "MilligramSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Milligram)); - yield return new (MassMomentOfInertiaUnit.PoundSquareFoot, "PoundSquareFoot", "PoundSquareFeet", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound)); - yield return new (MassMomentOfInertiaUnit.PoundSquareInch, "PoundSquareInch", "PoundSquareInches", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound)); - yield return new (MassMomentOfInertiaUnit.SlugSquareFoot, "SlugSquareFoot", "SlugSquareFeet", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Slug)); - yield return new (MassMomentOfInertiaUnit.SlugSquareInch, "SlugSquareInch", "SlugSquareInches", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Slug)); - yield return new (MassMomentOfInertiaUnit.TonneSquareCentimeter, "TonneSquareCentimeter", "TonneSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Tonne)); - yield return new (MassMomentOfInertiaUnit.TonneSquareDecimeter, "TonneSquareDecimeter", "TonneSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Tonne)); - yield return new (MassMomentOfInertiaUnit.TonneSquareMeter, "TonneSquareMeter", "TonneSquareMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Tonne)); - yield return new (MassMomentOfInertiaUnit.TonneSquareMillimeter, "TonneSquareMillimeter", "TonneSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Tonne)); + yield return new (MassMomentOfInertiaUnit.KilogramSquareMillimeter, "KilogramSquareMillimeter", "KilogramSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram), + 1000000 + ); + yield return new (MassMomentOfInertiaUnit.KilotonneSquareCentimeter, "KilotonneSquareCentimeter", "KilotonneSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilotonne), + new QuantityValue(1, 100) + ); + yield return new (MassMomentOfInertiaUnit.KilotonneSquareDecimeter, "KilotonneSquareDecimeter", "KilotonneSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilotonne), + new QuantityValue(1, 10000) + ); + yield return new (MassMomentOfInertiaUnit.KilotonneSquareMeter, "KilotonneSquareMeter", "KilotonneSquareMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilotonne), + new QuantityValue(1, 1000000) + ); + yield return new (MassMomentOfInertiaUnit.KilotonneSquareMillimeter, "KilotonneSquareMillimeter", "KilotonneSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilotonne), + 1 + ); + yield return new (MassMomentOfInertiaUnit.MegatonneSquareCentimeter, "MegatonneSquareCentimeter", "MegatonneSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Megatonne), + new QuantityValue(1, 100000) + ); + yield return new (MassMomentOfInertiaUnit.MegatonneSquareDecimeter, "MegatonneSquareDecimeter", "MegatonneSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Megatonne), + new QuantityValue(1, 10000000) + ); + yield return new (MassMomentOfInertiaUnit.MegatonneSquareMeter, "MegatonneSquareMeter", "MegatonneSquareMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Megatonne), + new QuantityValue(1, 1000000000) + ); + yield return new (MassMomentOfInertiaUnit.MegatonneSquareMillimeter, "MegatonneSquareMillimeter", "MegatonneSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Megatonne), + new QuantityValue(1, 1000) + ); + yield return new (MassMomentOfInertiaUnit.MilligramSquareCentimeter, "MilligramSquareCentimeter", "MilligramSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Milligram), + 10000000000 + ); + yield return new (MassMomentOfInertiaUnit.MilligramSquareDecimeter, "MilligramSquareDecimeter", "MilligramSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Milligram), + 100000000 + ); + yield return new (MassMomentOfInertiaUnit.MilligramSquareMeter, "MilligramSquareMeter", "MilligramSquareMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram), + 1000000 + ); + yield return new (MassMomentOfInertiaUnit.MilligramSquareMillimeter, "MilligramSquareMillimeter", "MilligramSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Milligram), + 1000000000000 + ); + yield return new (MassMomentOfInertiaUnit.PoundSquareFoot, "PoundSquareFoot", "PoundSquareFeet", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound), + new QuantityValue(156250000000000, 6584392202157) + ); + yield return new (MassMomentOfInertiaUnit.PoundSquareInch, "PoundSquareInch", "PoundSquareInches", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound), + new QuantityValue(2500000000000000, 731599133573) + ); + yield return new (MassMomentOfInertiaUnit.SlugSquareFoot, "SlugSquareFoot", "SlugSquareFeet", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Slug), + new QuantityValue(2500000000000000, 3389544870828501) + ); + yield return new (MassMomentOfInertiaUnit.SlugSquareInch, "SlugSquareInch", "SlugSquareInches", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Slug), + new QuantityValue(120000000000000000, 1129848290276167) + ); + yield return new (MassMomentOfInertiaUnit.TonneSquareCentimeter, "TonneSquareCentimeter", "TonneSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Tonne), + 10 + ); + yield return new (MassMomentOfInertiaUnit.TonneSquareDecimeter, "TonneSquareDecimeter", "TonneSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Tonne), + new QuantityValue(1, 10) + ); + yield return new (MassMomentOfInertiaUnit.TonneSquareMeter, "TonneSquareMeter", "TonneSquareMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Tonne), + new QuantityValue(1, 1000) + ); + yield return new (MassMomentOfInertiaUnit.TonneSquareMillimeter, "TonneSquareMillimeter", "TonneSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Tonne), + 1000 + ); } } static MassMomentOfInertia() { - Info = MassMomentOfInertiaInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MassMomentOfInertiaInfo.CreateDefault); } /// @@ -159,7 +210,7 @@ static MassMomentOfInertia() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public MassMomentOfInertia(double value, MassMomentOfInertiaUnit unit) + public MassMomentOfInertia(QuantityValue value, MassMomentOfInertiaUnit unit) { _value = value; _unit = unit; @@ -173,7 +224,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -184,7 +235,8 @@ public MassMomentOfInertia(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -213,10 +265,8 @@ public MassMomentOfInertia(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public MassMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -255,217 +305,149 @@ public MassMomentOfInertia(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramSquareCentimeters => As(MassMomentOfInertiaUnit.GramSquareCentimeter); + public QuantityValue GramSquareCentimeters => this.As(MassMomentOfInertiaUnit.GramSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramSquareDecimeters => As(MassMomentOfInertiaUnit.GramSquareDecimeter); + public QuantityValue GramSquareDecimeters => this.As(MassMomentOfInertiaUnit.GramSquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramSquareMeters => As(MassMomentOfInertiaUnit.GramSquareMeter); + public QuantityValue GramSquareMeters => this.As(MassMomentOfInertiaUnit.GramSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramSquareMillimeters => As(MassMomentOfInertiaUnit.GramSquareMillimeter); + public QuantityValue GramSquareMillimeters => this.As(MassMomentOfInertiaUnit.GramSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramSquareCentimeters => As(MassMomentOfInertiaUnit.KilogramSquareCentimeter); + public QuantityValue KilogramSquareCentimeters => this.As(MassMomentOfInertiaUnit.KilogramSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramSquareDecimeters => As(MassMomentOfInertiaUnit.KilogramSquareDecimeter); + public QuantityValue KilogramSquareDecimeters => this.As(MassMomentOfInertiaUnit.KilogramSquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramSquareMeters => As(MassMomentOfInertiaUnit.KilogramSquareMeter); + public QuantityValue KilogramSquareMeters => this.As(MassMomentOfInertiaUnit.KilogramSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramSquareMillimeters => As(MassMomentOfInertiaUnit.KilogramSquareMillimeter); + public QuantityValue KilogramSquareMillimeters => this.As(MassMomentOfInertiaUnit.KilogramSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilotonneSquareCentimeters => As(MassMomentOfInertiaUnit.KilotonneSquareCentimeter); + public QuantityValue KilotonneSquareCentimeters => this.As(MassMomentOfInertiaUnit.KilotonneSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilotonneSquareDecimeters => As(MassMomentOfInertiaUnit.KilotonneSquareDecimeter); + public QuantityValue KilotonneSquareDecimeters => this.As(MassMomentOfInertiaUnit.KilotonneSquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilotonneSquareMeters => As(MassMomentOfInertiaUnit.KilotonneSquareMeter); + public QuantityValue KilotonneSquareMeters => this.As(MassMomentOfInertiaUnit.KilotonneSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilotonneSquareMillimeters => As(MassMomentOfInertiaUnit.KilotonneSquareMillimeter); + public QuantityValue KilotonneSquareMillimeters => this.As(MassMomentOfInertiaUnit.KilotonneSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegatonneSquareCentimeters => As(MassMomentOfInertiaUnit.MegatonneSquareCentimeter); + public QuantityValue MegatonneSquareCentimeters => this.As(MassMomentOfInertiaUnit.MegatonneSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegatonneSquareDecimeters => As(MassMomentOfInertiaUnit.MegatonneSquareDecimeter); + public QuantityValue MegatonneSquareDecimeters => this.As(MassMomentOfInertiaUnit.MegatonneSquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegatonneSquareMeters => As(MassMomentOfInertiaUnit.MegatonneSquareMeter); + public QuantityValue MegatonneSquareMeters => this.As(MassMomentOfInertiaUnit.MegatonneSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegatonneSquareMillimeters => As(MassMomentOfInertiaUnit.MegatonneSquareMillimeter); + public QuantityValue MegatonneSquareMillimeters => this.As(MassMomentOfInertiaUnit.MegatonneSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramSquareCentimeters => As(MassMomentOfInertiaUnit.MilligramSquareCentimeter); + public QuantityValue MilligramSquareCentimeters => this.As(MassMomentOfInertiaUnit.MilligramSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramSquareDecimeters => As(MassMomentOfInertiaUnit.MilligramSquareDecimeter); + public QuantityValue MilligramSquareDecimeters => this.As(MassMomentOfInertiaUnit.MilligramSquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramSquareMeters => As(MassMomentOfInertiaUnit.MilligramSquareMeter); + public QuantityValue MilligramSquareMeters => this.As(MassMomentOfInertiaUnit.MilligramSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramSquareMillimeters => As(MassMomentOfInertiaUnit.MilligramSquareMillimeter); + public QuantityValue MilligramSquareMillimeters => this.As(MassMomentOfInertiaUnit.MilligramSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundSquareFeet => As(MassMomentOfInertiaUnit.PoundSquareFoot); + public QuantityValue PoundSquareFeet => this.As(MassMomentOfInertiaUnit.PoundSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundSquareInches => As(MassMomentOfInertiaUnit.PoundSquareInch); + public QuantityValue PoundSquareInches => this.As(MassMomentOfInertiaUnit.PoundSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SlugSquareFeet => As(MassMomentOfInertiaUnit.SlugSquareFoot); + public QuantityValue SlugSquareFeet => this.As(MassMomentOfInertiaUnit.SlugSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SlugSquareInches => As(MassMomentOfInertiaUnit.SlugSquareInch); + public QuantityValue SlugSquareInches => this.As(MassMomentOfInertiaUnit.SlugSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonneSquareCentimeters => As(MassMomentOfInertiaUnit.TonneSquareCentimeter); + public QuantityValue TonneSquareCentimeters => this.As(MassMomentOfInertiaUnit.TonneSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonneSquareDecimeters => As(MassMomentOfInertiaUnit.TonneSquareDecimeter); + public QuantityValue TonneSquareDecimeters => this.As(MassMomentOfInertiaUnit.TonneSquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonneSquareMeters => As(MassMomentOfInertiaUnit.TonneSquareMeter); + public QuantityValue TonneSquareMeters => this.As(MassMomentOfInertiaUnit.TonneSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonneSquareMillimeters => As(MassMomentOfInertiaUnit.TonneSquareMillimeter); + public QuantityValue TonneSquareMillimeters => this.As(MassMomentOfInertiaUnit.TonneSquareMillimeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: MassMomentOfInertiaUnit -> BaseUnit - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.GramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.GramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.GramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.GramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilotonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilotonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilotonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilotonneSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MegatonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MegatonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MegatonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MegatonneSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MilligramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MilligramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MilligramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.MilligramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.PoundSquareFoot, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.PoundSquareInch, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.SlugSquareFoot, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.SlugSquareInch, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.TonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.TonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.TonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.TonneSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> MassMomentOfInertiaUnit - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.GramSquareCentimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.GramSquareDecimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.GramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareMillimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.GramSquareMillimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareCentimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareDecimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMillimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilogramSquareMillimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareCentimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareDecimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareMillimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.KilotonneSquareMillimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareCentimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareDecimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareMillimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MegatonneSquareMillimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MilligramSquareCentimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MilligramSquareDecimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MilligramSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareMillimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.MilligramSquareMillimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.PoundSquareFoot, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.PoundSquareFoot)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.PoundSquareInch, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.PoundSquareInch)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.SlugSquareFoot, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.SlugSquareFoot)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.SlugSquareInch, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.SlugSquareInch)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareCentimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.TonneSquareCentimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareDecimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.TonneSquareDecimeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareMeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.TonneSquareMeter)); - unitConverter.SetConversionFunction(MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareMillimeter, quantity => quantity.ToUnit(MassMomentOfInertiaUnit.TonneSquareMillimeter)); - } - /// /// Get unit abbreviation string. /// @@ -494,7 +476,7 @@ public static string GetAbbreviation(MassMomentOfInertiaUnit unit, IFormatProvid /// /// Creates a from . /// - public static MassMomentOfInertia FromGramSquareCentimeters(double value) + public static MassMomentOfInertia FromGramSquareCentimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareCentimeter); } @@ -502,7 +484,7 @@ public static MassMomentOfInertia FromGramSquareCentimeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromGramSquareDecimeters(double value) + public static MassMomentOfInertia FromGramSquareDecimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareDecimeter); } @@ -510,7 +492,7 @@ public static MassMomentOfInertia FromGramSquareDecimeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromGramSquareMeters(double value) + public static MassMomentOfInertia FromGramSquareMeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMeter); } @@ -518,7 +500,7 @@ public static MassMomentOfInertia FromGramSquareMeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromGramSquareMillimeters(double value) + public static MassMomentOfInertia FromGramSquareMillimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.GramSquareMillimeter); } @@ -526,7 +508,7 @@ public static MassMomentOfInertia FromGramSquareMillimeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromKilogramSquareCentimeters(double value) + public static MassMomentOfInertia FromKilogramSquareCentimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareCentimeter); } @@ -534,7 +516,7 @@ public static MassMomentOfInertia FromKilogramSquareCentimeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromKilogramSquareDecimeters(double value) + public static MassMomentOfInertia FromKilogramSquareDecimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareDecimeter); } @@ -542,7 +524,7 @@ public static MassMomentOfInertia FromKilogramSquareDecimeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromKilogramSquareMeters(double value) + public static MassMomentOfInertia FromKilogramSquareMeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMeter); } @@ -550,7 +532,7 @@ public static MassMomentOfInertia FromKilogramSquareMeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromKilogramSquareMillimeters(double value) + public static MassMomentOfInertia FromKilogramSquareMillimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilogramSquareMillimeter); } @@ -558,7 +540,7 @@ public static MassMomentOfInertia FromKilogramSquareMillimeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromKilotonneSquareCentimeters(double value) + public static MassMomentOfInertia FromKilotonneSquareCentimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareCentimeter); } @@ -566,7 +548,7 @@ public static MassMomentOfInertia FromKilotonneSquareCentimeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromKilotonneSquareDecimeters(double value) + public static MassMomentOfInertia FromKilotonneSquareDecimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareDecimeter); } @@ -574,7 +556,7 @@ public static MassMomentOfInertia FromKilotonneSquareDecimeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromKilotonneSquareMeters(double value) + public static MassMomentOfInertia FromKilotonneSquareMeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMeter); } @@ -582,7 +564,7 @@ public static MassMomentOfInertia FromKilotonneSquareMeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromKilotonneSquareMillimeters(double value) + public static MassMomentOfInertia FromKilotonneSquareMillimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.KilotonneSquareMillimeter); } @@ -590,7 +572,7 @@ public static MassMomentOfInertia FromKilotonneSquareMillimeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromMegatonneSquareCentimeters(double value) + public static MassMomentOfInertia FromMegatonneSquareCentimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareCentimeter); } @@ -598,7 +580,7 @@ public static MassMomentOfInertia FromMegatonneSquareCentimeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromMegatonneSquareDecimeters(double value) + public static MassMomentOfInertia FromMegatonneSquareDecimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareDecimeter); } @@ -606,7 +588,7 @@ public static MassMomentOfInertia FromMegatonneSquareDecimeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromMegatonneSquareMeters(double value) + public static MassMomentOfInertia FromMegatonneSquareMeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMeter); } @@ -614,7 +596,7 @@ public static MassMomentOfInertia FromMegatonneSquareMeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromMegatonneSquareMillimeters(double value) + public static MassMomentOfInertia FromMegatonneSquareMillimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MegatonneSquareMillimeter); } @@ -622,7 +604,7 @@ public static MassMomentOfInertia FromMegatonneSquareMillimeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromMilligramSquareCentimeters(double value) + public static MassMomentOfInertia FromMilligramSquareCentimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareCentimeter); } @@ -630,7 +612,7 @@ public static MassMomentOfInertia FromMilligramSquareCentimeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromMilligramSquareDecimeters(double value) + public static MassMomentOfInertia FromMilligramSquareDecimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareDecimeter); } @@ -638,7 +620,7 @@ public static MassMomentOfInertia FromMilligramSquareDecimeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromMilligramSquareMeters(double value) + public static MassMomentOfInertia FromMilligramSquareMeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMeter); } @@ -646,7 +628,7 @@ public static MassMomentOfInertia FromMilligramSquareMeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromMilligramSquareMillimeters(double value) + public static MassMomentOfInertia FromMilligramSquareMillimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.MilligramSquareMillimeter); } @@ -654,7 +636,7 @@ public static MassMomentOfInertia FromMilligramSquareMillimeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromPoundSquareFeet(double value) + public static MassMomentOfInertia FromPoundSquareFeet(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareFoot); } @@ -662,7 +644,7 @@ public static MassMomentOfInertia FromPoundSquareFeet(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromPoundSquareInches(double value) + public static MassMomentOfInertia FromPoundSquareInches(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.PoundSquareInch); } @@ -670,7 +652,7 @@ public static MassMomentOfInertia FromPoundSquareInches(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromSlugSquareFeet(double value) + public static MassMomentOfInertia FromSlugSquareFeet(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareFoot); } @@ -678,7 +660,7 @@ public static MassMomentOfInertia FromSlugSquareFeet(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromSlugSquareInches(double value) + public static MassMomentOfInertia FromSlugSquareInches(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.SlugSquareInch); } @@ -686,7 +668,7 @@ public static MassMomentOfInertia FromSlugSquareInches(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromTonneSquareCentimeters(double value) + public static MassMomentOfInertia FromTonneSquareCentimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareCentimeter); } @@ -694,7 +676,7 @@ public static MassMomentOfInertia FromTonneSquareCentimeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromTonneSquareDecimeters(double value) + public static MassMomentOfInertia FromTonneSquareDecimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareDecimeter); } @@ -702,7 +684,7 @@ public static MassMomentOfInertia FromTonneSquareDecimeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromTonneSquareMeters(double value) + public static MassMomentOfInertia FromTonneSquareMeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMeter); } @@ -710,7 +692,7 @@ public static MassMomentOfInertia FromTonneSquareMeters(double value) /// /// Creates a from . /// - public static MassMomentOfInertia FromTonneSquareMillimeters(double value) + public static MassMomentOfInertia FromTonneSquareMillimeters(QuantityValue value) { return new MassMomentOfInertia(value, MassMomentOfInertiaUnit.TonneSquareMillimeter); } @@ -721,7 +703,7 @@ public static MassMomentOfInertia FromTonneSquareMillimeters(double value) /// Value to convert from. /// Unit to convert from. /// MassMomentOfInertia unit value. - public static MassMomentOfInertia From(double value, MassMomentOfInertiaUnit fromUnit) + public static MassMomentOfInertia From(QuantityValue value, MassMomentOfInertiaUnit fromUnit) { return new MassMomentOfInertia(value, fromUnit); } @@ -782,10 +764,7 @@ public static MassMomentOfInertia Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static MassMomentOfInertia Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -813,11 +792,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out MassMomentOfIner /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out MassMomentOfInertia result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -838,7 +813,7 @@ public static MassMomentOfInertiaUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -849,7 +824,7 @@ public static MassMomentOfInertiaUnit ParseUnit(string str, IFormatProvider? pro return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out MassMomentOfInertiaUnit unit) { return TryParseUnit(str, null, out unit); @@ -864,7 +839,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out MassMomentOf /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out MassMomentOfInertiaUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -883,35 +858,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static MassMomentOfInertia operator +(MassMomentOfInertia left, MassMomentOfInertia right) { - return new MassMomentOfInertia(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new MassMomentOfInertia(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static MassMomentOfInertia operator -(MassMomentOfInertia left, MassMomentOfInertia right) { - return new MassMomentOfInertia(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new MassMomentOfInertia(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -923,97 +898,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(MassMomentOfInertia left, MassMomentOfInertia right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(MassMomentOfInertia left, MassMomentOfInertia right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(MassMomentOfInertia left, MassMomentOfInertia right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(MassMomentOfInertia left, MassMomentOfInertia right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MassMomentOfInertia other, MassMomentOfInertia tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(MassMomentOfInertia left, MassMomentOfInertia right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MassMomentOfInertia other, MassMomentOfInertia tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(MassMomentOfInertia left, MassMomentOfInertia right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MassMomentOfInertia other, MassMomentOfInertia tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is MassMomentOfInertia otherQuantity)) + if (obj is not MassMomentOfInertia otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MassMomentOfInertia other, MassMomentOfInertia tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(MassMomentOfInertia other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current MassMomentOfInertia. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(MassMomentOfInertia), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MassMomentOfInertia otherQuantity)) throw new ArgumentException("Expected type MassMomentOfInertia.", nameof(obj)); + if (obj is not MassMomentOfInertia otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1025,200 +985,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MassMomentOfInertia other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MassMomentOfInertiaUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this MassMomentOfInertia to another MassMomentOfInertia with the unit representation . - /// - /// The unit to convert to. - /// A MassMomentOfInertia with the specified unit. - public MassMomentOfInertia ToUnit(MassMomentOfInertiaUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A MassMomentOfInertia with the specified unit. - public MassMomentOfInertia ToUnit(MassMomentOfInertiaUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(MassMomentOfInertia), Unit, typeof(MassMomentOfInertia), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (MassMomentOfInertia)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(MassMomentOfInertiaUnit unit, [NotNullWhen(true)] out MassMomentOfInertia? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - MassMomentOfInertia? convertedOrNull = (Unit, unit) switch - { - // MassMomentOfInertiaUnit -> BaseUnit - (MassMomentOfInertiaUnit.GramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value / 1e7, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.GramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value / 1e5, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.GramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value / 1e3, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.GramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value / 1e9, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.KilogramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e7) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.KilogramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e5) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.KilogramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e9) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.KilotonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e1) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.KilotonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e-1) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.KilotonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e-3) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.KilotonneSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e3) * 1e3d, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.MegatonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e1) * 1e6d, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.MegatonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e-1) * 1e6d, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.MegatonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e-3) * 1e6d, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.MegatonneSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e3) * 1e6d, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.MilligramSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e7) * 1e-3d, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.MilligramSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e5) * 1e-3d, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.MilligramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e3) * 1e-3d, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.MilligramSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia((_value / 1e9) * 1e-3d, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.PoundSquareFoot, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value * (0.45359237 * 9.290304e-2), MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.PoundSquareInch, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value * (0.45359237 * 0.00064516), MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.SlugSquareFoot, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value * 0.45359237 * 9.290304e-2 * 9.80665 / 0.3048, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.SlugSquareInch, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value * 0.45359237 * 0.00064516 * 9.80665 / 0.3048, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.TonneSquareCentimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value / 1e1, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.TonneSquareDecimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value / 1e-1, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.TonneSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value / 1e-3, MassMomentOfInertiaUnit.KilogramSquareMeter), - (MassMomentOfInertiaUnit.TonneSquareMillimeter, MassMomentOfInertiaUnit.KilogramSquareMeter) => new MassMomentOfInertia(_value / 1e3, MassMomentOfInertiaUnit.KilogramSquareMeter), - - // BaseUnit -> MassMomentOfInertiaUnit - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareCentimeter) => new MassMomentOfInertia(_value * 1e7, MassMomentOfInertiaUnit.GramSquareCentimeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareDecimeter) => new MassMomentOfInertia(_value * 1e5, MassMomentOfInertiaUnit.GramSquareDecimeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareMeter) => new MassMomentOfInertia(_value * 1e3, MassMomentOfInertiaUnit.GramSquareMeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.GramSquareMillimeter) => new MassMomentOfInertia(_value * 1e9, MassMomentOfInertiaUnit.GramSquareMillimeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareCentimeter) => new MassMomentOfInertia((_value * 1e7) / 1e3d, MassMomentOfInertiaUnit.KilogramSquareCentimeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareDecimeter) => new MassMomentOfInertia((_value * 1e5) / 1e3d, MassMomentOfInertiaUnit.KilogramSquareDecimeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilogramSquareMillimeter) => new MassMomentOfInertia((_value * 1e9) / 1e3d, MassMomentOfInertiaUnit.KilogramSquareMillimeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareCentimeter) => new MassMomentOfInertia((_value * 1e1) / 1e3d, MassMomentOfInertiaUnit.KilotonneSquareCentimeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareDecimeter) => new MassMomentOfInertia((_value * 1e-1) / 1e3d, MassMomentOfInertiaUnit.KilotonneSquareDecimeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareMeter) => new MassMomentOfInertia((_value * 1e-3) / 1e3d, MassMomentOfInertiaUnit.KilotonneSquareMeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.KilotonneSquareMillimeter) => new MassMomentOfInertia((_value * 1e3) / 1e3d, MassMomentOfInertiaUnit.KilotonneSquareMillimeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareCentimeter) => new MassMomentOfInertia((_value * 1e1) / 1e6d, MassMomentOfInertiaUnit.MegatonneSquareCentimeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareDecimeter) => new MassMomentOfInertia((_value * 1e-1) / 1e6d, MassMomentOfInertiaUnit.MegatonneSquareDecimeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareMeter) => new MassMomentOfInertia((_value * 1e-3) / 1e6d, MassMomentOfInertiaUnit.MegatonneSquareMeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MegatonneSquareMillimeter) => new MassMomentOfInertia((_value * 1e3) / 1e6d, MassMomentOfInertiaUnit.MegatonneSquareMillimeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareCentimeter) => new MassMomentOfInertia((_value * 1e7) / 1e-3d, MassMomentOfInertiaUnit.MilligramSquareCentimeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareDecimeter) => new MassMomentOfInertia((_value * 1e5) / 1e-3d, MassMomentOfInertiaUnit.MilligramSquareDecimeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareMeter) => new MassMomentOfInertia((_value * 1e3) / 1e-3d, MassMomentOfInertiaUnit.MilligramSquareMeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.MilligramSquareMillimeter) => new MassMomentOfInertia((_value * 1e9) / 1e-3d, MassMomentOfInertiaUnit.MilligramSquareMillimeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.PoundSquareFoot) => new MassMomentOfInertia(_value / (0.45359237 * 9.290304e-2), MassMomentOfInertiaUnit.PoundSquareFoot), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.PoundSquareInch) => new MassMomentOfInertia(_value / (0.45359237 * 0.00064516), MassMomentOfInertiaUnit.PoundSquareInch), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.SlugSquareFoot) => new MassMomentOfInertia(_value * 0.3048 / (0.45359237 * 9.290304e-2 * 9.80665), MassMomentOfInertiaUnit.SlugSquareFoot), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.SlugSquareInch) => new MassMomentOfInertia(_value * 0.3048 / (0.45359237 * 0.00064516 * 9.80665), MassMomentOfInertiaUnit.SlugSquareInch), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareCentimeter) => new MassMomentOfInertia(_value * 1e1, MassMomentOfInertiaUnit.TonneSquareCentimeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareDecimeter) => new MassMomentOfInertia(_value * 1e-1, MassMomentOfInertiaUnit.TonneSquareDecimeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareMeter) => new MassMomentOfInertia(_value * 1e-3, MassMomentOfInertiaUnit.TonneSquareMeter), - (MassMomentOfInertiaUnit.KilogramSquareMeter, MassMomentOfInertiaUnit.TonneSquareMillimeter) => new MassMomentOfInertia(_value * 1e3, MassMomentOfInertiaUnit.TonneSquareMillimeter), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public MassMomentOfInertia ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not MassMomentOfInertiaUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MassMomentOfInertiaUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(MassMomentOfInertiaUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(MassMomentOfInertiaUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1233,7 +1017,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Molality.g.cs b/UnitsNet/GeneratedCode/Quantities/Molality.g.cs index 332dcbb159..83ede28f29 100644 --- a/UnitsNet/GeneratedCode/Quantities/Molality.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Molality.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Molality /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Molality : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly MolalityUnit? _unit; /// @@ -104,7 +103,7 @@ public static MolalityInfo CreateDefault(Func - /// The for is [M^-1][N]. + /// The for is M^-1N. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, -1, 0, 0, 0, 1, 0); @@ -119,17 +118,19 @@ public static MolalityInfo CreateDefault(FuncAn of representing the default unit mappings for Molality. public static IEnumerable> GetDefaultMappings() { - yield return new (MolalityUnit.MillimolePerKilogram, "MillimolePerKilogram", "MillimolesPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, amount: AmountOfSubstanceUnit.Millimole)); - yield return new (MolalityUnit.MolePerGram, "MolePerGram", "MolesPerGram", new BaseUnits(mass: MassUnit.Gram, amount: AmountOfSubstanceUnit.Mole)); + yield return new (MolalityUnit.MillimolePerKilogram, "MillimolePerKilogram", "MillimolesPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, amount: AmountOfSubstanceUnit.Millimole), + 1000 + ); + yield return new (MolalityUnit.MolePerGram, "MolePerGram", "MolesPerGram", new BaseUnits(mass: MassUnit.Gram, amount: AmountOfSubstanceUnit.Mole), + new QuantityValue(1, 1000) + ); yield return new (MolalityUnit.MolePerKilogram, "MolePerKilogram", "MolesPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, amount: AmountOfSubstanceUnit.Mole)); } } static Molality() { - Info = MolalityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MolalityInfo.CreateDefault); } /// @@ -137,7 +138,7 @@ static Molality() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Molality(double value, MolalityUnit unit) + public Molality(QuantityValue value, MolalityUnit unit) { _value = value; _unit = unit; @@ -151,7 +152,7 @@ public Molality(double value, MolalityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Molality(double value, UnitSystem unitSystem) + public Molality(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -162,7 +163,8 @@ public Molality(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -191,10 +193,8 @@ public Molality(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public MolalityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -233,42 +233,24 @@ public Molality(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimolesPerKilogram => As(MolalityUnit.MillimolePerKilogram); + public QuantityValue MillimolesPerKilogram => this.As(MolalityUnit.MillimolePerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MolesPerGram => As(MolalityUnit.MolePerGram); + public QuantityValue MolesPerGram => this.As(MolalityUnit.MolePerGram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MolesPerKilogram => As(MolalityUnit.MolePerKilogram); + public QuantityValue MolesPerKilogram => this.As(MolalityUnit.MolePerKilogram); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: MolalityUnit -> BaseUnit - unitConverter.SetConversionFunction(MolalityUnit.MillimolePerKilogram, MolalityUnit.MolePerKilogram, quantity => quantity.ToUnit(MolalityUnit.MolePerKilogram)); - unitConverter.SetConversionFunction(MolalityUnit.MolePerGram, MolalityUnit.MolePerKilogram, quantity => quantity.ToUnit(MolalityUnit.MolePerKilogram)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(MolalityUnit.MolePerKilogram, MolalityUnit.MolePerKilogram, quantity => quantity); - - // Register in unit converter: BaseUnit -> MolalityUnit - unitConverter.SetConversionFunction(MolalityUnit.MolePerKilogram, MolalityUnit.MillimolePerKilogram, quantity => quantity.ToUnit(MolalityUnit.MillimolePerKilogram)); - unitConverter.SetConversionFunction(MolalityUnit.MolePerKilogram, MolalityUnit.MolePerGram, quantity => quantity.ToUnit(MolalityUnit.MolePerGram)); - } - /// /// Get unit abbreviation string. /// @@ -297,7 +279,7 @@ public static string GetAbbreviation(MolalityUnit unit, IFormatProvider? provide /// /// Creates a from . /// - public static Molality FromMillimolesPerKilogram(double value) + public static Molality FromMillimolesPerKilogram(QuantityValue value) { return new Molality(value, MolalityUnit.MillimolePerKilogram); } @@ -305,7 +287,7 @@ public static Molality FromMillimolesPerKilogram(double value) /// /// Creates a from . /// - public static Molality FromMolesPerGram(double value) + public static Molality FromMolesPerGram(QuantityValue value) { return new Molality(value, MolalityUnit.MolePerGram); } @@ -313,7 +295,7 @@ public static Molality FromMolesPerGram(double value) /// /// Creates a from . /// - public static Molality FromMolesPerKilogram(double value) + public static Molality FromMolesPerKilogram(QuantityValue value) { return new Molality(value, MolalityUnit.MolePerKilogram); } @@ -324,7 +306,7 @@ public static Molality FromMolesPerKilogram(double value) /// Value to convert from. /// Unit to convert from. /// Molality unit value. - public static Molality From(double value, MolalityUnit fromUnit) + public static Molality From(QuantityValue value, MolalityUnit fromUnit) { return new Molality(value, fromUnit); } @@ -385,10 +367,7 @@ public static Molality Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Molality Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -416,11 +395,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Molality result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Molality result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -441,7 +416,7 @@ public static MolalityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -452,7 +427,7 @@ public static MolalityUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out MolalityUnit unit) { return TryParseUnit(str, null, out unit); @@ -467,7 +442,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out MolalityUnit /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out MolalityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -486,35 +461,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Molality operator +(Molality left, Molality right) { - return new Molality(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Molality(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Molality operator -(Molality left, Molality right) { - return new Molality(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Molality(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static Molality operator *(double left, Molality right) + public static Molality operator *(QuantityValue left, Molality right) { return new Molality(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Molality operator *(Molality left, double right) + public static Molality operator *(Molality left, QuantityValue right) { return new Molality(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Molality operator /(Molality left, double right) + public static Molality operator /(Molality left, QuantityValue right) { return new Molality(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Molality left, Molality right) + public static QuantityValue operator /(Molality left, Molality right) { return left.MolesPerKilogram / right.MolesPerKilogram; } @@ -526,97 +501,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Molality left, Molality right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Molality left, Molality right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Molality left, Molality right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Molality left, Molality right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Molality other, Molality tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Molality left, Molality right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Molality other, Molality tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Molality left, Molality right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Molality other, Molality tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Molality otherQuantity)) + if (obj is not Molality otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Molality other, Molality tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Molality other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Molality. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Molality), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Molality otherQuantity)) throw new ArgumentException("Expected type Molality.", nameof(obj)); + if (obj is not Molality otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -628,150 +588,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Molality other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolalityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this Molality to another Molality with the unit representation . - /// - /// The unit to convert to. - /// A Molality with the specified unit. - public Molality ToUnit(MolalityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Molality with the specified unit. - public Molality ToUnit(MolalityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Molality), Unit, typeof(Molality), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Molality)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(MolalityUnit unit, [NotNullWhen(true)] out Molality? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Molality? convertedOrNull = (Unit, unit) switch - { - // MolalityUnit -> BaseUnit - (MolalityUnit.MillimolePerKilogram, MolalityUnit.MolePerKilogram) => new Molality((_value) * 1e-3d, MolalityUnit.MolePerKilogram), - (MolalityUnit.MolePerGram, MolalityUnit.MolePerKilogram) => new Molality(_value / 1e-3, MolalityUnit.MolePerKilogram), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> MolalityUnit - (MolalityUnit.MolePerKilogram, MolalityUnit.MillimolePerKilogram) => new Molality((_value) / 1e-3d, MolalityUnit.MillimolePerKilogram), - (MolalityUnit.MolePerKilogram, MolalityUnit.MolePerGram) => new Molality(_value * 1e-3, MolalityUnit.MolePerGram), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Molality ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not MolalityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolalityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is MolalityUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolalityUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(MolalityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(MolalityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -786,7 +620,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs index 441c570f1d..516a51c7cc 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarEnergy.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// Molar energy is the amount of energy stored in 1 mole of a substance. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct MolarEnergy : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly MolarEnergyUnit? _unit; /// @@ -104,7 +103,7 @@ public static MolarEnergyInfo CreateDefault(Func - /// The for is [T^-2][L^2][M][N^-1]. + /// The for is T^-2L^2MN^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, 0, 0, -1, 0); @@ -120,16 +119,18 @@ public static MolarEnergyInfo CreateDefault(Func> GetDefaultMappings() { yield return new (MolarEnergyUnit.JoulePerMole, "JoulePerMole", "JoulesPerMole", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, amount: AmountOfSubstanceUnit.Mole)); - yield return new (MolarEnergyUnit.KilojoulePerMole, "KilojoulePerMole", "KilojoulesPerMole", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, amount: AmountOfSubstanceUnit.Millimole)); - yield return new (MolarEnergyUnit.MegajoulePerMole, "MegajoulePerMole", "MegajoulesPerMole", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, amount: AmountOfSubstanceUnit.Micromole)); + yield return new (MolarEnergyUnit.KilojoulePerMole, "KilojoulePerMole", "KilojoulesPerMole", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, amount: AmountOfSubstanceUnit.Millimole), + new QuantityValue(1, 1000) + ); + yield return new (MolarEnergyUnit.MegajoulePerMole, "MegajoulePerMole", "MegajoulesPerMole", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, amount: AmountOfSubstanceUnit.Micromole), + new QuantityValue(1, 1000000) + ); } } static MolarEnergy() { - Info = MolarEnergyInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MolarEnergyInfo.CreateDefault); } /// @@ -137,7 +138,7 @@ static MolarEnergy() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public MolarEnergy(double value, MolarEnergyUnit unit) + public MolarEnergy(QuantityValue value, MolarEnergyUnit unit) { _value = value; _unit = unit; @@ -151,7 +152,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -162,7 +163,8 @@ public MolarEnergy(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -191,10 +193,8 @@ public MolarEnergy(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public MolarEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -233,42 +233,24 @@ public MolarEnergy(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double JoulesPerMole => As(MolarEnergyUnit.JoulePerMole); + public QuantityValue JoulesPerMole => this.As(MolarEnergyUnit.JoulePerMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilojoulesPerMole => As(MolarEnergyUnit.KilojoulePerMole); + public QuantityValue KilojoulesPerMole => this.As(MolarEnergyUnit.KilojoulePerMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegajoulesPerMole => As(MolarEnergyUnit.MegajoulePerMole); + public QuantityValue MegajoulesPerMole => this.As(MolarEnergyUnit.MegajoulePerMole); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: MolarEnergyUnit -> BaseUnit - unitConverter.SetConversionFunction(MolarEnergyUnit.KilojoulePerMole, MolarEnergyUnit.JoulePerMole, quantity => quantity.ToUnit(MolarEnergyUnit.JoulePerMole)); - unitConverter.SetConversionFunction(MolarEnergyUnit.MegajoulePerMole, MolarEnergyUnit.JoulePerMole, quantity => quantity.ToUnit(MolarEnergyUnit.JoulePerMole)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(MolarEnergyUnit.JoulePerMole, MolarEnergyUnit.JoulePerMole, quantity => quantity); - - // Register in unit converter: BaseUnit -> MolarEnergyUnit - unitConverter.SetConversionFunction(MolarEnergyUnit.JoulePerMole, MolarEnergyUnit.KilojoulePerMole, quantity => quantity.ToUnit(MolarEnergyUnit.KilojoulePerMole)); - unitConverter.SetConversionFunction(MolarEnergyUnit.JoulePerMole, MolarEnergyUnit.MegajoulePerMole, quantity => quantity.ToUnit(MolarEnergyUnit.MegajoulePerMole)); - } - /// /// Get unit abbreviation string. /// @@ -297,7 +279,7 @@ public static string GetAbbreviation(MolarEnergyUnit unit, IFormatProvider? prov /// /// Creates a from . /// - public static MolarEnergy FromJoulesPerMole(double value) + public static MolarEnergy FromJoulesPerMole(QuantityValue value) { return new MolarEnergy(value, MolarEnergyUnit.JoulePerMole); } @@ -305,7 +287,7 @@ public static MolarEnergy FromJoulesPerMole(double value) /// /// Creates a from . /// - public static MolarEnergy FromKilojoulesPerMole(double value) + public static MolarEnergy FromKilojoulesPerMole(QuantityValue value) { return new MolarEnergy(value, MolarEnergyUnit.KilojoulePerMole); } @@ -313,7 +295,7 @@ public static MolarEnergy FromKilojoulesPerMole(double value) /// /// Creates a from . /// - public static MolarEnergy FromMegajoulesPerMole(double value) + public static MolarEnergy FromMegajoulesPerMole(QuantityValue value) { return new MolarEnergy(value, MolarEnergyUnit.MegajoulePerMole); } @@ -324,7 +306,7 @@ public static MolarEnergy FromMegajoulesPerMole(double value) /// Value to convert from. /// Unit to convert from. /// MolarEnergy unit value. - public static MolarEnergy From(double value, MolarEnergyUnit fromUnit) + public static MolarEnergy From(QuantityValue value, MolarEnergyUnit fromUnit) { return new MolarEnergy(value, fromUnit); } @@ -385,10 +367,7 @@ public static MolarEnergy Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static MolarEnergy Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -416,11 +395,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out MolarEnergy resu /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out MolarEnergy result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -441,7 +416,7 @@ public static MolarEnergyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -452,7 +427,7 @@ public static MolarEnergyUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out MolarEnergyUnit unit) { return TryParseUnit(str, null, out unit); @@ -467,7 +442,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out MolarEnergyU /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out MolarEnergyUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -486,35 +461,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static MolarEnergy operator +(MolarEnergy left, MolarEnergy right) { - return new MolarEnergy(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new MolarEnergy(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static MolarEnergy operator -(MolarEnergy left, MolarEnergy right) { - return new MolarEnergy(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new MolarEnergy(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -536,97 +511,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(MolarEnergy left, MolarEnergy right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(MolarEnergy left, MolarEnergy right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(MolarEnergy left, MolarEnergy right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(MolarEnergy left, MolarEnergy right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MolarEnergy other, MolarEnergy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(MolarEnergy left, MolarEnergy right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MolarEnergy other, MolarEnergy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(MolarEnergy left, MolarEnergy right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MolarEnergy other, MolarEnergy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is MolarEnergy otherQuantity)) + if (obj is not MolarEnergy otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MolarEnergy other, MolarEnergy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(MolarEnergy other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current MolarEnergy. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(MolarEnergy), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MolarEnergy otherQuantity)) throw new ArgumentException("Expected type MolarEnergy.", nameof(obj)); + if (obj is not MolarEnergy otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -638,150 +598,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MolarEnergy other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarEnergyUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this MolarEnergy to another MolarEnergy with the unit representation . - /// - /// The unit to convert to. - /// A MolarEnergy with the specified unit. - public MolarEnergy ToUnit(MolarEnergyUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A MolarEnergy with the specified unit. - public MolarEnergy ToUnit(MolarEnergyUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(MolarEnergy), Unit, typeof(MolarEnergy), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (MolarEnergy)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(MolarEnergyUnit unit, [NotNullWhen(true)] out MolarEnergy? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - MolarEnergy? convertedOrNull = (Unit, unit) switch - { - // MolarEnergyUnit -> BaseUnit - (MolarEnergyUnit.KilojoulePerMole, MolarEnergyUnit.JoulePerMole) => new MolarEnergy((_value) * 1e3d, MolarEnergyUnit.JoulePerMole), - (MolarEnergyUnit.MegajoulePerMole, MolarEnergyUnit.JoulePerMole) => new MolarEnergy((_value) * 1e6d, MolarEnergyUnit.JoulePerMole), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> MolarEnergyUnit - (MolarEnergyUnit.JoulePerMole, MolarEnergyUnit.KilojoulePerMole) => new MolarEnergy((_value) / 1e3d, MolarEnergyUnit.KilojoulePerMole), - (MolarEnergyUnit.JoulePerMole, MolarEnergyUnit.MegajoulePerMole) => new MolarEnergy((_value) / 1e6d, MolarEnergyUnit.MegajoulePerMole), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public MolarEnergy ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not MolarEnergyUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEnergyUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is MolarEnergyUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEnergyUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(MolarEnergyUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(MolarEnergyUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -796,7 +630,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs index c25e244cc8..d9f5bf0a0e 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarEntropy.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// Molar entropy is amount of energy required to increase temperature of 1 mole substance by 1 Kelvin. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct MolarEntropy : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly MolarEntropyUnit? _unit; /// @@ -101,7 +100,7 @@ public static MolarEntropyInfo CreateDefault(Func - /// The for is [T^-2][L^2][M][Θ^-1][N^-1]. + /// The for is T^-2L^2MΘ^-1N^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, 0, -1, -1, 0); @@ -117,16 +116,18 @@ public static MolarEntropyInfo CreateDefault(Func> GetDefaultMappings() { yield return new (MolarEntropyUnit.JoulePerMoleKelvin, "JoulePerMoleKelvin", "JoulesPerMoleKelvin", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Mole)); - yield return new (MolarEntropyUnit.KilojoulePerMoleKelvin, "KilojoulePerMoleKelvin", "KilojoulesPerMoleKelvin", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Millimole)); - yield return new (MolarEntropyUnit.MegajoulePerMoleKelvin, "MegajoulePerMoleKelvin", "MegajoulesPerMoleKelvin", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Micromole)); + yield return new (MolarEntropyUnit.KilojoulePerMoleKelvin, "KilojoulePerMoleKelvin", "KilojoulesPerMoleKelvin", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Millimole), + new QuantityValue(1, 1000) + ); + yield return new (MolarEntropyUnit.MegajoulePerMoleKelvin, "MegajoulePerMoleKelvin", "MegajoulesPerMoleKelvin", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin, amount: AmountOfSubstanceUnit.Micromole), + new QuantityValue(1, 1000000) + ); } } static MolarEntropy() { - Info = MolarEntropyInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MolarEntropyInfo.CreateDefault); } /// @@ -134,7 +135,7 @@ static MolarEntropy() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public MolarEntropy(double value, MolarEntropyUnit unit) + public MolarEntropy(QuantityValue value, MolarEntropyUnit unit) { _value = value; _unit = unit; @@ -148,7 +149,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -159,7 +160,8 @@ public MolarEntropy(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -188,10 +190,8 @@ public MolarEntropy(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public MolarEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -230,42 +230,24 @@ public MolarEntropy(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double JoulesPerMoleKelvin => As(MolarEntropyUnit.JoulePerMoleKelvin); + public QuantityValue JoulesPerMoleKelvin => this.As(MolarEntropyUnit.JoulePerMoleKelvin); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilojoulesPerMoleKelvin => As(MolarEntropyUnit.KilojoulePerMoleKelvin); + public QuantityValue KilojoulesPerMoleKelvin => this.As(MolarEntropyUnit.KilojoulePerMoleKelvin); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegajoulesPerMoleKelvin => As(MolarEntropyUnit.MegajoulePerMoleKelvin); + public QuantityValue MegajoulesPerMoleKelvin => this.As(MolarEntropyUnit.MegajoulePerMoleKelvin); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: MolarEntropyUnit -> BaseUnit - unitConverter.SetConversionFunction(MolarEntropyUnit.KilojoulePerMoleKelvin, MolarEntropyUnit.JoulePerMoleKelvin, quantity => quantity.ToUnit(MolarEntropyUnit.JoulePerMoleKelvin)); - unitConverter.SetConversionFunction(MolarEntropyUnit.MegajoulePerMoleKelvin, MolarEntropyUnit.JoulePerMoleKelvin, quantity => quantity.ToUnit(MolarEntropyUnit.JoulePerMoleKelvin)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(MolarEntropyUnit.JoulePerMoleKelvin, MolarEntropyUnit.JoulePerMoleKelvin, quantity => quantity); - - // Register in unit converter: BaseUnit -> MolarEntropyUnit - unitConverter.SetConversionFunction(MolarEntropyUnit.JoulePerMoleKelvin, MolarEntropyUnit.KilojoulePerMoleKelvin, quantity => quantity.ToUnit(MolarEntropyUnit.KilojoulePerMoleKelvin)); - unitConverter.SetConversionFunction(MolarEntropyUnit.JoulePerMoleKelvin, MolarEntropyUnit.MegajoulePerMoleKelvin, quantity => quantity.ToUnit(MolarEntropyUnit.MegajoulePerMoleKelvin)); - } - /// /// Get unit abbreviation string. /// @@ -294,7 +276,7 @@ public static string GetAbbreviation(MolarEntropyUnit unit, IFormatProvider? pro /// /// Creates a from . /// - public static MolarEntropy FromJoulesPerMoleKelvin(double value) + public static MolarEntropy FromJoulesPerMoleKelvin(QuantityValue value) { return new MolarEntropy(value, MolarEntropyUnit.JoulePerMoleKelvin); } @@ -302,7 +284,7 @@ public static MolarEntropy FromJoulesPerMoleKelvin(double value) /// /// Creates a from . /// - public static MolarEntropy FromKilojoulesPerMoleKelvin(double value) + public static MolarEntropy FromKilojoulesPerMoleKelvin(QuantityValue value) { return new MolarEntropy(value, MolarEntropyUnit.KilojoulePerMoleKelvin); } @@ -310,7 +292,7 @@ public static MolarEntropy FromKilojoulesPerMoleKelvin(double value) /// /// Creates a from . /// - public static MolarEntropy FromMegajoulesPerMoleKelvin(double value) + public static MolarEntropy FromMegajoulesPerMoleKelvin(QuantityValue value) { return new MolarEntropy(value, MolarEntropyUnit.MegajoulePerMoleKelvin); } @@ -321,7 +303,7 @@ public static MolarEntropy FromMegajoulesPerMoleKelvin(double value) /// Value to convert from. /// Unit to convert from. /// MolarEntropy unit value. - public static MolarEntropy From(double value, MolarEntropyUnit fromUnit) + public static MolarEntropy From(QuantityValue value, MolarEntropyUnit fromUnit) { return new MolarEntropy(value, fromUnit); } @@ -382,10 +364,7 @@ public static MolarEntropy Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static MolarEntropy Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -413,11 +392,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out MolarEntropy res /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out MolarEntropy result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -438,7 +413,7 @@ public static MolarEntropyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -449,7 +424,7 @@ public static MolarEntropyUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out MolarEntropyUnit unit) { return TryParseUnit(str, null, out unit); @@ -464,7 +439,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out MolarEntropy /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out MolarEntropyUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -483,35 +458,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static MolarEntropy operator +(MolarEntropy left, MolarEntropy right) { - return new MolarEntropy(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new MolarEntropy(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static MolarEntropy operator -(MolarEntropy left, MolarEntropy right) { - return new MolarEntropy(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new MolarEntropy(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -523,97 +498,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(MolarEntropy left, MolarEntropy right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(MolarEntropy left, MolarEntropy right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(MolarEntropy left, MolarEntropy right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(MolarEntropy left, MolarEntropy right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MolarEntropy other, MolarEntropy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(MolarEntropy left, MolarEntropy right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MolarEntropy other, MolarEntropy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(MolarEntropy left, MolarEntropy right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MolarEntropy other, MolarEntropy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is MolarEntropy otherQuantity)) + if (obj is not MolarEntropy otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MolarEntropy other, MolarEntropy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(MolarEntropy other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current MolarEntropy. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(MolarEntropy), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MolarEntropy otherQuantity)) throw new ArgumentException("Expected type MolarEntropy.", nameof(obj)); + if (obj is not MolarEntropy otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -625,150 +585,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MolarEntropy other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarEntropyUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this MolarEntropy to another MolarEntropy with the unit representation . - /// - /// The unit to convert to. - /// A MolarEntropy with the specified unit. - public MolarEntropy ToUnit(MolarEntropyUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A MolarEntropy with the specified unit. - public MolarEntropy ToUnit(MolarEntropyUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(MolarEntropy), Unit, typeof(MolarEntropy), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (MolarEntropy)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(MolarEntropyUnit unit, [NotNullWhen(true)] out MolarEntropy? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - MolarEntropy? convertedOrNull = (Unit, unit) switch - { - // MolarEntropyUnit -> BaseUnit - (MolarEntropyUnit.KilojoulePerMoleKelvin, MolarEntropyUnit.JoulePerMoleKelvin) => new MolarEntropy((_value) * 1e3d, MolarEntropyUnit.JoulePerMoleKelvin), - (MolarEntropyUnit.MegajoulePerMoleKelvin, MolarEntropyUnit.JoulePerMoleKelvin) => new MolarEntropy((_value) * 1e6d, MolarEntropyUnit.JoulePerMoleKelvin), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> MolarEntropyUnit - (MolarEntropyUnit.JoulePerMoleKelvin, MolarEntropyUnit.KilojoulePerMoleKelvin) => new MolarEntropy((_value) / 1e3d, MolarEntropyUnit.KilojoulePerMoleKelvin), - (MolarEntropyUnit.JoulePerMoleKelvin, MolarEntropyUnit.MegajoulePerMoleKelvin) => new MolarEntropy((_value) / 1e6d, MolarEntropyUnit.MegajoulePerMoleKelvin), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public MolarEntropy ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not MolarEntropyUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEntropyUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is MolarEntropyUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarEntropyUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(MolarEntropyUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(MolarEntropyUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -783,7 +617,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/MolarFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarFlow.g.cs index ebd3e62887..c866ee5d1c 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarFlow.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// Molar flow is the ratio of the amount of substance change to the time during which the change occurred (value of amount of substance changes per unit time). /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct MolarFlow : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -56,13 +55,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly MolarFlowUnit? _unit; /// @@ -107,7 +106,7 @@ public static MolarFlowInfo CreateDefault(Func - /// The for is [T^-1][N]. + /// The for is T^-1N. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -1, 0, 0, 1, 0); @@ -122,23 +121,37 @@ public static MolarFlowInfo CreateDefault(FuncAn of representing the default unit mappings for MolarFlow. public static IEnumerable> GetDefaultMappings() { - yield return new (MolarFlowUnit.KilomolePerHour, "KilomolePerHour", "KilomolesPerHour", new BaseUnits(time: DurationUnit.Hour, amount: AmountOfSubstanceUnit.Kilomole)); - yield return new (MolarFlowUnit.KilomolePerMinute, "KilomolePerMinute", "KilomolesPerMinute", new BaseUnits(time: DurationUnit.Minute, amount: AmountOfSubstanceUnit.Kilomole)); - yield return new (MolarFlowUnit.KilomolePerSecond, "KilomolePerSecond", "KilomolesPerSecond", new BaseUnits(time: DurationUnit.Second, amount: AmountOfSubstanceUnit.Kilomole)); - yield return new (MolarFlowUnit.MolePerHour, "MolePerHour", "MolesPerHour", new BaseUnits(time: DurationUnit.Hour, amount: AmountOfSubstanceUnit.Mole)); - yield return new (MolarFlowUnit.MolePerMinute, "MolePerMinute", "MolesPerMinute", new BaseUnits(time: DurationUnit.Minute, amount: AmountOfSubstanceUnit.Mole)); + yield return new (MolarFlowUnit.KilomolePerHour, "KilomolePerHour", "KilomolesPerHour", new BaseUnits(time: DurationUnit.Hour, amount: AmountOfSubstanceUnit.Kilomole), + new QuantityValue(18, 5) + ); + yield return new (MolarFlowUnit.KilomolePerMinute, "KilomolePerMinute", "KilomolesPerMinute", new BaseUnits(time: DurationUnit.Minute, amount: AmountOfSubstanceUnit.Kilomole), + new QuantityValue(3, 50) + ); + yield return new (MolarFlowUnit.KilomolePerSecond, "KilomolePerSecond", "KilomolesPerSecond", new BaseUnits(time: DurationUnit.Second, amount: AmountOfSubstanceUnit.Kilomole), + new QuantityValue(1, 1000) + ); + yield return new (MolarFlowUnit.MolePerHour, "MolePerHour", "MolesPerHour", new BaseUnits(time: DurationUnit.Hour, amount: AmountOfSubstanceUnit.Mole), + 3600 + ); + yield return new (MolarFlowUnit.MolePerMinute, "MolePerMinute", "MolesPerMinute", new BaseUnits(time: DurationUnit.Minute, amount: AmountOfSubstanceUnit.Mole), + 60 + ); yield return new (MolarFlowUnit.MolePerSecond, "MolePerSecond", "MolesPerSecond", new BaseUnits(time: DurationUnit.Second, amount: AmountOfSubstanceUnit.Mole)); - yield return new (MolarFlowUnit.PoundMolePerHour, "PoundMolePerHour", "PoundMolesPerHour", new BaseUnits(time: DurationUnit.Hour, amount: AmountOfSubstanceUnit.PoundMole)); - yield return new (MolarFlowUnit.PoundMolePerMinute, "PoundMolePerMinute", "PoundMolesPerMinute", new BaseUnits(time: DurationUnit.Minute, amount: AmountOfSubstanceUnit.PoundMole)); - yield return new (MolarFlowUnit.PoundMolePerSecond, "PoundMolePerSecond", "PoundMolesPerSecond", new BaseUnits(time: DurationUnit.Second, amount: AmountOfSubstanceUnit.PoundMole)); + yield return new (MolarFlowUnit.PoundMolePerHour, "PoundMolePerHour", "PoundMolesPerHour", new BaseUnits(time: DurationUnit.Hour, amount: AmountOfSubstanceUnit.PoundMole), + new QuantityValue(360000000, 45359237) + ); + yield return new (MolarFlowUnit.PoundMolePerMinute, "PoundMolePerMinute", "PoundMolesPerMinute", new BaseUnits(time: DurationUnit.Minute, amount: AmountOfSubstanceUnit.PoundMole), + new QuantityValue(6000000, 45359237) + ); + yield return new (MolarFlowUnit.PoundMolePerSecond, "PoundMolePerSecond", "PoundMolesPerSecond", new BaseUnits(time: DurationUnit.Second, amount: AmountOfSubstanceUnit.PoundMole), + new QuantityValue(100000, 45359237) + ); } } static MolarFlow() { - Info = MolarFlowInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MolarFlowInfo.CreateDefault); } /// @@ -146,7 +159,7 @@ static MolarFlow() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public MolarFlow(double value, MolarFlowUnit unit) + public MolarFlow(QuantityValue value, MolarFlowUnit unit) { _value = value; _unit = unit; @@ -160,7 +173,7 @@ public MolarFlow(double value, MolarFlowUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public MolarFlow(double value, UnitSystem unitSystem) + public MolarFlow(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -171,7 +184,8 @@ public MolarFlow(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -200,10 +214,8 @@ public MolarFlow(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public MolarFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -242,84 +254,54 @@ public MolarFlow(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilomolesPerHour => As(MolarFlowUnit.KilomolePerHour); + public QuantityValue KilomolesPerHour => this.As(MolarFlowUnit.KilomolePerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilomolesPerMinute => As(MolarFlowUnit.KilomolePerMinute); + public QuantityValue KilomolesPerMinute => this.As(MolarFlowUnit.KilomolePerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilomolesPerSecond => As(MolarFlowUnit.KilomolePerSecond); + public QuantityValue KilomolesPerSecond => this.As(MolarFlowUnit.KilomolePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MolesPerHour => As(MolarFlowUnit.MolePerHour); + public QuantityValue MolesPerHour => this.As(MolarFlowUnit.MolePerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MolesPerMinute => As(MolarFlowUnit.MolePerMinute); + public QuantityValue MolesPerMinute => this.As(MolarFlowUnit.MolePerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MolesPerSecond => As(MolarFlowUnit.MolePerSecond); + public QuantityValue MolesPerSecond => this.As(MolarFlowUnit.MolePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundMolesPerHour => As(MolarFlowUnit.PoundMolePerHour); + public QuantityValue PoundMolesPerHour => this.As(MolarFlowUnit.PoundMolePerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundMolesPerMinute => As(MolarFlowUnit.PoundMolePerMinute); + public QuantityValue PoundMolesPerMinute => this.As(MolarFlowUnit.PoundMolePerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundMolesPerSecond => As(MolarFlowUnit.PoundMolePerSecond); + public QuantityValue PoundMolesPerSecond => this.As(MolarFlowUnit.PoundMolePerSecond); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: MolarFlowUnit -> BaseUnit - unitConverter.SetConversionFunction(MolarFlowUnit.KilomolePerHour, MolarFlowUnit.MolePerSecond, quantity => quantity.ToUnit(MolarFlowUnit.MolePerSecond)); - unitConverter.SetConversionFunction(MolarFlowUnit.KilomolePerMinute, MolarFlowUnit.MolePerSecond, quantity => quantity.ToUnit(MolarFlowUnit.MolePerSecond)); - unitConverter.SetConversionFunction(MolarFlowUnit.KilomolePerSecond, MolarFlowUnit.MolePerSecond, quantity => quantity.ToUnit(MolarFlowUnit.MolePerSecond)); - unitConverter.SetConversionFunction(MolarFlowUnit.MolePerHour, MolarFlowUnit.MolePerSecond, quantity => quantity.ToUnit(MolarFlowUnit.MolePerSecond)); - unitConverter.SetConversionFunction(MolarFlowUnit.MolePerMinute, MolarFlowUnit.MolePerSecond, quantity => quantity.ToUnit(MolarFlowUnit.MolePerSecond)); - unitConverter.SetConversionFunction(MolarFlowUnit.PoundMolePerHour, MolarFlowUnit.MolePerSecond, quantity => quantity.ToUnit(MolarFlowUnit.MolePerSecond)); - unitConverter.SetConversionFunction(MolarFlowUnit.PoundMolePerMinute, MolarFlowUnit.MolePerSecond, quantity => quantity.ToUnit(MolarFlowUnit.MolePerSecond)); - unitConverter.SetConversionFunction(MolarFlowUnit.PoundMolePerSecond, MolarFlowUnit.MolePerSecond, quantity => quantity.ToUnit(MolarFlowUnit.MolePerSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(MolarFlowUnit.MolePerSecond, MolarFlowUnit.MolePerSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> MolarFlowUnit - unitConverter.SetConversionFunction(MolarFlowUnit.MolePerSecond, MolarFlowUnit.KilomolePerHour, quantity => quantity.ToUnit(MolarFlowUnit.KilomolePerHour)); - unitConverter.SetConversionFunction(MolarFlowUnit.MolePerSecond, MolarFlowUnit.KilomolePerMinute, quantity => quantity.ToUnit(MolarFlowUnit.KilomolePerMinute)); - unitConverter.SetConversionFunction(MolarFlowUnit.MolePerSecond, MolarFlowUnit.KilomolePerSecond, quantity => quantity.ToUnit(MolarFlowUnit.KilomolePerSecond)); - unitConverter.SetConversionFunction(MolarFlowUnit.MolePerSecond, MolarFlowUnit.MolePerHour, quantity => quantity.ToUnit(MolarFlowUnit.MolePerHour)); - unitConverter.SetConversionFunction(MolarFlowUnit.MolePerSecond, MolarFlowUnit.MolePerMinute, quantity => quantity.ToUnit(MolarFlowUnit.MolePerMinute)); - unitConverter.SetConversionFunction(MolarFlowUnit.MolePerSecond, MolarFlowUnit.PoundMolePerHour, quantity => quantity.ToUnit(MolarFlowUnit.PoundMolePerHour)); - unitConverter.SetConversionFunction(MolarFlowUnit.MolePerSecond, MolarFlowUnit.PoundMolePerMinute, quantity => quantity.ToUnit(MolarFlowUnit.PoundMolePerMinute)); - unitConverter.SetConversionFunction(MolarFlowUnit.MolePerSecond, MolarFlowUnit.PoundMolePerSecond, quantity => quantity.ToUnit(MolarFlowUnit.PoundMolePerSecond)); - } - /// /// Get unit abbreviation string. /// @@ -348,7 +330,7 @@ public static string GetAbbreviation(MolarFlowUnit unit, IFormatProvider? provid /// /// Creates a from . /// - public static MolarFlow FromKilomolesPerHour(double value) + public static MolarFlow FromKilomolesPerHour(QuantityValue value) { return new MolarFlow(value, MolarFlowUnit.KilomolePerHour); } @@ -356,7 +338,7 @@ public static MolarFlow FromKilomolesPerHour(double value) /// /// Creates a from . /// - public static MolarFlow FromKilomolesPerMinute(double value) + public static MolarFlow FromKilomolesPerMinute(QuantityValue value) { return new MolarFlow(value, MolarFlowUnit.KilomolePerMinute); } @@ -364,7 +346,7 @@ public static MolarFlow FromKilomolesPerMinute(double value) /// /// Creates a from . /// - public static MolarFlow FromKilomolesPerSecond(double value) + public static MolarFlow FromKilomolesPerSecond(QuantityValue value) { return new MolarFlow(value, MolarFlowUnit.KilomolePerSecond); } @@ -372,7 +354,7 @@ public static MolarFlow FromKilomolesPerSecond(double value) /// /// Creates a from . /// - public static MolarFlow FromMolesPerHour(double value) + public static MolarFlow FromMolesPerHour(QuantityValue value) { return new MolarFlow(value, MolarFlowUnit.MolePerHour); } @@ -380,7 +362,7 @@ public static MolarFlow FromMolesPerHour(double value) /// /// Creates a from . /// - public static MolarFlow FromMolesPerMinute(double value) + public static MolarFlow FromMolesPerMinute(QuantityValue value) { return new MolarFlow(value, MolarFlowUnit.MolePerMinute); } @@ -388,7 +370,7 @@ public static MolarFlow FromMolesPerMinute(double value) /// /// Creates a from . /// - public static MolarFlow FromMolesPerSecond(double value) + public static MolarFlow FromMolesPerSecond(QuantityValue value) { return new MolarFlow(value, MolarFlowUnit.MolePerSecond); } @@ -396,7 +378,7 @@ public static MolarFlow FromMolesPerSecond(double value) /// /// Creates a from . /// - public static MolarFlow FromPoundMolesPerHour(double value) + public static MolarFlow FromPoundMolesPerHour(QuantityValue value) { return new MolarFlow(value, MolarFlowUnit.PoundMolePerHour); } @@ -404,7 +386,7 @@ public static MolarFlow FromPoundMolesPerHour(double value) /// /// Creates a from . /// - public static MolarFlow FromPoundMolesPerMinute(double value) + public static MolarFlow FromPoundMolesPerMinute(QuantityValue value) { return new MolarFlow(value, MolarFlowUnit.PoundMolePerMinute); } @@ -412,7 +394,7 @@ public static MolarFlow FromPoundMolesPerMinute(double value) /// /// Creates a from . /// - public static MolarFlow FromPoundMolesPerSecond(double value) + public static MolarFlow FromPoundMolesPerSecond(QuantityValue value) { return new MolarFlow(value, MolarFlowUnit.PoundMolePerSecond); } @@ -423,7 +405,7 @@ public static MolarFlow FromPoundMolesPerSecond(double value) /// Value to convert from. /// Unit to convert from. /// MolarFlow unit value. - public static MolarFlow From(double value, MolarFlowUnit fromUnit) + public static MolarFlow From(QuantityValue value, MolarFlowUnit fromUnit) { return new MolarFlow(value, fromUnit); } @@ -484,10 +466,7 @@ public static MolarFlow Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static MolarFlow Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -515,11 +494,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out MolarFlow result /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out MolarFlow result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -540,7 +515,7 @@ public static MolarFlowUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -551,7 +526,7 @@ public static MolarFlowUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out MolarFlowUnit unit) { return TryParseUnit(str, null, out unit); @@ -566,7 +541,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out MolarFlowUni /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out MolarFlowUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -585,35 +560,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static MolarFlow operator +(MolarFlow left, MolarFlow right) { - return new MolarFlow(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new MolarFlow(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static MolarFlow operator -(MolarFlow left, MolarFlow right) { - return new MolarFlow(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new MolarFlow(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static MolarFlow operator *(double left, MolarFlow right) + public static MolarFlow operator *(QuantityValue left, MolarFlow right) { return new MolarFlow(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static MolarFlow operator *(MolarFlow left, double right) + public static MolarFlow operator *(MolarFlow left, QuantityValue right) { return new MolarFlow(left.Value * right, left.Unit); } /// Get from dividing by value. - public static MolarFlow operator /(MolarFlow left, double right) + public static MolarFlow operator /(MolarFlow left, QuantityValue right) { return new MolarFlow(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(MolarFlow left, MolarFlow right) + public static QuantityValue operator /(MolarFlow left, MolarFlow right) { return left.MolesPerSecond / right.MolesPerSecond; } @@ -653,97 +628,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(MolarFlow left, MolarFlow right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(MolarFlow left, MolarFlow right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(MolarFlow left, MolarFlow right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(MolarFlow left, MolarFlow right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MolarFlow other, MolarFlow tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(MolarFlow left, MolarFlow right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MolarFlow other, MolarFlow tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(MolarFlow left, MolarFlow right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MolarFlow other, MolarFlow tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is MolarFlow otherQuantity)) + if (obj is not MolarFlow otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MolarFlow other, MolarFlow tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(MolarFlow other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current MolarFlow. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(MolarFlow), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MolarFlow otherQuantity)) throw new ArgumentException("Expected type MolarFlow.", nameof(obj)); + if (obj is not MolarFlow otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -755,162 +715,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MolarFlow other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarFlowUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this MolarFlow to another MolarFlow with the unit representation . - /// - /// The unit to convert to. - /// A MolarFlow with the specified unit. - public MolarFlow ToUnit(MolarFlowUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A MolarFlow with the specified unit. - public MolarFlow ToUnit(MolarFlowUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(MolarFlow), Unit, typeof(MolarFlow), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (MolarFlow)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(MolarFlowUnit unit, [NotNullWhen(true)] out MolarFlow? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - MolarFlow? convertedOrNull = (Unit, unit) switch - { - // MolarFlowUnit -> BaseUnit - (MolarFlowUnit.KilomolePerHour, MolarFlowUnit.MolePerSecond) => new MolarFlow((_value / 3600) * 1e3d, MolarFlowUnit.MolePerSecond), - (MolarFlowUnit.KilomolePerMinute, MolarFlowUnit.MolePerSecond) => new MolarFlow((_value / 60) * 1e3d, MolarFlowUnit.MolePerSecond), - (MolarFlowUnit.KilomolePerSecond, MolarFlowUnit.MolePerSecond) => new MolarFlow((_value) * 1e3d, MolarFlowUnit.MolePerSecond), - (MolarFlowUnit.MolePerHour, MolarFlowUnit.MolePerSecond) => new MolarFlow(_value / 3600, MolarFlowUnit.MolePerSecond), - (MolarFlowUnit.MolePerMinute, MolarFlowUnit.MolePerSecond) => new MolarFlow(_value / 60, MolarFlowUnit.MolePerSecond), - (MolarFlowUnit.PoundMolePerHour, MolarFlowUnit.MolePerSecond) => new MolarFlow((_value * 453.59237) / 3600, MolarFlowUnit.MolePerSecond), - (MolarFlowUnit.PoundMolePerMinute, MolarFlowUnit.MolePerSecond) => new MolarFlow((_value * 453.59237) / 60, MolarFlowUnit.MolePerSecond), - (MolarFlowUnit.PoundMolePerSecond, MolarFlowUnit.MolePerSecond) => new MolarFlow(_value * 453.59237, MolarFlowUnit.MolePerSecond), - - // BaseUnit -> MolarFlowUnit - (MolarFlowUnit.MolePerSecond, MolarFlowUnit.KilomolePerHour) => new MolarFlow((_value * 3600) / 1e3d, MolarFlowUnit.KilomolePerHour), - (MolarFlowUnit.MolePerSecond, MolarFlowUnit.KilomolePerMinute) => new MolarFlow((_value * 60) / 1e3d, MolarFlowUnit.KilomolePerMinute), - (MolarFlowUnit.MolePerSecond, MolarFlowUnit.KilomolePerSecond) => new MolarFlow((_value) / 1e3d, MolarFlowUnit.KilomolePerSecond), - (MolarFlowUnit.MolePerSecond, MolarFlowUnit.MolePerHour) => new MolarFlow(_value * 3600, MolarFlowUnit.MolePerHour), - (MolarFlowUnit.MolePerSecond, MolarFlowUnit.MolePerMinute) => new MolarFlow(_value * 60, MolarFlowUnit.MolePerMinute), - (MolarFlowUnit.MolePerSecond, MolarFlowUnit.PoundMolePerHour) => new MolarFlow((_value / 453.59237) * 3600, MolarFlowUnit.PoundMolePerHour), - (MolarFlowUnit.MolePerSecond, MolarFlowUnit.PoundMolePerMinute) => new MolarFlow((_value / 453.59237) * 60, MolarFlowUnit.PoundMolePerMinute), - (MolarFlowUnit.MolePerSecond, MolarFlowUnit.PoundMolePerSecond) => new MolarFlow(_value / 453.59237, MolarFlowUnit.PoundMolePerSecond), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public MolarFlow ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not MolarFlowUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarFlowUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is MolarFlowUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarFlowUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(MolarFlowUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(MolarFlowUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -925,7 +747,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs b/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs index 010b9d74f9..c2c8cc7a5e 100644 --- a/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/MolarMass.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct MolarMass : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -55,13 +54,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly MolarMassUnit? _unit; /// @@ -106,7 +105,7 @@ public static MolarMassInfo CreateDefault(Func - /// The for is [M][N^-1]. + /// The for is MN^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, 0, 0, 0, -1, 0); @@ -121,27 +120,49 @@ public static MolarMassInfo CreateDefault(FuncAn of representing the default unit mappings for MolarMass. public static IEnumerable> GetDefaultMappings() { - yield return new (MolarMassUnit.CentigramPerMole, "CentigramPerMole", "CentigramsPerMole", new BaseUnits(mass: MassUnit.Centigram, amount: AmountOfSubstanceUnit.Mole)); - yield return new (MolarMassUnit.DecagramPerMole, "DecagramPerMole", "DecagramsPerMole", new BaseUnits(mass: MassUnit.Decagram, amount: AmountOfSubstanceUnit.Mole)); - yield return new (MolarMassUnit.DecigramPerMole, "DecigramPerMole", "DecigramsPerMole", new BaseUnits(mass: MassUnit.Decigram, amount: AmountOfSubstanceUnit.Mole)); - yield return new (MolarMassUnit.GramPerMole, "GramPerMole", "GramsPerMole", new BaseUnits(mass: MassUnit.Gram, amount: AmountOfSubstanceUnit.Mole)); - yield return new (MolarMassUnit.HectogramPerMole, "HectogramPerMole", "HectogramsPerMole", new BaseUnits(mass: MassUnit.Hectogram, amount: AmountOfSubstanceUnit.Mole)); - yield return new (MolarMassUnit.KilogramPerKilomole, "KilogramPerKilomole", "KilogramsPerKilomole", new BaseUnits(mass: MassUnit.Kilogram, amount: AmountOfSubstanceUnit.Kilomole)); + yield return new (MolarMassUnit.CentigramPerMole, "CentigramPerMole", "CentigramsPerMole", new BaseUnits(mass: MassUnit.Centigram, amount: AmountOfSubstanceUnit.Mole), + 100000 + ); + yield return new (MolarMassUnit.DecagramPerMole, "DecagramPerMole", "DecagramsPerMole", new BaseUnits(mass: MassUnit.Decagram, amount: AmountOfSubstanceUnit.Mole), + 100 + ); + yield return new (MolarMassUnit.DecigramPerMole, "DecigramPerMole", "DecigramsPerMole", new BaseUnits(mass: MassUnit.Decigram, amount: AmountOfSubstanceUnit.Mole), + 10000 + ); + yield return new (MolarMassUnit.GramPerMole, "GramPerMole", "GramsPerMole", new BaseUnits(mass: MassUnit.Gram, amount: AmountOfSubstanceUnit.Mole), + 1000 + ); + yield return new (MolarMassUnit.HectogramPerMole, "HectogramPerMole", "HectogramsPerMole", new BaseUnits(mass: MassUnit.Hectogram, amount: AmountOfSubstanceUnit.Mole), + 10 + ); + yield return new (MolarMassUnit.KilogramPerKilomole, "KilogramPerKilomole", "KilogramsPerKilomole", new BaseUnits(mass: MassUnit.Kilogram, amount: AmountOfSubstanceUnit.Kilomole), + 1000 + ); yield return new (MolarMassUnit.KilogramPerMole, "KilogramPerMole", "KilogramsPerMole", new BaseUnits(mass: MassUnit.Kilogram, amount: AmountOfSubstanceUnit.Mole)); - yield return new (MolarMassUnit.KilopoundPerMole, "KilopoundPerMole", "KilopoundsPerMole", new BaseUnits(mass: MassUnit.Kilopound, amount: AmountOfSubstanceUnit.Mole)); - yield return new (MolarMassUnit.MegapoundPerMole, "MegapoundPerMole", "MegapoundsPerMole", new BaseUnits(mass: MassUnit.Megapound, amount: AmountOfSubstanceUnit.Mole)); - yield return new (MolarMassUnit.MicrogramPerMole, "MicrogramPerMole", "MicrogramsPerMole", new BaseUnits(mass: MassUnit.Microgram, amount: AmountOfSubstanceUnit.Mole)); - yield return new (MolarMassUnit.MilligramPerMole, "MilligramPerMole", "MilligramsPerMole", new BaseUnits(mass: MassUnit.Milligram, amount: AmountOfSubstanceUnit.Mole)); - yield return new (MolarMassUnit.NanogramPerMole, "NanogramPerMole", "NanogramsPerMole", new BaseUnits(mass: MassUnit.Nanogram, amount: AmountOfSubstanceUnit.Mole)); - yield return new (MolarMassUnit.PoundPerMole, "PoundPerMole", "PoundsPerMole", new BaseUnits(mass: MassUnit.Pound, amount: AmountOfSubstanceUnit.Mole)); + yield return new (MolarMassUnit.KilopoundPerMole, "KilopoundPerMole", "KilopoundsPerMole", new BaseUnits(mass: MassUnit.Kilopound, amount: AmountOfSubstanceUnit.Mole), + new QuantityValue(100000, 45359237) + ); + yield return new (MolarMassUnit.MegapoundPerMole, "MegapoundPerMole", "MegapoundsPerMole", new BaseUnits(mass: MassUnit.Megapound, amount: AmountOfSubstanceUnit.Mole), + new QuantityValue(100, 45359237) + ); + yield return new (MolarMassUnit.MicrogramPerMole, "MicrogramPerMole", "MicrogramsPerMole", new BaseUnits(mass: MassUnit.Microgram, amount: AmountOfSubstanceUnit.Mole), + 1000000000 + ); + yield return new (MolarMassUnit.MilligramPerMole, "MilligramPerMole", "MilligramsPerMole", new BaseUnits(mass: MassUnit.Milligram, amount: AmountOfSubstanceUnit.Mole), + 1000000 + ); + yield return new (MolarMassUnit.NanogramPerMole, "NanogramPerMole", "NanogramsPerMole", new BaseUnits(mass: MassUnit.Nanogram, amount: AmountOfSubstanceUnit.Mole), + 1000000000000 + ); + yield return new (MolarMassUnit.PoundPerMole, "PoundPerMole", "PoundsPerMole", new BaseUnits(mass: MassUnit.Pound, amount: AmountOfSubstanceUnit.Mole), + new QuantityValue(100000000, 45359237) + ); } } static MolarMass() { - Info = MolarMassInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MolarMassInfo.CreateDefault); } /// @@ -149,7 +170,7 @@ static MolarMass() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public MolarMass(double value, MolarMassUnit unit) + public MolarMass(QuantityValue value, MolarMassUnit unit) { _value = value; _unit = unit; @@ -163,7 +184,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -174,7 +195,8 @@ public MolarMass(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -203,10 +225,8 @@ public MolarMass(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public MolarMassUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -245,112 +265,74 @@ public MolarMass(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentigramsPerMole => As(MolarMassUnit.CentigramPerMole); + public QuantityValue CentigramsPerMole => this.As(MolarMassUnit.CentigramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecagramsPerMole => As(MolarMassUnit.DecagramPerMole); + public QuantityValue DecagramsPerMole => this.As(MolarMassUnit.DecagramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecigramsPerMole => As(MolarMassUnit.DecigramPerMole); + public QuantityValue DecigramsPerMole => this.As(MolarMassUnit.DecigramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerMole => As(MolarMassUnit.GramPerMole); + public QuantityValue GramsPerMole => this.As(MolarMassUnit.GramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HectogramsPerMole => As(MolarMassUnit.HectogramPerMole); + public QuantityValue HectogramsPerMole => this.As(MolarMassUnit.HectogramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerKilomole => As(MolarMassUnit.KilogramPerKilomole); + public QuantityValue KilogramsPerKilomole => this.As(MolarMassUnit.KilogramPerKilomole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerMole => As(MolarMassUnit.KilogramPerMole); + public QuantityValue KilogramsPerMole => this.As(MolarMassUnit.KilogramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsPerMole => As(MolarMassUnit.KilopoundPerMole); + public QuantityValue KilopoundsPerMole => this.As(MolarMassUnit.KilopoundPerMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegapoundsPerMole => As(MolarMassUnit.MegapoundPerMole); + public QuantityValue MegapoundsPerMole => this.As(MolarMassUnit.MegapoundPerMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrogramsPerMole => As(MolarMassUnit.MicrogramPerMole); + public QuantityValue MicrogramsPerMole => this.As(MolarMassUnit.MicrogramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilligramsPerMole => As(MolarMassUnit.MilligramPerMole); + public QuantityValue MilligramsPerMole => this.As(MolarMassUnit.MilligramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanogramsPerMole => As(MolarMassUnit.NanogramPerMole); + public QuantityValue NanogramsPerMole => this.As(MolarMassUnit.NanogramPerMole); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerMole => As(MolarMassUnit.PoundPerMole); + public QuantityValue PoundsPerMole => this.As(MolarMassUnit.PoundPerMole); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: MolarMassUnit -> BaseUnit - unitConverter.SetConversionFunction(MolarMassUnit.CentigramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.DecagramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.DecigramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.GramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.HectogramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerKilomole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilopoundPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.MegapoundPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.MicrogramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.MilligramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.NanogramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.PoundPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerMole)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.KilogramPerMole, quantity => quantity); - - // Register in unit converter: BaseUnit -> MolarMassUnit - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.CentigramPerMole, quantity => quantity.ToUnit(MolarMassUnit.CentigramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.DecagramPerMole, quantity => quantity.ToUnit(MolarMassUnit.DecagramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.DecigramPerMole, quantity => quantity.ToUnit(MolarMassUnit.DecigramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.GramPerMole, quantity => quantity.ToUnit(MolarMassUnit.GramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.HectogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.HectogramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.KilogramPerKilomole, quantity => quantity.ToUnit(MolarMassUnit.KilogramPerKilomole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.KilopoundPerMole, quantity => quantity.ToUnit(MolarMassUnit.KilopoundPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.MegapoundPerMole, quantity => quantity.ToUnit(MolarMassUnit.MegapoundPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.MicrogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.MicrogramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.MilligramPerMole, quantity => quantity.ToUnit(MolarMassUnit.MilligramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.NanogramPerMole, quantity => quantity.ToUnit(MolarMassUnit.NanogramPerMole)); - unitConverter.SetConversionFunction(MolarMassUnit.KilogramPerMole, MolarMassUnit.PoundPerMole, quantity => quantity.ToUnit(MolarMassUnit.PoundPerMole)); - } - /// /// Get unit abbreviation string. /// @@ -379,7 +361,7 @@ public static string GetAbbreviation(MolarMassUnit unit, IFormatProvider? provid /// /// Creates a from . /// - public static MolarMass FromCentigramsPerMole(double value) + public static MolarMass FromCentigramsPerMole(QuantityValue value) { return new MolarMass(value, MolarMassUnit.CentigramPerMole); } @@ -387,7 +369,7 @@ public static MolarMass FromCentigramsPerMole(double value) /// /// Creates a from . /// - public static MolarMass FromDecagramsPerMole(double value) + public static MolarMass FromDecagramsPerMole(QuantityValue value) { return new MolarMass(value, MolarMassUnit.DecagramPerMole); } @@ -395,7 +377,7 @@ public static MolarMass FromDecagramsPerMole(double value) /// /// Creates a from . /// - public static MolarMass FromDecigramsPerMole(double value) + public static MolarMass FromDecigramsPerMole(QuantityValue value) { return new MolarMass(value, MolarMassUnit.DecigramPerMole); } @@ -403,7 +385,7 @@ public static MolarMass FromDecigramsPerMole(double value) /// /// Creates a from . /// - public static MolarMass FromGramsPerMole(double value) + public static MolarMass FromGramsPerMole(QuantityValue value) { return new MolarMass(value, MolarMassUnit.GramPerMole); } @@ -411,7 +393,7 @@ public static MolarMass FromGramsPerMole(double value) /// /// Creates a from . /// - public static MolarMass FromHectogramsPerMole(double value) + public static MolarMass FromHectogramsPerMole(QuantityValue value) { return new MolarMass(value, MolarMassUnit.HectogramPerMole); } @@ -419,7 +401,7 @@ public static MolarMass FromHectogramsPerMole(double value) /// /// Creates a from . /// - public static MolarMass FromKilogramsPerKilomole(double value) + public static MolarMass FromKilogramsPerKilomole(QuantityValue value) { return new MolarMass(value, MolarMassUnit.KilogramPerKilomole); } @@ -427,7 +409,7 @@ public static MolarMass FromKilogramsPerKilomole(double value) /// /// Creates a from . /// - public static MolarMass FromKilogramsPerMole(double value) + public static MolarMass FromKilogramsPerMole(QuantityValue value) { return new MolarMass(value, MolarMassUnit.KilogramPerMole); } @@ -435,7 +417,7 @@ public static MolarMass FromKilogramsPerMole(double value) /// /// Creates a from . /// - public static MolarMass FromKilopoundsPerMole(double value) + public static MolarMass FromKilopoundsPerMole(QuantityValue value) { return new MolarMass(value, MolarMassUnit.KilopoundPerMole); } @@ -443,7 +425,7 @@ public static MolarMass FromKilopoundsPerMole(double value) /// /// Creates a from . /// - public static MolarMass FromMegapoundsPerMole(double value) + public static MolarMass FromMegapoundsPerMole(QuantityValue value) { return new MolarMass(value, MolarMassUnit.MegapoundPerMole); } @@ -451,7 +433,7 @@ public static MolarMass FromMegapoundsPerMole(double value) /// /// Creates a from . /// - public static MolarMass FromMicrogramsPerMole(double value) + public static MolarMass FromMicrogramsPerMole(QuantityValue value) { return new MolarMass(value, MolarMassUnit.MicrogramPerMole); } @@ -459,7 +441,7 @@ public static MolarMass FromMicrogramsPerMole(double value) /// /// Creates a from . /// - public static MolarMass FromMilligramsPerMole(double value) + public static MolarMass FromMilligramsPerMole(QuantityValue value) { return new MolarMass(value, MolarMassUnit.MilligramPerMole); } @@ -467,7 +449,7 @@ public static MolarMass FromMilligramsPerMole(double value) /// /// Creates a from . /// - public static MolarMass FromNanogramsPerMole(double value) + public static MolarMass FromNanogramsPerMole(QuantityValue value) { return new MolarMass(value, MolarMassUnit.NanogramPerMole); } @@ -475,7 +457,7 @@ public static MolarMass FromNanogramsPerMole(double value) /// /// Creates a from . /// - public static MolarMass FromPoundsPerMole(double value) + public static MolarMass FromPoundsPerMole(QuantityValue value) { return new MolarMass(value, MolarMassUnit.PoundPerMole); } @@ -486,7 +468,7 @@ public static MolarMass FromPoundsPerMole(double value) /// Value to convert from. /// Unit to convert from. /// MolarMass unit value. - public static MolarMass From(double value, MolarMassUnit fromUnit) + public static MolarMass From(QuantityValue value, MolarMassUnit fromUnit) { return new MolarMass(value, fromUnit); } @@ -547,10 +529,7 @@ public static MolarMass Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static MolarMass Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -578,11 +557,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out MolarMass result /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out MolarMass result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -603,7 +578,7 @@ public static MolarMassUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -614,7 +589,7 @@ public static MolarMassUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out MolarMassUnit unit) { return TryParseUnit(str, null, out unit); @@ -629,7 +604,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out MolarMassUni /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out MolarMassUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -648,35 +623,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static MolarMass operator +(MolarMass left, MolarMass right) { - return new MolarMass(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new MolarMass(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static MolarMass operator -(MolarMass left, MolarMass right) { - return new MolarMass(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new MolarMass(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -710,97 +685,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(MolarMass left, MolarMass right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(MolarMass left, MolarMass right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(MolarMass left, MolarMass right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(MolarMass left, MolarMass right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MolarMass other, MolarMass tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(MolarMass left, MolarMass right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(MolarMass other, MolarMass tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(MolarMass left, MolarMass right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MolarMass other, MolarMass tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is MolarMass otherQuantity)) + if (obj is not MolarMass otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(MolarMass other, MolarMass tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(MolarMass other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current MolarMass. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(MolarMass), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is MolarMass otherQuantity)) throw new ArgumentException("Expected type MolarMass.", nameof(obj)); + if (obj is not MolarMass otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -812,170 +772,24 @@ public int CompareTo(object? obj) /// public int CompareTo(MolarMass other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarMassUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this MolarMass to another MolarMass with the unit representation . - /// - /// The unit to convert to. - /// A MolarMass with the specified unit. - public MolarMass ToUnit(MolarMassUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A MolarMass with the specified unit. - public MolarMass ToUnit(MolarMassUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(MolarMass), Unit, typeof(MolarMass), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (MolarMass)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(MolarMassUnit unit, [NotNullWhen(true)] out MolarMass? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - MolarMass? convertedOrNull = (Unit, unit) switch - { - // MolarMassUnit -> BaseUnit - (MolarMassUnit.CentigramPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value / 1e3) * 1e-2d, MolarMassUnit.KilogramPerMole), - (MolarMassUnit.DecagramPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value / 1e3) * 1e1d, MolarMassUnit.KilogramPerMole), - (MolarMassUnit.DecigramPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value / 1e3) * 1e-1d, MolarMassUnit.KilogramPerMole), - (MolarMassUnit.GramPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass(_value / 1e3, MolarMassUnit.KilogramPerMole), - (MolarMassUnit.HectogramPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value / 1e3) * 1e2d, MolarMassUnit.KilogramPerMole), - (MolarMassUnit.KilogramPerKilomole, MolarMassUnit.KilogramPerMole) => new MolarMass(_value / 1e3, MolarMassUnit.KilogramPerMole), - (MolarMassUnit.KilopoundPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value * 0.45359237) * 1e3d, MolarMassUnit.KilogramPerMole), - (MolarMassUnit.MegapoundPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value * 0.45359237) * 1e6d, MolarMassUnit.KilogramPerMole), - (MolarMassUnit.MicrogramPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value / 1e3) * 1e-6d, MolarMassUnit.KilogramPerMole), - (MolarMassUnit.MilligramPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value / 1e3) * 1e-3d, MolarMassUnit.KilogramPerMole), - (MolarMassUnit.NanogramPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass((_value / 1e3) * 1e-9d, MolarMassUnit.KilogramPerMole), - (MolarMassUnit.PoundPerMole, MolarMassUnit.KilogramPerMole) => new MolarMass(_value * 0.45359237, MolarMassUnit.KilogramPerMole), - - // BaseUnit -> MolarMassUnit - (MolarMassUnit.KilogramPerMole, MolarMassUnit.CentigramPerMole) => new MolarMass((_value * 1e3) / 1e-2d, MolarMassUnit.CentigramPerMole), - (MolarMassUnit.KilogramPerMole, MolarMassUnit.DecagramPerMole) => new MolarMass((_value * 1e3) / 1e1d, MolarMassUnit.DecagramPerMole), - (MolarMassUnit.KilogramPerMole, MolarMassUnit.DecigramPerMole) => new MolarMass((_value * 1e3) / 1e-1d, MolarMassUnit.DecigramPerMole), - (MolarMassUnit.KilogramPerMole, MolarMassUnit.GramPerMole) => new MolarMass(_value * 1e3, MolarMassUnit.GramPerMole), - (MolarMassUnit.KilogramPerMole, MolarMassUnit.HectogramPerMole) => new MolarMass((_value * 1e3) / 1e2d, MolarMassUnit.HectogramPerMole), - (MolarMassUnit.KilogramPerMole, MolarMassUnit.KilogramPerKilomole) => new MolarMass(_value * 1e3, MolarMassUnit.KilogramPerKilomole), - (MolarMassUnit.KilogramPerMole, MolarMassUnit.KilopoundPerMole) => new MolarMass((_value / 0.45359237) / 1e3d, MolarMassUnit.KilopoundPerMole), - (MolarMassUnit.KilogramPerMole, MolarMassUnit.MegapoundPerMole) => new MolarMass((_value / 0.45359237) / 1e6d, MolarMassUnit.MegapoundPerMole), - (MolarMassUnit.KilogramPerMole, MolarMassUnit.MicrogramPerMole) => new MolarMass((_value * 1e3) / 1e-6d, MolarMassUnit.MicrogramPerMole), - (MolarMassUnit.KilogramPerMole, MolarMassUnit.MilligramPerMole) => new MolarMass((_value * 1e3) / 1e-3d, MolarMassUnit.MilligramPerMole), - (MolarMassUnit.KilogramPerMole, MolarMassUnit.NanogramPerMole) => new MolarMass((_value * 1e3) / 1e-9d, MolarMassUnit.NanogramPerMole), - (MolarMassUnit.KilogramPerMole, MolarMassUnit.PoundPerMole) => new MolarMass(_value / 0.45359237, MolarMassUnit.PoundPerMole), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public MolarMass ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not MolarMassUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarMassUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(MolarMassUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(MolarMassUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -990,7 +804,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs b/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs index 1782635893..dfed366b03 100644 --- a/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Molarity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Molar_concentration /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Molarity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -60,13 +59,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly MolarityUnit? _unit; /// @@ -111,7 +110,7 @@ public static MolarityInfo CreateDefault(Func - /// The for is [L^-3][N]. + /// The for is L^-3N. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-3, 0, 0, 0, 0, 1, 0); @@ -126,25 +125,43 @@ public static MolarityInfo CreateDefault(FuncAn of representing the default unit mappings for Molarity. public static IEnumerable> GetDefaultMappings() { - yield return new (MolarityUnit.CentimolePerLiter, "CentimolePerLiter", "CentimolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Centimole)); - yield return new (MolarityUnit.DecimolePerLiter, "DecimolePerLiter", "DecimolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Decimole)); - yield return new (MolarityUnit.FemtomolePerLiter, "FemtomolePerLiter", "FemtomolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Femtomole)); - yield return new (MolarityUnit.KilomolePerCubicMeter, "KilomolePerCubicMeter", "KilomolesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, amount: AmountOfSubstanceUnit.Kilomole)); - yield return new (MolarityUnit.MicromolePerLiter, "MicromolePerLiter", "MicromolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Micromole)); - yield return new (MolarityUnit.MillimolePerLiter, "MillimolePerLiter", "MillimolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Millimole)); + yield return new (MolarityUnit.CentimolePerLiter, "CentimolePerLiter", "CentimolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Centimole), + new QuantityValue(1, 10) + ); + yield return new (MolarityUnit.DecimolePerLiter, "DecimolePerLiter", "DecimolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Decimole), + new QuantityValue(1, 100) + ); + yield return new (MolarityUnit.FemtomolePerLiter, "FemtomolePerLiter", "FemtomolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Femtomole), + 1000000000000 + ); + yield return new (MolarityUnit.KilomolePerCubicMeter, "KilomolePerCubicMeter", "KilomolesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, amount: AmountOfSubstanceUnit.Kilomole), + new QuantityValue(1, 1000) + ); + yield return new (MolarityUnit.MicromolePerLiter, "MicromolePerLiter", "MicromolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Micromole), + 1000 + ); + yield return new (MolarityUnit.MillimolePerLiter, "MillimolePerLiter", "MillimolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Millimole), + 1 + ); yield return new (MolarityUnit.MolePerCubicMeter, "MolePerCubicMeter", "MolesPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, amount: AmountOfSubstanceUnit.Mole)); - yield return new (MolarityUnit.MolePerLiter, "MolePerLiter", "MolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Mole)); - yield return new (MolarityUnit.NanomolePerLiter, "NanomolePerLiter", "NanomolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Nanomole)); - yield return new (MolarityUnit.PicomolePerLiter, "PicomolePerLiter", "PicomolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Picomole)); - yield return new (MolarityUnit.PoundMolePerCubicFoot, "PoundMolePerCubicFoot", "PoundMolesPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, amount: AmountOfSubstanceUnit.PoundMole)); + yield return new (MolarityUnit.MolePerLiter, "MolePerLiter", "MolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Mole), + new QuantityValue(1, 1000) + ); + yield return new (MolarityUnit.NanomolePerLiter, "NanomolePerLiter", "NanomolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Nanomole), + 1000000 + ); + yield return new (MolarityUnit.PicomolePerLiter, "PicomolePerLiter", "PicomolesPerLiter", new BaseUnits(length: LengthUnit.Decimeter, amount: AmountOfSubstanceUnit.Picomole), + 1000000000 + ); + yield return new (MolarityUnit.PoundMolePerCubicFoot, "PoundMolePerCubicFoot", "PoundMolesPerCubicFoot", new BaseUnits(length: LengthUnit.Foot, amount: AmountOfSubstanceUnit.PoundMole), + new QuantityValue(221225364, 3543690390625) + ); } } static Molarity() { - Info = MolarityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(MolarityInfo.CreateDefault); } /// @@ -152,7 +169,7 @@ static Molarity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Molarity(double value, MolarityUnit unit) + public Molarity(QuantityValue value, MolarityUnit unit) { _value = value; _unit = unit; @@ -166,7 +183,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -177,7 +194,8 @@ public Molarity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -206,10 +224,8 @@ public Molarity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public MolarityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -248,98 +264,64 @@ public Molarity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentimolesPerLiter => As(MolarityUnit.CentimolePerLiter); + public QuantityValue CentimolesPerLiter => this.As(MolarityUnit.CentimolePerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecimolesPerLiter => As(MolarityUnit.DecimolePerLiter); + public QuantityValue DecimolesPerLiter => this.As(MolarityUnit.DecimolePerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double FemtomolesPerLiter => As(MolarityUnit.FemtomolePerLiter); + public QuantityValue FemtomolesPerLiter => this.As(MolarityUnit.FemtomolePerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilomolesPerCubicMeter => As(MolarityUnit.KilomolePerCubicMeter); + public QuantityValue KilomolesPerCubicMeter => this.As(MolarityUnit.KilomolePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicromolesPerLiter => As(MolarityUnit.MicromolePerLiter); + public QuantityValue MicromolesPerLiter => this.As(MolarityUnit.MicromolePerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimolesPerLiter => As(MolarityUnit.MillimolePerLiter); + public QuantityValue MillimolesPerLiter => this.As(MolarityUnit.MillimolePerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MolesPerCubicMeter => As(MolarityUnit.MolePerCubicMeter); + public QuantityValue MolesPerCubicMeter => this.As(MolarityUnit.MolePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MolesPerLiter => As(MolarityUnit.MolePerLiter); + public QuantityValue MolesPerLiter => this.As(MolarityUnit.MolePerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanomolesPerLiter => As(MolarityUnit.NanomolePerLiter); + public QuantityValue NanomolesPerLiter => this.As(MolarityUnit.NanomolePerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicomolesPerLiter => As(MolarityUnit.PicomolePerLiter); + public QuantityValue PicomolesPerLiter => this.As(MolarityUnit.PicomolePerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundMolesPerCubicFoot => As(MolarityUnit.PoundMolePerCubicFoot); + public QuantityValue PoundMolesPerCubicFoot => this.As(MolarityUnit.PoundMolePerCubicFoot); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: MolarityUnit -> BaseUnit - unitConverter.SetConversionFunction(MolarityUnit.CentimolePerLiter, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); - unitConverter.SetConversionFunction(MolarityUnit.DecimolePerLiter, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); - unitConverter.SetConversionFunction(MolarityUnit.FemtomolePerLiter, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); - unitConverter.SetConversionFunction(MolarityUnit.KilomolePerCubicMeter, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); - unitConverter.SetConversionFunction(MolarityUnit.MicromolePerLiter, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); - unitConverter.SetConversionFunction(MolarityUnit.MillimolePerLiter, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); - unitConverter.SetConversionFunction(MolarityUnit.MolePerLiter, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); - unitConverter.SetConversionFunction(MolarityUnit.NanomolePerLiter, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); - unitConverter.SetConversionFunction(MolarityUnit.PicomolePerLiter, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); - unitConverter.SetConversionFunction(MolarityUnit.PoundMolePerCubicFoot, MolarityUnit.MolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.MolePerCubicMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(MolarityUnit.MolePerCubicMeter, MolarityUnit.MolePerCubicMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> MolarityUnit - unitConverter.SetConversionFunction(MolarityUnit.MolePerCubicMeter, MolarityUnit.CentimolePerLiter, quantity => quantity.ToUnit(MolarityUnit.CentimolePerLiter)); - unitConverter.SetConversionFunction(MolarityUnit.MolePerCubicMeter, MolarityUnit.DecimolePerLiter, quantity => quantity.ToUnit(MolarityUnit.DecimolePerLiter)); - unitConverter.SetConversionFunction(MolarityUnit.MolePerCubicMeter, MolarityUnit.FemtomolePerLiter, quantity => quantity.ToUnit(MolarityUnit.FemtomolePerLiter)); - unitConverter.SetConversionFunction(MolarityUnit.MolePerCubicMeter, MolarityUnit.KilomolePerCubicMeter, quantity => quantity.ToUnit(MolarityUnit.KilomolePerCubicMeter)); - unitConverter.SetConversionFunction(MolarityUnit.MolePerCubicMeter, MolarityUnit.MicromolePerLiter, quantity => quantity.ToUnit(MolarityUnit.MicromolePerLiter)); - unitConverter.SetConversionFunction(MolarityUnit.MolePerCubicMeter, MolarityUnit.MillimolePerLiter, quantity => quantity.ToUnit(MolarityUnit.MillimolePerLiter)); - unitConverter.SetConversionFunction(MolarityUnit.MolePerCubicMeter, MolarityUnit.MolePerLiter, quantity => quantity.ToUnit(MolarityUnit.MolePerLiter)); - unitConverter.SetConversionFunction(MolarityUnit.MolePerCubicMeter, MolarityUnit.NanomolePerLiter, quantity => quantity.ToUnit(MolarityUnit.NanomolePerLiter)); - unitConverter.SetConversionFunction(MolarityUnit.MolePerCubicMeter, MolarityUnit.PicomolePerLiter, quantity => quantity.ToUnit(MolarityUnit.PicomolePerLiter)); - unitConverter.SetConversionFunction(MolarityUnit.MolePerCubicMeter, MolarityUnit.PoundMolePerCubicFoot, quantity => quantity.ToUnit(MolarityUnit.PoundMolePerCubicFoot)); - } - /// /// Get unit abbreviation string. /// @@ -368,7 +350,7 @@ public static string GetAbbreviation(MolarityUnit unit, IFormatProvider? provide /// /// Creates a from . /// - public static Molarity FromCentimolesPerLiter(double value) + public static Molarity FromCentimolesPerLiter(QuantityValue value) { return new Molarity(value, MolarityUnit.CentimolePerLiter); } @@ -376,7 +358,7 @@ public static Molarity FromCentimolesPerLiter(double value) /// /// Creates a from . /// - public static Molarity FromDecimolesPerLiter(double value) + public static Molarity FromDecimolesPerLiter(QuantityValue value) { return new Molarity(value, MolarityUnit.DecimolePerLiter); } @@ -384,7 +366,7 @@ public static Molarity FromDecimolesPerLiter(double value) /// /// Creates a from . /// - public static Molarity FromFemtomolesPerLiter(double value) + public static Molarity FromFemtomolesPerLiter(QuantityValue value) { return new Molarity(value, MolarityUnit.FemtomolePerLiter); } @@ -392,7 +374,7 @@ public static Molarity FromFemtomolesPerLiter(double value) /// /// Creates a from . /// - public static Molarity FromKilomolesPerCubicMeter(double value) + public static Molarity FromKilomolesPerCubicMeter(QuantityValue value) { return new Molarity(value, MolarityUnit.KilomolePerCubicMeter); } @@ -400,7 +382,7 @@ public static Molarity FromKilomolesPerCubicMeter(double value) /// /// Creates a from . /// - public static Molarity FromMicromolesPerLiter(double value) + public static Molarity FromMicromolesPerLiter(QuantityValue value) { return new Molarity(value, MolarityUnit.MicromolePerLiter); } @@ -408,7 +390,7 @@ public static Molarity FromMicromolesPerLiter(double value) /// /// Creates a from . /// - public static Molarity FromMillimolesPerLiter(double value) + public static Molarity FromMillimolesPerLiter(QuantityValue value) { return new Molarity(value, MolarityUnit.MillimolePerLiter); } @@ -416,7 +398,7 @@ public static Molarity FromMillimolesPerLiter(double value) /// /// Creates a from . /// - public static Molarity FromMolesPerCubicMeter(double value) + public static Molarity FromMolesPerCubicMeter(QuantityValue value) { return new Molarity(value, MolarityUnit.MolePerCubicMeter); } @@ -424,7 +406,7 @@ public static Molarity FromMolesPerCubicMeter(double value) /// /// Creates a from . /// - public static Molarity FromMolesPerLiter(double value) + public static Molarity FromMolesPerLiter(QuantityValue value) { return new Molarity(value, MolarityUnit.MolePerLiter); } @@ -432,7 +414,7 @@ public static Molarity FromMolesPerLiter(double value) /// /// Creates a from . /// - public static Molarity FromNanomolesPerLiter(double value) + public static Molarity FromNanomolesPerLiter(QuantityValue value) { return new Molarity(value, MolarityUnit.NanomolePerLiter); } @@ -440,7 +422,7 @@ public static Molarity FromNanomolesPerLiter(double value) /// /// Creates a from . /// - public static Molarity FromPicomolesPerLiter(double value) + public static Molarity FromPicomolesPerLiter(QuantityValue value) { return new Molarity(value, MolarityUnit.PicomolePerLiter); } @@ -448,7 +430,7 @@ public static Molarity FromPicomolesPerLiter(double value) /// /// Creates a from . /// - public static Molarity FromPoundMolesPerCubicFoot(double value) + public static Molarity FromPoundMolesPerCubicFoot(QuantityValue value) { return new Molarity(value, MolarityUnit.PoundMolePerCubicFoot); } @@ -459,7 +441,7 @@ public static Molarity FromPoundMolesPerCubicFoot(double value) /// Value to convert from. /// Unit to convert from. /// Molarity unit value. - public static Molarity From(double value, MolarityUnit fromUnit) + public static Molarity From(QuantityValue value, MolarityUnit fromUnit) { return new Molarity(value, fromUnit); } @@ -520,10 +502,7 @@ public static Molarity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Molarity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -551,11 +530,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Molarity result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Molarity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -576,7 +551,7 @@ public static MolarityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -587,7 +562,7 @@ public static MolarityUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out MolarityUnit unit) { return TryParseUnit(str, null, out unit); @@ -602,7 +577,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out MolarityUnit /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out MolarityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -621,35 +596,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Molarity operator +(Molarity left, Molarity right) { - return new Molarity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Molarity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Molarity operator -(Molarity left, Molarity right) { - return new Molarity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Molarity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -695,97 +670,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Molarity left, Molarity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Molarity left, Molarity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Molarity left, Molarity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Molarity left, Molarity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Molarity other, Molarity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Molarity left, Molarity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Molarity other, Molarity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Molarity left, Molarity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Molarity other, Molarity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Molarity otherQuantity)) + if (obj is not Molarity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Molarity other, Molarity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Molarity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Molarity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Molarity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Molarity otherQuantity)) throw new ArgumentException("Expected type Molarity.", nameof(obj)); + if (obj is not Molarity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -797,166 +757,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Molarity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(MolarityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Molarity to another Molarity with the unit representation . - /// - /// The unit to convert to. - /// A Molarity with the specified unit. - public Molarity ToUnit(MolarityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Molarity with the specified unit. - public Molarity ToUnit(MolarityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Molarity), Unit, typeof(Molarity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Molarity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(MolarityUnit unit, [NotNullWhen(true)] out Molarity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Molarity? convertedOrNull = (Unit, unit) switch - { - // MolarityUnit -> BaseUnit - (MolarityUnit.CentimolePerLiter, MolarityUnit.MolePerCubicMeter) => new Molarity((_value / 1e-3) * 1e-2d, MolarityUnit.MolePerCubicMeter), - (MolarityUnit.DecimolePerLiter, MolarityUnit.MolePerCubicMeter) => new Molarity((_value / 1e-3) * 1e-1d, MolarityUnit.MolePerCubicMeter), - (MolarityUnit.FemtomolePerLiter, MolarityUnit.MolePerCubicMeter) => new Molarity((_value / 1e-3) * 1e-15d, MolarityUnit.MolePerCubicMeter), - (MolarityUnit.KilomolePerCubicMeter, MolarityUnit.MolePerCubicMeter) => new Molarity((_value) * 1e3d, MolarityUnit.MolePerCubicMeter), - (MolarityUnit.MicromolePerLiter, MolarityUnit.MolePerCubicMeter) => new Molarity((_value / 1e-3) * 1e-6d, MolarityUnit.MolePerCubicMeter), - (MolarityUnit.MillimolePerLiter, MolarityUnit.MolePerCubicMeter) => new Molarity((_value / 1e-3) * 1e-3d, MolarityUnit.MolePerCubicMeter), - (MolarityUnit.MolePerLiter, MolarityUnit.MolePerCubicMeter) => new Molarity(_value / 1e-3, MolarityUnit.MolePerCubicMeter), - (MolarityUnit.NanomolePerLiter, MolarityUnit.MolePerCubicMeter) => new Molarity((_value / 1e-3) * 1e-9d, MolarityUnit.MolePerCubicMeter), - (MolarityUnit.PicomolePerLiter, MolarityUnit.MolePerCubicMeter) => new Molarity((_value / 1e-3) * 1e-12d, MolarityUnit.MolePerCubicMeter), - (MolarityUnit.PoundMolePerCubicFoot, MolarityUnit.MolePerCubicMeter) => new Molarity(_value * 1000 * 0.45359237 / 0.028316846592, MolarityUnit.MolePerCubicMeter), - - // BaseUnit -> MolarityUnit - (MolarityUnit.MolePerCubicMeter, MolarityUnit.CentimolePerLiter) => new Molarity((_value * 1e-3) / 1e-2d, MolarityUnit.CentimolePerLiter), - (MolarityUnit.MolePerCubicMeter, MolarityUnit.DecimolePerLiter) => new Molarity((_value * 1e-3) / 1e-1d, MolarityUnit.DecimolePerLiter), - (MolarityUnit.MolePerCubicMeter, MolarityUnit.FemtomolePerLiter) => new Molarity((_value * 1e-3) / 1e-15d, MolarityUnit.FemtomolePerLiter), - (MolarityUnit.MolePerCubicMeter, MolarityUnit.KilomolePerCubicMeter) => new Molarity((_value) / 1e3d, MolarityUnit.KilomolePerCubicMeter), - (MolarityUnit.MolePerCubicMeter, MolarityUnit.MicromolePerLiter) => new Molarity((_value * 1e-3) / 1e-6d, MolarityUnit.MicromolePerLiter), - (MolarityUnit.MolePerCubicMeter, MolarityUnit.MillimolePerLiter) => new Molarity((_value * 1e-3) / 1e-3d, MolarityUnit.MillimolePerLiter), - (MolarityUnit.MolePerCubicMeter, MolarityUnit.MolePerLiter) => new Molarity(_value * 1e-3, MolarityUnit.MolePerLiter), - (MolarityUnit.MolePerCubicMeter, MolarityUnit.NanomolePerLiter) => new Molarity((_value * 1e-3) / 1e-9d, MolarityUnit.NanomolePerLiter), - (MolarityUnit.MolePerCubicMeter, MolarityUnit.PicomolePerLiter) => new Molarity((_value * 1e-3) / 1e-12d, MolarityUnit.PicomolePerLiter), - (MolarityUnit.MolePerCubicMeter, MolarityUnit.PoundMolePerCubicFoot) => new Molarity(_value / (1000 * 0.45359237 / 0.028316846592), MolarityUnit.PoundMolePerCubicFoot), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Molarity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not MolarityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(MolarityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(MolarityUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(MolarityUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -971,7 +789,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs b/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs index dc5f8837d6..239fa7df8e 100644 --- a/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Permeability.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Permeability_(electromagnetism) /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Permeability : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly PermeabilityUnit? _unit; /// @@ -104,7 +103,7 @@ public static PermeabilityInfo CreateDefault(Func - /// The for is [T^-2][L][M][I^-2]. + /// The for is T^-2LMI^-2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 1, -2, -2, 0, 0, 0); @@ -125,9 +124,7 @@ public static IEnumerable> GetDefaultMappings() static Permeability() { - Info = PermeabilityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(PermeabilityInfo.CreateDefault); } /// @@ -135,7 +132,7 @@ static Permeability() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Permeability(double value, PermeabilityUnit unit) + public Permeability(QuantityValue value, PermeabilityUnit unit) { _value = value; _unit = unit; @@ -149,7 +146,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -160,7 +157,8 @@ public Permeability(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -189,10 +187,8 @@ public Permeability(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public PermeabilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -231,28 +227,14 @@ public Permeability(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HenriesPerMeter => As(PermeabilityUnit.HenryPerMeter); + public QuantityValue HenriesPerMeter => this.As(PermeabilityUnit.HenryPerMeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: PermeabilityUnit -> BaseUnit - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(PermeabilityUnit.HenryPerMeter, PermeabilityUnit.HenryPerMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> PermeabilityUnit - } - /// /// Get unit abbreviation string. /// @@ -281,7 +263,7 @@ public static string GetAbbreviation(PermeabilityUnit unit, IFormatProvider? pro /// /// Creates a from . /// - public static Permeability FromHenriesPerMeter(double value) + public static Permeability FromHenriesPerMeter(QuantityValue value) { return new Permeability(value, PermeabilityUnit.HenryPerMeter); } @@ -292,7 +274,7 @@ public static Permeability FromHenriesPerMeter(double value) /// Value to convert from. /// Unit to convert from. /// Permeability unit value. - public static Permeability From(double value, PermeabilityUnit fromUnit) + public static Permeability From(QuantityValue value, PermeabilityUnit fromUnit) { return new Permeability(value, fromUnit); } @@ -353,10 +335,7 @@ public static Permeability Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Permeability Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -384,11 +363,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Permeability res /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Permeability result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -409,7 +384,7 @@ public static PermeabilityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -420,7 +395,7 @@ public static PermeabilityUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out PermeabilityUnit unit) { return TryParseUnit(str, null, out unit); @@ -435,7 +410,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out Permeability /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out PermeabilityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -454,35 +429,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Permeability operator +(Permeability left, Permeability right) { - return new Permeability(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Permeability(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Permeability operator -(Permeability left, Permeability right) { - return new Permeability(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Permeability(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -494,97 +469,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Permeability left, Permeability right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Permeability left, Permeability right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Permeability left, Permeability right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Permeability left, Permeability right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Permeability other, Permeability tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Permeability left, Permeability right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Permeability other, Permeability tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Permeability left, Permeability right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Permeability other, Permeability tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Permeability otherQuantity)) + if (obj is not Permeability otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Permeability other, Permeability tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Permeability other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Permeability. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Permeability), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Permeability otherQuantity)) throw new ArgumentException("Expected type Permeability.", nameof(obj)); + if (obj is not Permeability otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -596,146 +556,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Permeability other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PermeabilityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this Permeability to another Permeability with the unit representation . - /// - /// The unit to convert to. - /// A Permeability with the specified unit. - public Permeability ToUnit(PermeabilityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Permeability with the specified unit. - public Permeability ToUnit(PermeabilityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Permeability), Unit, typeof(Permeability), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Permeability)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(PermeabilityUnit unit, [NotNullWhen(true)] out Permeability? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Permeability? convertedOrNull = (Unit, unit) switch - { - // PermeabilityUnit -> BaseUnit + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> PermeabilityUnit - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Permeability ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not PermeabilityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermeabilityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is PermeabilityUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermeabilityUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(PermeabilityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(PermeabilityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -750,7 +588,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs b/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs index a28939c50e..7fa721c312 100644 --- a/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Permittivity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Permittivity /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Permittivity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly PermittivityUnit? _unit; /// @@ -104,7 +103,7 @@ public static PermittivityInfo CreateDefault(Func - /// The for is [T^4][L^-3][M^-1][I^2]. + /// The for is T^4L^-3M^-1I^2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-3, -1, 4, 2, 0, 0, 0); @@ -125,9 +124,7 @@ public static IEnumerable> GetDefaultMappings() static Permittivity() { - Info = PermittivityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(PermittivityInfo.CreateDefault); } /// @@ -135,7 +132,7 @@ static Permittivity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Permittivity(double value, PermittivityUnit unit) + public Permittivity(QuantityValue value, PermittivityUnit unit) { _value = value; _unit = unit; @@ -149,7 +146,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -160,7 +157,8 @@ public Permittivity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -189,10 +187,8 @@ public Permittivity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public PermittivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -231,28 +227,14 @@ public Permittivity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double FaradsPerMeter => As(PermittivityUnit.FaradPerMeter); + public QuantityValue FaradsPerMeter => this.As(PermittivityUnit.FaradPerMeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: PermittivityUnit -> BaseUnit - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(PermittivityUnit.FaradPerMeter, PermittivityUnit.FaradPerMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> PermittivityUnit - } - /// /// Get unit abbreviation string. /// @@ -281,7 +263,7 @@ public static string GetAbbreviation(PermittivityUnit unit, IFormatProvider? pro /// /// Creates a from . /// - public static Permittivity FromFaradsPerMeter(double value) + public static Permittivity FromFaradsPerMeter(QuantityValue value) { return new Permittivity(value, PermittivityUnit.FaradPerMeter); } @@ -292,7 +274,7 @@ public static Permittivity FromFaradsPerMeter(double value) /// Value to convert from. /// Unit to convert from. /// Permittivity unit value. - public static Permittivity From(double value, PermittivityUnit fromUnit) + public static Permittivity From(QuantityValue value, PermittivityUnit fromUnit) { return new Permittivity(value, fromUnit); } @@ -353,10 +335,7 @@ public static Permittivity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Permittivity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -384,11 +363,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Permittivity res /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Permittivity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -409,7 +384,7 @@ public static PermittivityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -420,7 +395,7 @@ public static PermittivityUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out PermittivityUnit unit) { return TryParseUnit(str, null, out unit); @@ -435,7 +410,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out Permittivity /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out PermittivityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -454,35 +429,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Permittivity operator +(Permittivity left, Permittivity right) { - return new Permittivity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Permittivity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Permittivity operator -(Permittivity left, Permittivity right) { - return new Permittivity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Permittivity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -494,97 +469,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Permittivity left, Permittivity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Permittivity left, Permittivity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Permittivity left, Permittivity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Permittivity left, Permittivity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Permittivity other, Permittivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Permittivity left, Permittivity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Permittivity other, Permittivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Permittivity left, Permittivity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Permittivity other, Permittivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Permittivity otherQuantity)) + if (obj is not Permittivity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Permittivity other, Permittivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Permittivity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Permittivity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Permittivity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Permittivity otherQuantity)) throw new ArgumentException("Expected type Permittivity.", nameof(obj)); + if (obj is not Permittivity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -596,146 +556,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Permittivity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PermittivityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this Permittivity to another Permittivity with the unit representation . - /// - /// The unit to convert to. - /// A Permittivity with the specified unit. - public Permittivity ToUnit(PermittivityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Permittivity with the specified unit. - public Permittivity ToUnit(PermittivityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Permittivity), Unit, typeof(Permittivity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Permittivity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(PermittivityUnit unit, [NotNullWhen(true)] out Permittivity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Permittivity? convertedOrNull = (Unit, unit) switch - { - // PermittivityUnit -> BaseUnit + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> PermittivityUnit - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Permittivity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not PermittivityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermittivityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is PermittivityUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PermittivityUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(PermittivityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(PermittivityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -750,7 +588,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs b/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs index 87a5c54c1b..9a1bffa840 100644 --- a/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PorousMediumPermeability.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Permeability_(Earth_sciences) /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct PorousMediumPermeability : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly PorousMediumPermeabilityUnit? _unit; /// @@ -104,7 +103,7 @@ public static PorousMediumPermeabilityInfo CreateDefault(Func - /// The for is [L^2]. + /// The for is L^2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); @@ -119,19 +118,25 @@ public static PorousMediumPermeabilityInfo CreateDefault(FuncAn of representing the default unit mappings for PorousMediumPermeability. public static IEnumerable> GetDefaultMappings() { - yield return new (PorousMediumPermeabilityUnit.Darcy, "Darcy", "Darcys", BaseUnits.Undefined); - yield return new (PorousMediumPermeabilityUnit.Microdarcy, "Microdarcy", "Microdarcys", BaseUnits.Undefined); - yield return new (PorousMediumPermeabilityUnit.Millidarcy, "Millidarcy", "Millidarcys", BaseUnits.Undefined); - yield return new (PorousMediumPermeabilityUnit.SquareCentimeter, "SquareCentimeter", "SquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter)); + yield return new (PorousMediumPermeabilityUnit.Darcy, "Darcy", "Darcys", BaseUnits.Undefined, + new QuantityValue(QuantityValue.PowerOfTen(19), 9869233) + ); + yield return new (PorousMediumPermeabilityUnit.Microdarcy, "Microdarcy", "Microdarcys", BaseUnits.Undefined, + new QuantityValue(QuantityValue.PowerOfTen(25), 9869233) + ); + yield return new (PorousMediumPermeabilityUnit.Millidarcy, "Millidarcy", "Millidarcys", BaseUnits.Undefined, + new QuantityValue(QuantityValue.PowerOfTen(22), 9869233) + ); + yield return new (PorousMediumPermeabilityUnit.SquareCentimeter, "SquareCentimeter", "SquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter), + 10000 + ); yield return new (PorousMediumPermeabilityUnit.SquareMeter, "SquareMeter", "SquareMeters", new BaseUnits(length: LengthUnit.Meter)); } } static PorousMediumPermeability() { - Info = PorousMediumPermeabilityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(PorousMediumPermeabilityInfo.CreateDefault); } /// @@ -139,7 +144,7 @@ static PorousMediumPermeability() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public PorousMediumPermeability(double value, PorousMediumPermeabilityUnit unit) + public PorousMediumPermeability(QuantityValue value, PorousMediumPermeabilityUnit unit) { _value = value; _unit = unit; @@ -153,7 +158,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -164,7 +169,8 @@ public PorousMediumPermeability(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -193,10 +199,8 @@ public PorousMediumPermeability(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public PorousMediumPermeabilityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -235,56 +239,34 @@ public PorousMediumPermeability(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Darcys => As(PorousMediumPermeabilityUnit.Darcy); + public QuantityValue Darcys => this.As(PorousMediumPermeabilityUnit.Darcy); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microdarcys => As(PorousMediumPermeabilityUnit.Microdarcy); + public QuantityValue Microdarcys => this.As(PorousMediumPermeabilityUnit.Microdarcy); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millidarcys => As(PorousMediumPermeabilityUnit.Millidarcy); + public QuantityValue Millidarcys => this.As(PorousMediumPermeabilityUnit.Millidarcy); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareCentimeters => As(PorousMediumPermeabilityUnit.SquareCentimeter); + public QuantityValue SquareCentimeters => this.As(PorousMediumPermeabilityUnit.SquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareMeters => As(PorousMediumPermeabilityUnit.SquareMeter); + public QuantityValue SquareMeters => this.As(PorousMediumPermeabilityUnit.SquareMeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: PorousMediumPermeabilityUnit -> BaseUnit - unitConverter.SetConversionFunction(PorousMediumPermeabilityUnit.Darcy, PorousMediumPermeabilityUnit.SquareMeter, quantity => quantity.ToUnit(PorousMediumPermeabilityUnit.SquareMeter)); - unitConverter.SetConversionFunction(PorousMediumPermeabilityUnit.Microdarcy, PorousMediumPermeabilityUnit.SquareMeter, quantity => quantity.ToUnit(PorousMediumPermeabilityUnit.SquareMeter)); - unitConverter.SetConversionFunction(PorousMediumPermeabilityUnit.Millidarcy, PorousMediumPermeabilityUnit.SquareMeter, quantity => quantity.ToUnit(PorousMediumPermeabilityUnit.SquareMeter)); - unitConverter.SetConversionFunction(PorousMediumPermeabilityUnit.SquareCentimeter, PorousMediumPermeabilityUnit.SquareMeter, quantity => quantity.ToUnit(PorousMediumPermeabilityUnit.SquareMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.SquareMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> PorousMediumPermeabilityUnit - unitConverter.SetConversionFunction(PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.Darcy, quantity => quantity.ToUnit(PorousMediumPermeabilityUnit.Darcy)); - unitConverter.SetConversionFunction(PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.Microdarcy, quantity => quantity.ToUnit(PorousMediumPermeabilityUnit.Microdarcy)); - unitConverter.SetConversionFunction(PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.Millidarcy, quantity => quantity.ToUnit(PorousMediumPermeabilityUnit.Millidarcy)); - unitConverter.SetConversionFunction(PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.SquareCentimeter, quantity => quantity.ToUnit(PorousMediumPermeabilityUnit.SquareCentimeter)); - } - /// /// Get unit abbreviation string. /// @@ -313,7 +295,7 @@ public static string GetAbbreviation(PorousMediumPermeabilityUnit unit, IFormatP /// /// Creates a from . /// - public static PorousMediumPermeability FromDarcys(double value) + public static PorousMediumPermeability FromDarcys(QuantityValue value) { return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.Darcy); } @@ -321,7 +303,7 @@ public static PorousMediumPermeability FromDarcys(double value) /// /// Creates a from . /// - public static PorousMediumPermeability FromMicrodarcys(double value) + public static PorousMediumPermeability FromMicrodarcys(QuantityValue value) { return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.Microdarcy); } @@ -329,7 +311,7 @@ public static PorousMediumPermeability FromMicrodarcys(double value) /// /// Creates a from . /// - public static PorousMediumPermeability FromMillidarcys(double value) + public static PorousMediumPermeability FromMillidarcys(QuantityValue value) { return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.Millidarcy); } @@ -337,7 +319,7 @@ public static PorousMediumPermeability FromMillidarcys(double value) /// /// Creates a from . /// - public static PorousMediumPermeability FromSquareCentimeters(double value) + public static PorousMediumPermeability FromSquareCentimeters(QuantityValue value) { return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.SquareCentimeter); } @@ -345,7 +327,7 @@ public static PorousMediumPermeability FromSquareCentimeters(double value) /// /// Creates a from . /// - public static PorousMediumPermeability FromSquareMeters(double value) + public static PorousMediumPermeability FromSquareMeters(QuantityValue value) { return new PorousMediumPermeability(value, PorousMediumPermeabilityUnit.SquareMeter); } @@ -356,7 +338,7 @@ public static PorousMediumPermeability FromSquareMeters(double value) /// Value to convert from. /// Unit to convert from. /// PorousMediumPermeability unit value. - public static PorousMediumPermeability From(double value, PorousMediumPermeabilityUnit fromUnit) + public static PorousMediumPermeability From(QuantityValue value, PorousMediumPermeabilityUnit fromUnit) { return new PorousMediumPermeability(value, fromUnit); } @@ -417,10 +399,7 @@ public static PorousMediumPermeability Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static PorousMediumPermeability Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -448,11 +427,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out PorousMediumPerm /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out PorousMediumPermeability result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -473,7 +448,7 @@ public static PorousMediumPermeabilityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -484,7 +459,7 @@ public static PorousMediumPermeabilityUnit ParseUnit(string str, IFormatProvider return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out PorousMediumPermeabilityUnit unit) { return TryParseUnit(str, null, out unit); @@ -499,7 +474,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out PorousMedium /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out PorousMediumPermeabilityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -518,35 +493,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static PorousMediumPermeability operator +(PorousMediumPermeability left, PorousMediumPermeability right) { - return new PorousMediumPermeability(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new PorousMediumPermeability(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static PorousMediumPermeability operator -(PorousMediumPermeability left, PorousMediumPermeability right) { - return new PorousMediumPermeability(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new PorousMediumPermeability(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -558,97 +533,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(PorousMediumPermeability left, PorousMediumPermeability right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(PorousMediumPermeability left, PorousMediumPermeability right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(PorousMediumPermeability left, PorousMediumPermeability right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(PorousMediumPermeability left, PorousMediumPermeability right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(PorousMediumPermeability other, PorousMediumPermeability tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(PorousMediumPermeability left, PorousMediumPermeability right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(PorousMediumPermeability other, PorousMediumPermeability tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(PorousMediumPermeability left, PorousMediumPermeability right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(PorousMediumPermeability other, PorousMediumPermeability tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is PorousMediumPermeability otherQuantity)) + if (obj is not PorousMediumPermeability otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(PorousMediumPermeability other, PorousMediumPermeability tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(PorousMediumPermeability other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current PorousMediumPermeability. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(PorousMediumPermeability), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is PorousMediumPermeability otherQuantity)) throw new ArgumentException("Expected type PorousMediumPermeability.", nameof(obj)); + if (obj is not PorousMediumPermeability otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -660,154 +620,24 @@ public int CompareTo(object? obj) /// public int CompareTo(PorousMediumPermeability other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PorousMediumPermeabilityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this PorousMediumPermeability to another PorousMediumPermeability with the unit representation . - /// - /// The unit to convert to. - /// A PorousMediumPermeability with the specified unit. - public PorousMediumPermeability ToUnit(PorousMediumPermeabilityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A PorousMediumPermeability with the specified unit. - public PorousMediumPermeability ToUnit(PorousMediumPermeabilityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(PorousMediumPermeability), Unit, typeof(PorousMediumPermeability), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (PorousMediumPermeability)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(PorousMediumPermeabilityUnit unit, [NotNullWhen(true)] out PorousMediumPermeability? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - PorousMediumPermeability? convertedOrNull = (Unit, unit) switch - { - // PorousMediumPermeabilityUnit -> BaseUnit - (PorousMediumPermeabilityUnit.Darcy, PorousMediumPermeabilityUnit.SquareMeter) => new PorousMediumPermeability(_value * 9.869233e-13, PorousMediumPermeabilityUnit.SquareMeter), - (PorousMediumPermeabilityUnit.Microdarcy, PorousMediumPermeabilityUnit.SquareMeter) => new PorousMediumPermeability((_value * 9.869233e-13) * 1e-6d, PorousMediumPermeabilityUnit.SquareMeter), - (PorousMediumPermeabilityUnit.Millidarcy, PorousMediumPermeabilityUnit.SquareMeter) => new PorousMediumPermeability((_value * 9.869233e-13) * 1e-3d, PorousMediumPermeabilityUnit.SquareMeter), - (PorousMediumPermeabilityUnit.SquareCentimeter, PorousMediumPermeabilityUnit.SquareMeter) => new PorousMediumPermeability(_value * 1e-4, PorousMediumPermeabilityUnit.SquareMeter), - - // BaseUnit -> PorousMediumPermeabilityUnit - (PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.Darcy) => new PorousMediumPermeability(_value / 9.869233e-13, PorousMediumPermeabilityUnit.Darcy), - (PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.Microdarcy) => new PorousMediumPermeability((_value / 9.869233e-13) / 1e-6d, PorousMediumPermeabilityUnit.Microdarcy), - (PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.Millidarcy) => new PorousMediumPermeability((_value / 9.869233e-13) / 1e-3d, PorousMediumPermeabilityUnit.Millidarcy), - (PorousMediumPermeabilityUnit.SquareMeter, PorousMediumPermeabilityUnit.SquareCentimeter) => new PorousMediumPermeability(_value / 1e-4, PorousMediumPermeabilityUnit.SquareCentimeter), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public PorousMediumPermeability ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not PorousMediumPermeabilityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PorousMediumPermeabilityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(PorousMediumPermeabilityUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(PorousMediumPermeabilityUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -822,7 +652,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Power.g.cs b/UnitsNet/GeneratedCode/Quantities/Power.g.cs index 43145c28ef..e6207242ef 100644 --- a/UnitsNet/GeneratedCode/Quantities/Power.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Power.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// In physics, power is the rate of doing work. It is equivalent to an amount of energy consumed per unit time. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Power : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -66,13 +65,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly PowerUnit? _unit; /// @@ -117,7 +116,7 @@ public static PowerInfo CreateDefault(Func } /// - /// The for is [T^-3][L^2][M]. + /// The for is T^-3L^2M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -3, 0, 0, 0, 0); @@ -132,41 +131,91 @@ public static PowerInfo CreateDefault(Func /// An of representing the default unit mappings for Power. public static IEnumerable> GetDefaultMappings() { - yield return new (PowerUnit.BoilerHorsepower, "BoilerHorsepower", "BoilerHorsepower", BaseUnits.Undefined); - yield return new (PowerUnit.BritishThermalUnitPerHour, "BritishThermalUnitPerHour", "BritishThermalUnitsPerHour", BaseUnits.Undefined); - yield return new (PowerUnit.Decawatt, "Decawatt", "Decawatts", BaseUnits.Undefined); - yield return new (PowerUnit.Deciwatt, "Deciwatt", "Deciwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Hectogram, time: DurationUnit.Second)); - yield return new (PowerUnit.ElectricalHorsepower, "ElectricalHorsepower", "ElectricalHorsepower", BaseUnits.Undefined); - yield return new (PowerUnit.Femtowatt, "Femtowatt", "Femtowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Picogram, time: DurationUnit.Second)); - yield return new (PowerUnit.GigajoulePerHour, "GigajoulePerHour", "GigajoulesPerHour", BaseUnits.Undefined); - yield return new (PowerUnit.Gigawatt, "Gigawatt", "Gigawatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond)); - yield return new (PowerUnit.HydraulicHorsepower, "HydraulicHorsepower", "HydraulicHorsepower", BaseUnits.Undefined); - yield return new (PowerUnit.JoulePerHour, "JoulePerHour", "JoulesPerHour", BaseUnits.Undefined); - yield return new (PowerUnit.KilobritishThermalUnitPerHour, "KilobritishThermalUnitPerHour", "KilobritishThermalUnitsPerHour", BaseUnits.Undefined); - yield return new (PowerUnit.KilojoulePerHour, "KilojoulePerHour", "KilojoulesPerHour", BaseUnits.Undefined); - yield return new (PowerUnit.Kilowatt, "Kilowatt", "Kilowatts", BaseUnits.Undefined); - yield return new (PowerUnit.MechanicalHorsepower, "MechanicalHorsepower", "MechanicalHorsepower", BaseUnits.Undefined); - yield return new (PowerUnit.MegabritishThermalUnitPerHour, "MegabritishThermalUnitPerHour", "MegabritishThermalUnitsPerHour", BaseUnits.Undefined); - yield return new (PowerUnit.MegajoulePerHour, "MegajoulePerHour", "MegajoulesPerHour", BaseUnits.Undefined); - yield return new (PowerUnit.Megawatt, "Megawatt", "Megawatts", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PowerUnit.MetricHorsepower, "MetricHorsepower", "MetricHorsepower", BaseUnits.Undefined); - yield return new (PowerUnit.Microwatt, "Microwatt", "Microwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second)); - yield return new (PowerUnit.MillijoulePerHour, "MillijoulePerHour", "MillijoulesPerHour", BaseUnits.Undefined); - yield return new (PowerUnit.Milliwatt, "Milliwatt", "Milliwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second)); - yield return new (PowerUnit.Nanowatt, "Nanowatt", "Nanowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second)); - yield return new (PowerUnit.Petawatt, "Petawatt", "Petawatts", BaseUnits.Undefined); - yield return new (PowerUnit.Picowatt, "Picowatt", "Picowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second)); - yield return new (PowerUnit.Terawatt, "Terawatt", "Terawatts", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PowerUnit.TonOfRefrigeration, "TonOfRefrigeration", "TonsOfRefrigeration", BaseUnits.Undefined); + yield return new (PowerUnit.BoilerHorsepower, "BoilerHorsepower", "BoilerHorsepower", BaseUnits.Undefined, + new QuantityValue(2, 19625) + ); + yield return new (PowerUnit.BritishThermalUnitPerHour, "BritishThermalUnitPerHour", "BritishThermalUnitsPerHour", BaseUnits.Undefined, + new QuantityValue(180000000000, 52752792631) + ); + yield return new (PowerUnit.Decawatt, "Decawatt", "Decawatts", BaseUnits.Undefined, + new QuantityValue(1, 10) + ); + yield return new (PowerUnit.Deciwatt, "Deciwatt", "Deciwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Hectogram, time: DurationUnit.Second), + 10 + ); + yield return new (PowerUnit.ElectricalHorsepower, "ElectricalHorsepower", "ElectricalHorsepower", BaseUnits.Undefined, + new QuantityValue(1, 746) + ); + yield return new (PowerUnit.Femtowatt, "Femtowatt", "Femtowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Picogram, time: DurationUnit.Second), + 1000000000000000 + ); + yield return new (PowerUnit.GigajoulePerHour, "GigajoulePerHour", "GigajoulesPerHour", BaseUnits.Undefined, + new QuantityValue(9, 2500000) + ); + yield return new (PowerUnit.Gigawatt, "Gigawatt", "Gigawatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Millisecond), + new QuantityValue(1, 1000000000) + ); + yield return new (PowerUnit.HydraulicHorsepower, "HydraulicHorsepower", "HydraulicHorsepower", BaseUnits.Undefined, + new QuantityValue(50000000000000, 37284993579113511) + ); + yield return new (PowerUnit.JoulePerHour, "JoulePerHour", "JoulesPerHour", BaseUnits.Undefined, + 3600 + ); + yield return new (PowerUnit.KilobritishThermalUnitPerHour, "KilobritishThermalUnitPerHour", "KilobritishThermalUnitsPerHour", BaseUnits.Undefined, + new QuantityValue(180000000, 52752792631) + ); + yield return new (PowerUnit.KilojoulePerHour, "KilojoulePerHour", "KilojoulesPerHour", BaseUnits.Undefined, + new QuantityValue(18, 5) + ); + yield return new (PowerUnit.Kilowatt, "Kilowatt", "Kilowatts", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (PowerUnit.MechanicalHorsepower, "MechanicalHorsepower", "MechanicalHorsepower", BaseUnits.Undefined, + new QuantityValue(200000000000, 149139974303117) + ); + yield return new (PowerUnit.MegabritishThermalUnitPerHour, "MegabritishThermalUnitPerHour", "MegabritishThermalUnitsPerHour", BaseUnits.Undefined, + new QuantityValue(180000, 52752792631) + ); + yield return new (PowerUnit.MegajoulePerHour, "MegajoulePerHour", "MegajoulesPerHour", BaseUnits.Undefined, + new QuantityValue(9, 2500) + ); + yield return new (PowerUnit.Megawatt, "Megawatt", "Megawatts", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (PowerUnit.MetricHorsepower, "MetricHorsepower", "MetricHorsepower", BaseUnits.Undefined, + new QuantityValue(800, 588399) + ); + yield return new (PowerUnit.Microwatt, "Microwatt", "Microwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second), + 1000000 + ); + yield return new (PowerUnit.MillijoulePerHour, "MillijoulePerHour", "MillijoulesPerHour", BaseUnits.Undefined, + 3600000 + ); + yield return new (PowerUnit.Milliwatt, "Milliwatt", "Milliwatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second), + 1000 + ); + yield return new (PowerUnit.Nanowatt, "Nanowatt", "Nanowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second), + 1000000000 + ); + yield return new (PowerUnit.Petawatt, "Petawatt", "Petawatts", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000000) + ); + yield return new (PowerUnit.Picowatt, "Picowatt", "Picowatts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second), + 1000000000000 + ); + yield return new (PowerUnit.Terawatt, "Terawatt", "Terawatts", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000000000) + ); + yield return new (PowerUnit.TonOfRefrigeration, "TonOfRefrigeration", "TonsOfRefrigeration", BaseUnits.Undefined, + new QuantityValue(1000, 3516853) + ); yield return new (PowerUnit.Watt, "Watt", "Watts", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); } } static Power() { - Info = PowerInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(PowerInfo.CreateDefault); } /// @@ -174,7 +223,7 @@ static Power() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Power(double value, PowerUnit unit) + public Power(QuantityValue value, PowerUnit unit) { _value = value; _unit = unit; @@ -188,7 +237,7 @@ public Power(double value, PowerUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Power(double value, UnitSystem unitSystem) + public Power(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -199,7 +248,8 @@ public Power(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -228,10 +278,8 @@ public Power(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public PowerUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -270,210 +318,144 @@ public Power(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BoilerHorsepower => As(PowerUnit.BoilerHorsepower); + public QuantityValue BoilerHorsepower => this.As(PowerUnit.BoilerHorsepower); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BritishThermalUnitsPerHour => As(PowerUnit.BritishThermalUnitPerHour); + public QuantityValue BritishThermalUnitsPerHour => this.As(PowerUnit.BritishThermalUnitPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Decawatts => As(PowerUnit.Decawatt); + public QuantityValue Decawatts => this.As(PowerUnit.Decawatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Deciwatts => As(PowerUnit.Deciwatt); + public QuantityValue Deciwatts => this.As(PowerUnit.Deciwatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ElectricalHorsepower => As(PowerUnit.ElectricalHorsepower); + public QuantityValue ElectricalHorsepower => this.As(PowerUnit.ElectricalHorsepower); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Femtowatts => As(PowerUnit.Femtowatt); + public QuantityValue Femtowatts => this.As(PowerUnit.Femtowatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigajoulesPerHour => As(PowerUnit.GigajoulePerHour); + public QuantityValue GigajoulesPerHour => this.As(PowerUnit.GigajoulePerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigawatts => As(PowerUnit.Gigawatt); + public QuantityValue Gigawatts => this.As(PowerUnit.Gigawatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HydraulicHorsepower => As(PowerUnit.HydraulicHorsepower); + public QuantityValue HydraulicHorsepower => this.As(PowerUnit.HydraulicHorsepower); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double JoulesPerHour => As(PowerUnit.JoulePerHour); + public QuantityValue JoulesPerHour => this.As(PowerUnit.JoulePerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilobritishThermalUnitsPerHour => As(PowerUnit.KilobritishThermalUnitPerHour); + public QuantityValue KilobritishThermalUnitsPerHour => this.As(PowerUnit.KilobritishThermalUnitPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilojoulesPerHour => As(PowerUnit.KilojoulePerHour); + public QuantityValue KilojoulesPerHour => this.As(PowerUnit.KilojoulePerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilowatts => As(PowerUnit.Kilowatt); + public QuantityValue Kilowatts => this.As(PowerUnit.Kilowatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MechanicalHorsepower => As(PowerUnit.MechanicalHorsepower); + public QuantityValue MechanicalHorsepower => this.As(PowerUnit.MechanicalHorsepower); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegabritishThermalUnitsPerHour => As(PowerUnit.MegabritishThermalUnitPerHour); + public QuantityValue MegabritishThermalUnitsPerHour => this.As(PowerUnit.MegabritishThermalUnitPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegajoulesPerHour => As(PowerUnit.MegajoulePerHour); + public QuantityValue MegajoulesPerHour => this.As(PowerUnit.MegajoulePerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megawatts => As(PowerUnit.Megawatt); + public QuantityValue Megawatts => this.As(PowerUnit.Megawatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MetricHorsepower => As(PowerUnit.MetricHorsepower); + public QuantityValue MetricHorsepower => this.As(PowerUnit.MetricHorsepower); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microwatts => As(PowerUnit.Microwatt); + public QuantityValue Microwatts => this.As(PowerUnit.Microwatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillijoulesPerHour => As(PowerUnit.MillijoulePerHour); + public QuantityValue MillijoulesPerHour => this.As(PowerUnit.MillijoulePerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Milliwatts => As(PowerUnit.Milliwatt); + public QuantityValue Milliwatts => this.As(PowerUnit.Milliwatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanowatts => As(PowerUnit.Nanowatt); + public QuantityValue Nanowatts => this.As(PowerUnit.Nanowatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Petawatts => As(PowerUnit.Petawatt); + public QuantityValue Petawatts => this.As(PowerUnit.Petawatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Picowatts => As(PowerUnit.Picowatt); + public QuantityValue Picowatts => this.As(PowerUnit.Picowatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Terawatts => As(PowerUnit.Terawatt); + public QuantityValue Terawatts => this.As(PowerUnit.Terawatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonsOfRefrigeration => As(PowerUnit.TonOfRefrigeration); + public QuantityValue TonsOfRefrigeration => this.As(PowerUnit.TonOfRefrigeration); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Watts => As(PowerUnit.Watt); + public QuantityValue Watts => this.As(PowerUnit.Watt); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: PowerUnit -> BaseUnit - unitConverter.SetConversionFunction(PowerUnit.BoilerHorsepower, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.BritishThermalUnitPerHour, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.Decawatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.Deciwatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.ElectricalHorsepower, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.Femtowatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.GigajoulePerHour, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.Gigawatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.HydraulicHorsepower, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.JoulePerHour, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.KilobritishThermalUnitPerHour, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.KilojoulePerHour, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.Kilowatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.MechanicalHorsepower, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.MegabritishThermalUnitPerHour, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.MegajoulePerHour, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.Megawatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.MetricHorsepower, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.Microwatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.MillijoulePerHour, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.Milliwatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.Nanowatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.Petawatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.Picowatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.Terawatt, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - unitConverter.SetConversionFunction(PowerUnit.TonOfRefrigeration, PowerUnit.Watt, quantity => quantity.ToUnit(PowerUnit.Watt)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Watt, quantity => quantity); - - // Register in unit converter: BaseUnit -> PowerUnit - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.BoilerHorsepower, quantity => quantity.ToUnit(PowerUnit.BoilerHorsepower)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.BritishThermalUnitPerHour, quantity => quantity.ToUnit(PowerUnit.BritishThermalUnitPerHour)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Decawatt, quantity => quantity.ToUnit(PowerUnit.Decawatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Deciwatt, quantity => quantity.ToUnit(PowerUnit.Deciwatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.ElectricalHorsepower, quantity => quantity.ToUnit(PowerUnit.ElectricalHorsepower)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Femtowatt, quantity => quantity.ToUnit(PowerUnit.Femtowatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.GigajoulePerHour, quantity => quantity.ToUnit(PowerUnit.GigajoulePerHour)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Gigawatt, quantity => quantity.ToUnit(PowerUnit.Gigawatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.HydraulicHorsepower, quantity => quantity.ToUnit(PowerUnit.HydraulicHorsepower)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.JoulePerHour, quantity => quantity.ToUnit(PowerUnit.JoulePerHour)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.KilobritishThermalUnitPerHour, quantity => quantity.ToUnit(PowerUnit.KilobritishThermalUnitPerHour)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.KilojoulePerHour, quantity => quantity.ToUnit(PowerUnit.KilojoulePerHour)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Kilowatt, quantity => quantity.ToUnit(PowerUnit.Kilowatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.MechanicalHorsepower, quantity => quantity.ToUnit(PowerUnit.MechanicalHorsepower)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.MegabritishThermalUnitPerHour, quantity => quantity.ToUnit(PowerUnit.MegabritishThermalUnitPerHour)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.MegajoulePerHour, quantity => quantity.ToUnit(PowerUnit.MegajoulePerHour)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Megawatt, quantity => quantity.ToUnit(PowerUnit.Megawatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.MetricHorsepower, quantity => quantity.ToUnit(PowerUnit.MetricHorsepower)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Microwatt, quantity => quantity.ToUnit(PowerUnit.Microwatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.MillijoulePerHour, quantity => quantity.ToUnit(PowerUnit.MillijoulePerHour)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Milliwatt, quantity => quantity.ToUnit(PowerUnit.Milliwatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Nanowatt, quantity => quantity.ToUnit(PowerUnit.Nanowatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Petawatt, quantity => quantity.ToUnit(PowerUnit.Petawatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Picowatt, quantity => quantity.ToUnit(PowerUnit.Picowatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.Terawatt, quantity => quantity.ToUnit(PowerUnit.Terawatt)); - unitConverter.SetConversionFunction(PowerUnit.Watt, PowerUnit.TonOfRefrigeration, quantity => quantity.ToUnit(PowerUnit.TonOfRefrigeration)); - } - /// /// Get unit abbreviation string. /// @@ -502,7 +484,7 @@ public static string GetAbbreviation(PowerUnit unit, IFormatProvider? provider) /// /// Creates a from . /// - public static Power FromBoilerHorsepower(double value) + public static Power FromBoilerHorsepower(QuantityValue value) { return new Power(value, PowerUnit.BoilerHorsepower); } @@ -510,7 +492,7 @@ public static Power FromBoilerHorsepower(double value) /// /// Creates a from . /// - public static Power FromBritishThermalUnitsPerHour(double value) + public static Power FromBritishThermalUnitsPerHour(QuantityValue value) { return new Power(value, PowerUnit.BritishThermalUnitPerHour); } @@ -518,7 +500,7 @@ public static Power FromBritishThermalUnitsPerHour(double value) /// /// Creates a from . /// - public static Power FromDecawatts(double value) + public static Power FromDecawatts(QuantityValue value) { return new Power(value, PowerUnit.Decawatt); } @@ -526,7 +508,7 @@ public static Power FromDecawatts(double value) /// /// Creates a from . /// - public static Power FromDeciwatts(double value) + public static Power FromDeciwatts(QuantityValue value) { return new Power(value, PowerUnit.Deciwatt); } @@ -534,7 +516,7 @@ public static Power FromDeciwatts(double value) /// /// Creates a from . /// - public static Power FromElectricalHorsepower(double value) + public static Power FromElectricalHorsepower(QuantityValue value) { return new Power(value, PowerUnit.ElectricalHorsepower); } @@ -542,7 +524,7 @@ public static Power FromElectricalHorsepower(double value) /// /// Creates a from . /// - public static Power FromFemtowatts(double value) + public static Power FromFemtowatts(QuantityValue value) { return new Power(value, PowerUnit.Femtowatt); } @@ -550,7 +532,7 @@ public static Power FromFemtowatts(double value) /// /// Creates a from . /// - public static Power FromGigajoulesPerHour(double value) + public static Power FromGigajoulesPerHour(QuantityValue value) { return new Power(value, PowerUnit.GigajoulePerHour); } @@ -558,7 +540,7 @@ public static Power FromGigajoulesPerHour(double value) /// /// Creates a from . /// - public static Power FromGigawatts(double value) + public static Power FromGigawatts(QuantityValue value) { return new Power(value, PowerUnit.Gigawatt); } @@ -566,7 +548,7 @@ public static Power FromGigawatts(double value) /// /// Creates a from . /// - public static Power FromHydraulicHorsepower(double value) + public static Power FromHydraulicHorsepower(QuantityValue value) { return new Power(value, PowerUnit.HydraulicHorsepower); } @@ -574,7 +556,7 @@ public static Power FromHydraulicHorsepower(double value) /// /// Creates a from . /// - public static Power FromJoulesPerHour(double value) + public static Power FromJoulesPerHour(QuantityValue value) { return new Power(value, PowerUnit.JoulePerHour); } @@ -582,7 +564,7 @@ public static Power FromJoulesPerHour(double value) /// /// Creates a from . /// - public static Power FromKilobritishThermalUnitsPerHour(double value) + public static Power FromKilobritishThermalUnitsPerHour(QuantityValue value) { return new Power(value, PowerUnit.KilobritishThermalUnitPerHour); } @@ -590,7 +572,7 @@ public static Power FromKilobritishThermalUnitsPerHour(double value) /// /// Creates a from . /// - public static Power FromKilojoulesPerHour(double value) + public static Power FromKilojoulesPerHour(QuantityValue value) { return new Power(value, PowerUnit.KilojoulePerHour); } @@ -598,7 +580,7 @@ public static Power FromKilojoulesPerHour(double value) /// /// Creates a from . /// - public static Power FromKilowatts(double value) + public static Power FromKilowatts(QuantityValue value) { return new Power(value, PowerUnit.Kilowatt); } @@ -606,7 +588,7 @@ public static Power FromKilowatts(double value) /// /// Creates a from . /// - public static Power FromMechanicalHorsepower(double value) + public static Power FromMechanicalHorsepower(QuantityValue value) { return new Power(value, PowerUnit.MechanicalHorsepower); } @@ -614,7 +596,7 @@ public static Power FromMechanicalHorsepower(double value) /// /// Creates a from . /// - public static Power FromMegabritishThermalUnitsPerHour(double value) + public static Power FromMegabritishThermalUnitsPerHour(QuantityValue value) { return new Power(value, PowerUnit.MegabritishThermalUnitPerHour); } @@ -622,7 +604,7 @@ public static Power FromMegabritishThermalUnitsPerHour(double value) /// /// Creates a from . /// - public static Power FromMegajoulesPerHour(double value) + public static Power FromMegajoulesPerHour(QuantityValue value) { return new Power(value, PowerUnit.MegajoulePerHour); } @@ -630,7 +612,7 @@ public static Power FromMegajoulesPerHour(double value) /// /// Creates a from . /// - public static Power FromMegawatts(double value) + public static Power FromMegawatts(QuantityValue value) { return new Power(value, PowerUnit.Megawatt); } @@ -638,7 +620,7 @@ public static Power FromMegawatts(double value) /// /// Creates a from . /// - public static Power FromMetricHorsepower(double value) + public static Power FromMetricHorsepower(QuantityValue value) { return new Power(value, PowerUnit.MetricHorsepower); } @@ -646,7 +628,7 @@ public static Power FromMetricHorsepower(double value) /// /// Creates a from . /// - public static Power FromMicrowatts(double value) + public static Power FromMicrowatts(QuantityValue value) { return new Power(value, PowerUnit.Microwatt); } @@ -654,7 +636,7 @@ public static Power FromMicrowatts(double value) /// /// Creates a from . /// - public static Power FromMillijoulesPerHour(double value) + public static Power FromMillijoulesPerHour(QuantityValue value) { return new Power(value, PowerUnit.MillijoulePerHour); } @@ -662,7 +644,7 @@ public static Power FromMillijoulesPerHour(double value) /// /// Creates a from . /// - public static Power FromMilliwatts(double value) + public static Power FromMilliwatts(QuantityValue value) { return new Power(value, PowerUnit.Milliwatt); } @@ -670,7 +652,7 @@ public static Power FromMilliwatts(double value) /// /// Creates a from . /// - public static Power FromNanowatts(double value) + public static Power FromNanowatts(QuantityValue value) { return new Power(value, PowerUnit.Nanowatt); } @@ -678,7 +660,7 @@ public static Power FromNanowatts(double value) /// /// Creates a from . /// - public static Power FromPetawatts(double value) + public static Power FromPetawatts(QuantityValue value) { return new Power(value, PowerUnit.Petawatt); } @@ -686,7 +668,7 @@ public static Power FromPetawatts(double value) /// /// Creates a from . /// - public static Power FromPicowatts(double value) + public static Power FromPicowatts(QuantityValue value) { return new Power(value, PowerUnit.Picowatt); } @@ -694,7 +676,7 @@ public static Power FromPicowatts(double value) /// /// Creates a from . /// - public static Power FromTerawatts(double value) + public static Power FromTerawatts(QuantityValue value) { return new Power(value, PowerUnit.Terawatt); } @@ -702,7 +684,7 @@ public static Power FromTerawatts(double value) /// /// Creates a from . /// - public static Power FromTonsOfRefrigeration(double value) + public static Power FromTonsOfRefrigeration(QuantityValue value) { return new Power(value, PowerUnit.TonOfRefrigeration); } @@ -710,7 +692,7 @@ public static Power FromTonsOfRefrigeration(double value) /// /// Creates a from . /// - public static Power FromWatts(double value) + public static Power FromWatts(QuantityValue value) { return new Power(value, PowerUnit.Watt); } @@ -721,7 +703,7 @@ public static Power FromWatts(double value) /// Value to convert from. /// Unit to convert from. /// Power unit value. - public static Power From(double value, PowerUnit fromUnit) + public static Power From(QuantityValue value, PowerUnit fromUnit) { return new Power(value, fromUnit); } @@ -782,10 +764,7 @@ public static Power Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Power Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -813,11 +792,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Power result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Power result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -838,7 +813,7 @@ public static PowerUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -849,7 +824,7 @@ public static PowerUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out PowerUnit unit) { return TryParseUnit(str, null, out unit); @@ -864,7 +839,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out PowerUnit un /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out PowerUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -883,35 +858,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Power operator +(Power left, Power right) { - return new Power(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Power(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Power operator -(Power left, Power right) { - return new Power(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Power(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static Power operator *(double 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, double 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, double 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; } @@ -1011,97 +986,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Power left, Power right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Power left, Power right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Power left, Power right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Power left, Power right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Power other, Power tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Power left, Power right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Power other, Power tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Power left, Power right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Power other, Power tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Power otherQuantity)) + if (obj is not Power otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Power other, Power tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Power other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Power. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Power), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Power otherQuantity)) throw new ArgumentException("Expected type Power.", nameof(obj)); + if (obj is not Power otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1113,198 +1073,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Power other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PowerUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Power to another Power with the unit representation . - /// - /// The unit to convert to. - /// A Power with the specified unit. - public Power ToUnit(PowerUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Power with the specified unit. - public Power ToUnit(PowerUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Power), Unit, typeof(Power), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Power)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(PowerUnit unit, [NotNullWhen(true)] out Power? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Power? convertedOrNull = (Unit, unit) switch - { - // PowerUnit -> BaseUnit - (PowerUnit.BoilerHorsepower, PowerUnit.Watt) => new Power(_value * 9812.5, PowerUnit.Watt), - (PowerUnit.BritishThermalUnitPerHour, PowerUnit.Watt) => new Power(_value * 1055.05585262 / 3600, PowerUnit.Watt), - (PowerUnit.Decawatt, PowerUnit.Watt) => new Power((_value) * 1e1d, PowerUnit.Watt), - (PowerUnit.Deciwatt, PowerUnit.Watt) => new Power((_value) * 1e-1d, PowerUnit.Watt), - (PowerUnit.ElectricalHorsepower, PowerUnit.Watt) => new Power(_value * 746, PowerUnit.Watt), - (PowerUnit.Femtowatt, PowerUnit.Watt) => new Power((_value) * 1e-15d, PowerUnit.Watt), - (PowerUnit.GigajoulePerHour, PowerUnit.Watt) => new Power((_value / 3600) * 1e9d, PowerUnit.Watt), - (PowerUnit.Gigawatt, PowerUnit.Watt) => new Power((_value) * 1e9d, PowerUnit.Watt), - (PowerUnit.HydraulicHorsepower, PowerUnit.Watt) => new Power(_value * 745.69987158227022, PowerUnit.Watt), - (PowerUnit.JoulePerHour, PowerUnit.Watt) => new Power(_value / 3600, PowerUnit.Watt), - (PowerUnit.KilobritishThermalUnitPerHour, PowerUnit.Watt) => new Power((_value * 1055.05585262 / 3600) * 1e3d, PowerUnit.Watt), - (PowerUnit.KilojoulePerHour, PowerUnit.Watt) => new Power((_value / 3600) * 1e3d, PowerUnit.Watt), - (PowerUnit.Kilowatt, PowerUnit.Watt) => new Power((_value) * 1e3d, PowerUnit.Watt), - (PowerUnit.MechanicalHorsepower, PowerUnit.Watt) => new Power(_value * 76.0402249 * 9.80665, PowerUnit.Watt), - (PowerUnit.MegabritishThermalUnitPerHour, PowerUnit.Watt) => new Power((_value * 1055.05585262 / 3600) * 1e6d, PowerUnit.Watt), - (PowerUnit.MegajoulePerHour, PowerUnit.Watt) => new Power((_value / 3600) * 1e6d, PowerUnit.Watt), - (PowerUnit.Megawatt, PowerUnit.Watt) => new Power((_value) * 1e6d, PowerUnit.Watt), - (PowerUnit.MetricHorsepower, PowerUnit.Watt) => new Power(_value * 75 * 9.80665, PowerUnit.Watt), - (PowerUnit.Microwatt, PowerUnit.Watt) => new Power((_value) * 1e-6d, PowerUnit.Watt), - (PowerUnit.MillijoulePerHour, PowerUnit.Watt) => new Power((_value / 3600) * 1e-3d, PowerUnit.Watt), - (PowerUnit.Milliwatt, PowerUnit.Watt) => new Power((_value) * 1e-3d, PowerUnit.Watt), - (PowerUnit.Nanowatt, PowerUnit.Watt) => new Power((_value) * 1e-9d, PowerUnit.Watt), - (PowerUnit.Petawatt, PowerUnit.Watt) => new Power((_value) * 1e15d, PowerUnit.Watt), - (PowerUnit.Picowatt, PowerUnit.Watt) => new Power((_value) * 1e-12d, PowerUnit.Watt), - (PowerUnit.Terawatt, PowerUnit.Watt) => new Power((_value) * 1e12d, PowerUnit.Watt), - (PowerUnit.TonOfRefrigeration, PowerUnit.Watt) => new Power(_value * 3516.853, PowerUnit.Watt), - - // BaseUnit -> PowerUnit - (PowerUnit.Watt, PowerUnit.BoilerHorsepower) => new Power(_value / 9812.5, PowerUnit.BoilerHorsepower), - (PowerUnit.Watt, PowerUnit.BritishThermalUnitPerHour) => new Power(_value * 3600 / 1055.05585262, PowerUnit.BritishThermalUnitPerHour), - (PowerUnit.Watt, PowerUnit.Decawatt) => new Power((_value) / 1e1d, PowerUnit.Decawatt), - (PowerUnit.Watt, PowerUnit.Deciwatt) => new Power((_value) / 1e-1d, PowerUnit.Deciwatt), - (PowerUnit.Watt, PowerUnit.ElectricalHorsepower) => new Power(_value / 746, PowerUnit.ElectricalHorsepower), - (PowerUnit.Watt, PowerUnit.Femtowatt) => new Power((_value) / 1e-15d, PowerUnit.Femtowatt), - (PowerUnit.Watt, PowerUnit.GigajoulePerHour) => new Power((_value * 3600) / 1e9d, PowerUnit.GigajoulePerHour), - (PowerUnit.Watt, PowerUnit.Gigawatt) => new Power((_value) / 1e9d, PowerUnit.Gigawatt), - (PowerUnit.Watt, PowerUnit.HydraulicHorsepower) => new Power(_value / 745.69987158227022, PowerUnit.HydraulicHorsepower), - (PowerUnit.Watt, PowerUnit.JoulePerHour) => new Power(_value * 3600, PowerUnit.JoulePerHour), - (PowerUnit.Watt, PowerUnit.KilobritishThermalUnitPerHour) => new Power((_value * 3600 / 1055.05585262) / 1e3d, PowerUnit.KilobritishThermalUnitPerHour), - (PowerUnit.Watt, PowerUnit.KilojoulePerHour) => new Power((_value * 3600) / 1e3d, PowerUnit.KilojoulePerHour), - (PowerUnit.Watt, PowerUnit.Kilowatt) => new Power((_value) / 1e3d, PowerUnit.Kilowatt), - (PowerUnit.Watt, PowerUnit.MechanicalHorsepower) => new Power(_value / (76.0402249 * 9.80665), PowerUnit.MechanicalHorsepower), - (PowerUnit.Watt, PowerUnit.MegabritishThermalUnitPerHour) => new Power((_value * 3600 / 1055.05585262) / 1e6d, PowerUnit.MegabritishThermalUnitPerHour), - (PowerUnit.Watt, PowerUnit.MegajoulePerHour) => new Power((_value * 3600) / 1e6d, PowerUnit.MegajoulePerHour), - (PowerUnit.Watt, PowerUnit.Megawatt) => new Power((_value) / 1e6d, PowerUnit.Megawatt), - (PowerUnit.Watt, PowerUnit.MetricHorsepower) => new Power(_value / (75 * 9.80665), PowerUnit.MetricHorsepower), - (PowerUnit.Watt, PowerUnit.Microwatt) => new Power((_value) / 1e-6d, PowerUnit.Microwatt), - (PowerUnit.Watt, PowerUnit.MillijoulePerHour) => new Power((_value * 3600) / 1e-3d, PowerUnit.MillijoulePerHour), - (PowerUnit.Watt, PowerUnit.Milliwatt) => new Power((_value) / 1e-3d, PowerUnit.Milliwatt), - (PowerUnit.Watt, PowerUnit.Nanowatt) => new Power((_value) / 1e-9d, PowerUnit.Nanowatt), - (PowerUnit.Watt, PowerUnit.Petawatt) => new Power((_value) / 1e15d, PowerUnit.Petawatt), - (PowerUnit.Watt, PowerUnit.Picowatt) => new Power((_value) / 1e-12d, PowerUnit.Picowatt), - (PowerUnit.Watt, PowerUnit.Terawatt) => new Power((_value) / 1e12d, PowerUnit.Terawatt), - (PowerUnit.Watt, PowerUnit.TonOfRefrigeration) => new Power(_value / 3516.853, PowerUnit.TonOfRefrigeration), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Power ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not PowerUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(PowerUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(PowerUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1319,7 +1105,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs b/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs index 69c0b71d3b..d71b71ba88 100644 --- a/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PowerDensity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// The amount of power in a volume. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct PowerDensity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly PowerDensityUnit? _unit; /// @@ -101,7 +100,7 @@ public static PowerDensityInfo CreateDefault(Func - /// The for is [T^-3][L^-1][M]. + /// The for is T^-3L^-1M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); @@ -116,58 +115,142 @@ public static PowerDensityInfo CreateDefault(FuncAn of representing the default unit mappings for PowerDensity. public static IEnumerable> GetDefaultMappings() { - yield return new (PowerDensityUnit.DecawattPerCubicFoot, "DecawattPerCubicFoot", "DecawattsPerCubicFoot", BaseUnits.Undefined); - yield return new (PowerDensityUnit.DecawattPerCubicInch, "DecawattPerCubicInch", "DecawattsPerCubicInch", BaseUnits.Undefined); - yield return new (PowerDensityUnit.DecawattPerCubicMeter, "DecawattPerCubicMeter", "DecawattsPerCubicMeter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PowerDensityUnit.DecawattPerLiter, "DecawattPerLiter", "DecawattsPerLiter", BaseUnits.Undefined); - yield return new (PowerDensityUnit.DeciwattPerCubicFoot, "DeciwattPerCubicFoot", "DeciwattsPerCubicFoot", BaseUnits.Undefined); - yield return new (PowerDensityUnit.DeciwattPerCubicInch, "DeciwattPerCubicInch", "DeciwattsPerCubicInch", BaseUnits.Undefined); - yield return new (PowerDensityUnit.DeciwattPerCubicMeter, "DeciwattPerCubicMeter", "DeciwattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Hectogram, time: DurationUnit.Second)); - yield return new (PowerDensityUnit.DeciwattPerLiter, "DeciwattPerLiter", "DeciwattsPerLiter", BaseUnits.Undefined); - yield return new (PowerDensityUnit.GigawattPerCubicFoot, "GigawattPerCubicFoot", "GigawattsPerCubicFoot", BaseUnits.Undefined); - yield return new (PowerDensityUnit.GigawattPerCubicInch, "GigawattPerCubicInch", "GigawattsPerCubicInch", BaseUnits.Undefined); - yield return new (PowerDensityUnit.GigawattPerCubicMeter, "GigawattPerCubicMeter", "GigawattsPerCubicMeter", new BaseUnits(length: LengthUnit.Nanometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PowerDensityUnit.GigawattPerLiter, "GigawattPerLiter", "GigawattsPerLiter", BaseUnits.Undefined); - yield return new (PowerDensityUnit.KilowattPerCubicFoot, "KilowattPerCubicFoot", "KilowattsPerCubicFoot", BaseUnits.Undefined); - yield return new (PowerDensityUnit.KilowattPerCubicInch, "KilowattPerCubicInch", "KilowattsPerCubicInch", BaseUnits.Undefined); - yield return new (PowerDensityUnit.KilowattPerCubicMeter, "KilowattPerCubicMeter", "KilowattsPerCubicMeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PowerDensityUnit.KilowattPerLiter, "KilowattPerLiter", "KilowattsPerLiter", BaseUnits.Undefined); - yield return new (PowerDensityUnit.MegawattPerCubicFoot, "MegawattPerCubicFoot", "MegawattsPerCubicFoot", BaseUnits.Undefined); - yield return new (PowerDensityUnit.MegawattPerCubicInch, "MegawattPerCubicInch", "MegawattsPerCubicInch", BaseUnits.Undefined); - yield return new (PowerDensityUnit.MegawattPerCubicMeter, "MegawattPerCubicMeter", "MegawattsPerCubicMeter", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PowerDensityUnit.MegawattPerLiter, "MegawattPerLiter", "MegawattsPerLiter", BaseUnits.Undefined); - yield return new (PowerDensityUnit.MicrowattPerCubicFoot, "MicrowattPerCubicFoot", "MicrowattsPerCubicFoot", BaseUnits.Undefined); - yield return new (PowerDensityUnit.MicrowattPerCubicInch, "MicrowattPerCubicInch", "MicrowattsPerCubicInch", BaseUnits.Undefined); - yield return new (PowerDensityUnit.MicrowattPerCubicMeter, "MicrowattPerCubicMeter", "MicrowattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second)); - yield return new (PowerDensityUnit.MicrowattPerLiter, "MicrowattPerLiter", "MicrowattsPerLiter", BaseUnits.Undefined); - yield return new (PowerDensityUnit.MilliwattPerCubicFoot, "MilliwattPerCubicFoot", "MilliwattsPerCubicFoot", BaseUnits.Undefined); - yield return new (PowerDensityUnit.MilliwattPerCubicInch, "MilliwattPerCubicInch", "MilliwattsPerCubicInch", BaseUnits.Undefined); - yield return new (PowerDensityUnit.MilliwattPerCubicMeter, "MilliwattPerCubicMeter", "MilliwattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second)); - yield return new (PowerDensityUnit.MilliwattPerLiter, "MilliwattPerLiter", "MilliwattsPerLiter", BaseUnits.Undefined); - yield return new (PowerDensityUnit.NanowattPerCubicFoot, "NanowattPerCubicFoot", "NanowattsPerCubicFoot", BaseUnits.Undefined); - yield return new (PowerDensityUnit.NanowattPerCubicInch, "NanowattPerCubicInch", "NanowattsPerCubicInch", BaseUnits.Undefined); - yield return new (PowerDensityUnit.NanowattPerCubicMeter, "NanowattPerCubicMeter", "NanowattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second)); - yield return new (PowerDensityUnit.NanowattPerLiter, "NanowattPerLiter", "NanowattsPerLiter", BaseUnits.Undefined); - yield return new (PowerDensityUnit.PicowattPerCubicFoot, "PicowattPerCubicFoot", "PicowattsPerCubicFoot", BaseUnits.Undefined); - yield return new (PowerDensityUnit.PicowattPerCubicInch, "PicowattPerCubicInch", "PicowattsPerCubicInch", BaseUnits.Undefined); - yield return new (PowerDensityUnit.PicowattPerCubicMeter, "PicowattPerCubicMeter", "PicowattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second)); - yield return new (PowerDensityUnit.PicowattPerLiter, "PicowattPerLiter", "PicowattsPerLiter", BaseUnits.Undefined); - yield return new (PowerDensityUnit.TerawattPerCubicFoot, "TerawattPerCubicFoot", "TerawattsPerCubicFoot", BaseUnits.Undefined); - yield return new (PowerDensityUnit.TerawattPerCubicInch, "TerawattPerCubicInch", "TerawattsPerCubicInch", BaseUnits.Undefined); - yield return new (PowerDensityUnit.TerawattPerCubicMeter, "TerawattPerCubicMeter", "TerawattsPerCubicMeter", new BaseUnits(length: LengthUnit.Picometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PowerDensityUnit.TerawattPerLiter, "TerawattPerLiter", "TerawattsPerLiter", BaseUnits.Undefined); - yield return new (PowerDensityUnit.WattPerCubicFoot, "WattPerCubicFoot", "WattsPerCubicFoot", BaseUnits.Undefined); - yield return new (PowerDensityUnit.WattPerCubicInch, "WattPerCubicInch", "WattsPerCubicInch", BaseUnits.Undefined); + yield return new (PowerDensityUnit.DecawattPerCubicFoot, "DecawattPerCubicFoot", "DecawattsPerCubicFoot", BaseUnits.Undefined, + new QuantityValue(55306341, 19531250000) + ); + yield return new (PowerDensityUnit.DecawattPerCubicInch, "DecawattPerCubicInch", "DecawattsPerCubicInch", BaseUnits.Undefined, + new QuantityValue(2048383, 1250000000000) + ); + yield return new (PowerDensityUnit.DecawattPerCubicMeter, "DecawattPerCubicMeter", "DecawattsPerCubicMeter", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 10) + ); + yield return new (PowerDensityUnit.DecawattPerLiter, "DecawattPerLiter", "DecawattsPerLiter", BaseUnits.Undefined, + new QuantityValue(1, 10000) + ); + yield return new (PowerDensityUnit.DeciwattPerCubicFoot, "DeciwattPerCubicFoot", "DeciwattsPerCubicFoot", BaseUnits.Undefined, + new QuantityValue(55306341, 195312500) + ); + yield return new (PowerDensityUnit.DeciwattPerCubicInch, "DeciwattPerCubicInch", "DeciwattsPerCubicInch", BaseUnits.Undefined, + new QuantityValue(2048383, 12500000000) + ); + yield return new (PowerDensityUnit.DeciwattPerCubicMeter, "DeciwattPerCubicMeter", "DeciwattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Hectogram, time: DurationUnit.Second), + 10 + ); + yield return new (PowerDensityUnit.DeciwattPerLiter, "DeciwattPerLiter", "DeciwattsPerLiter", BaseUnits.Undefined, + new QuantityValue(1, 100) + ); + yield return new (PowerDensityUnit.GigawattPerCubicFoot, "GigawattPerCubicFoot", "GigawattsPerCubicFoot", BaseUnits.Undefined, + new QuantityValue(55306341, 1953125000000000000) + ); + yield return new (PowerDensityUnit.GigawattPerCubicInch, "GigawattPerCubicInch", "GigawattsPerCubicInch", BaseUnits.Undefined, + new QuantityValue(2048383, new BigInteger(125) * QuantityValue.PowerOfTen(18)) + ); + yield return new (PowerDensityUnit.GigawattPerCubicMeter, "GigawattPerCubicMeter", "GigawattsPerCubicMeter", new BaseUnits(length: LengthUnit.Nanometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000000) + ); + yield return new (PowerDensityUnit.GigawattPerLiter, "GigawattPerLiter", "GigawattsPerLiter", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000) + ); + yield return new (PowerDensityUnit.KilowattPerCubicFoot, "KilowattPerCubicFoot", "KilowattsPerCubicFoot", BaseUnits.Undefined, + new QuantityValue(55306341, 1953125000000) + ); + yield return new (PowerDensityUnit.KilowattPerCubicInch, "KilowattPerCubicInch", "KilowattsPerCubicInch", BaseUnits.Undefined, + new QuantityValue(2048383, 125000000000000) + ); + yield return new (PowerDensityUnit.KilowattPerCubicMeter, "KilowattPerCubicMeter", "KilowattsPerCubicMeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000) + ); + yield return new (PowerDensityUnit.KilowattPerLiter, "KilowattPerLiter", "KilowattsPerLiter", BaseUnits.Undefined, + new QuantityValue(1, 1000000) + ); + yield return new (PowerDensityUnit.MegawattPerCubicFoot, "MegawattPerCubicFoot", "MegawattsPerCubicFoot", BaseUnits.Undefined, + new QuantityValue(55306341, 1953125000000000) + ); + yield return new (PowerDensityUnit.MegawattPerCubicInch, "MegawattPerCubicInch", "MegawattsPerCubicInch", BaseUnits.Undefined, + new QuantityValue(2048383, 125000000000000000) + ); + yield return new (PowerDensityUnit.MegawattPerCubicMeter, "MegawattPerCubicMeter", "MegawattsPerCubicMeter", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (PowerDensityUnit.MegawattPerLiter, "MegawattPerLiter", "MegawattsPerLiter", BaseUnits.Undefined, + new QuantityValue(1, 1000000000) + ); + yield return new (PowerDensityUnit.MicrowattPerCubicFoot, "MicrowattPerCubicFoot", "MicrowattsPerCubicFoot", BaseUnits.Undefined, + new QuantityValue(442450728, 15625) + ); + yield return new (PowerDensityUnit.MicrowattPerCubicInch, "MicrowattPerCubicInch", "MicrowattsPerCubicInch", BaseUnits.Undefined, + new QuantityValue(2048383, 125000) + ); + yield return new (PowerDensityUnit.MicrowattPerCubicMeter, "MicrowattPerCubicMeter", "MicrowattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second), + 1000000 + ); + yield return new (PowerDensityUnit.MicrowattPerLiter, "MicrowattPerLiter", "MicrowattsPerLiter", BaseUnits.Undefined, + 1000 + ); + yield return new (PowerDensityUnit.MilliwattPerCubicFoot, "MilliwattPerCubicFoot", "MilliwattsPerCubicFoot", BaseUnits.Undefined, + new QuantityValue(55306341, 1953125) + ); + yield return new (PowerDensityUnit.MilliwattPerCubicInch, "MilliwattPerCubicInch", "MilliwattsPerCubicInch", BaseUnits.Undefined, + new QuantityValue(2048383, 125000000) + ); + yield return new (PowerDensityUnit.MilliwattPerCubicMeter, "MilliwattPerCubicMeter", "MilliwattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second), + 1000 + ); + yield return new (PowerDensityUnit.MilliwattPerLiter, "MilliwattPerLiter", "MilliwattsPerLiter", BaseUnits.Undefined, + 1 + ); + yield return new (PowerDensityUnit.NanowattPerCubicFoot, "NanowattPerCubicFoot", "NanowattsPerCubicFoot", BaseUnits.Undefined, + new QuantityValue(3539605824, 125) + ); + yield return new (PowerDensityUnit.NanowattPerCubicInch, "NanowattPerCubicInch", "NanowattsPerCubicInch", BaseUnits.Undefined, + new QuantityValue(2048383, 125) + ); + yield return new (PowerDensityUnit.NanowattPerCubicMeter, "NanowattPerCubicMeter", "NanowattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Microgram, time: DurationUnit.Second), + 1000000000 + ); + yield return new (PowerDensityUnit.NanowattPerLiter, "NanowattPerLiter", "NanowattsPerLiter", BaseUnits.Undefined, + 1000000 + ); + yield return new (PowerDensityUnit.PicowattPerCubicFoot, "PicowattPerCubicFoot", "PicowattsPerCubicFoot", BaseUnits.Undefined, + 28316846592 + ); + yield return new (PowerDensityUnit.PicowattPerCubicInch, "PicowattPerCubicInch", "PicowattsPerCubicInch", BaseUnits.Undefined, + 16387064 + ); + yield return new (PowerDensityUnit.PicowattPerCubicMeter, "PicowattPerCubicMeter", "PicowattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Nanogram, time: DurationUnit.Second), + 1000000000000 + ); + yield return new (PowerDensityUnit.PicowattPerLiter, "PicowattPerLiter", "PicowattsPerLiter", BaseUnits.Undefined, + 1000000000 + ); + yield return new (PowerDensityUnit.TerawattPerCubicFoot, "TerawattPerCubicFoot", "TerawattsPerCubicFoot", BaseUnits.Undefined, + new QuantityValue(55306341, new BigInteger(1953125) * QuantityValue.PowerOfTen(15)) + ); + yield return new (PowerDensityUnit.TerawattPerCubicInch, "TerawattPerCubicInch", "TerawattsPerCubicInch", BaseUnits.Undefined, + new QuantityValue(2048383, new BigInteger(125) * QuantityValue.PowerOfTen(21)) + ); + yield return new (PowerDensityUnit.TerawattPerCubicMeter, "TerawattPerCubicMeter", "TerawattsPerCubicMeter", new BaseUnits(length: LengthUnit.Picometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000000000) + ); + yield return new (PowerDensityUnit.TerawattPerLiter, "TerawattPerLiter", "TerawattsPerLiter", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000000) + ); + yield return new (PowerDensityUnit.WattPerCubicFoot, "WattPerCubicFoot", "WattsPerCubicFoot", BaseUnits.Undefined, + new QuantityValue(55306341, 1953125000) + ); + yield return new (PowerDensityUnit.WattPerCubicInch, "WattPerCubicInch", "WattsPerCubicInch", BaseUnits.Undefined, + new QuantityValue(2048383, 125000000000) + ); yield return new (PowerDensityUnit.WattPerCubicMeter, "WattPerCubicMeter", "WattsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PowerDensityUnit.WattPerLiter, "WattPerLiter", "WattsPerLiter", BaseUnits.Undefined); + yield return new (PowerDensityUnit.WattPerLiter, "WattPerLiter", "WattsPerLiter", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); } } static PowerDensity() { - Info = PowerDensityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(PowerDensityInfo.CreateDefault); } /// @@ -175,7 +258,7 @@ static PowerDensity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public PowerDensity(double value, PowerDensityUnit unit) + public PowerDensity(QuantityValue value, PowerDensityUnit unit) { _value = value; _unit = unit; @@ -189,7 +272,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -200,7 +283,8 @@ public PowerDensity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -229,10 +313,8 @@ public PowerDensity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public PowerDensityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -271,329 +353,229 @@ public PowerDensity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecawattsPerCubicFoot => As(PowerDensityUnit.DecawattPerCubicFoot); + public QuantityValue DecawattsPerCubicFoot => this.As(PowerDensityUnit.DecawattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecawattsPerCubicInch => As(PowerDensityUnit.DecawattPerCubicInch); + public QuantityValue DecawattsPerCubicInch => this.As(PowerDensityUnit.DecawattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecawattsPerCubicMeter => As(PowerDensityUnit.DecawattPerCubicMeter); + public QuantityValue DecawattsPerCubicMeter => this.As(PowerDensityUnit.DecawattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecawattsPerLiter => As(PowerDensityUnit.DecawattPerLiter); + public QuantityValue DecawattsPerLiter => this.As(PowerDensityUnit.DecawattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DeciwattsPerCubicFoot => As(PowerDensityUnit.DeciwattPerCubicFoot); + public QuantityValue DeciwattsPerCubicFoot => this.As(PowerDensityUnit.DeciwattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DeciwattsPerCubicInch => As(PowerDensityUnit.DeciwattPerCubicInch); + public QuantityValue DeciwattsPerCubicInch => this.As(PowerDensityUnit.DeciwattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DeciwattsPerCubicMeter => As(PowerDensityUnit.DeciwattPerCubicMeter); + public QuantityValue DeciwattsPerCubicMeter => this.As(PowerDensityUnit.DeciwattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DeciwattsPerLiter => As(PowerDensityUnit.DeciwattPerLiter); + public QuantityValue DeciwattsPerLiter => this.As(PowerDensityUnit.DeciwattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigawattsPerCubicFoot => As(PowerDensityUnit.GigawattPerCubicFoot); + public QuantityValue GigawattsPerCubicFoot => this.As(PowerDensityUnit.GigawattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigawattsPerCubicInch => As(PowerDensityUnit.GigawattPerCubicInch); + public QuantityValue GigawattsPerCubicInch => this.As(PowerDensityUnit.GigawattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigawattsPerCubicMeter => As(PowerDensityUnit.GigawattPerCubicMeter); + public QuantityValue GigawattsPerCubicMeter => this.As(PowerDensityUnit.GigawattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigawattsPerLiter => As(PowerDensityUnit.GigawattPerLiter); + public QuantityValue GigawattsPerLiter => this.As(PowerDensityUnit.GigawattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattsPerCubicFoot => As(PowerDensityUnit.KilowattPerCubicFoot); + public QuantityValue KilowattsPerCubicFoot => this.As(PowerDensityUnit.KilowattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattsPerCubicInch => As(PowerDensityUnit.KilowattPerCubicInch); + public QuantityValue KilowattsPerCubicInch => this.As(PowerDensityUnit.KilowattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattsPerCubicMeter => As(PowerDensityUnit.KilowattPerCubicMeter); + public QuantityValue KilowattsPerCubicMeter => this.As(PowerDensityUnit.KilowattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattsPerLiter => As(PowerDensityUnit.KilowattPerLiter); + public QuantityValue KilowattsPerLiter => this.As(PowerDensityUnit.KilowattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattsPerCubicFoot => As(PowerDensityUnit.MegawattPerCubicFoot); + public QuantityValue MegawattsPerCubicFoot => this.As(PowerDensityUnit.MegawattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattsPerCubicInch => As(PowerDensityUnit.MegawattPerCubicInch); + public QuantityValue MegawattsPerCubicInch => this.As(PowerDensityUnit.MegawattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattsPerCubicMeter => As(PowerDensityUnit.MegawattPerCubicMeter); + public QuantityValue MegawattsPerCubicMeter => this.As(PowerDensityUnit.MegawattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattsPerLiter => As(PowerDensityUnit.MegawattPerLiter); + public QuantityValue MegawattsPerLiter => this.As(PowerDensityUnit.MegawattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrowattsPerCubicFoot => As(PowerDensityUnit.MicrowattPerCubicFoot); + public QuantityValue MicrowattsPerCubicFoot => this.As(PowerDensityUnit.MicrowattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrowattsPerCubicInch => As(PowerDensityUnit.MicrowattPerCubicInch); + public QuantityValue MicrowattsPerCubicInch => this.As(PowerDensityUnit.MicrowattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrowattsPerCubicMeter => As(PowerDensityUnit.MicrowattPerCubicMeter); + public QuantityValue MicrowattsPerCubicMeter => this.As(PowerDensityUnit.MicrowattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrowattsPerLiter => As(PowerDensityUnit.MicrowattPerLiter); + public QuantityValue MicrowattsPerLiter => this.As(PowerDensityUnit.MicrowattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliwattsPerCubicFoot => As(PowerDensityUnit.MilliwattPerCubicFoot); + public QuantityValue MilliwattsPerCubicFoot => this.As(PowerDensityUnit.MilliwattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliwattsPerCubicInch => As(PowerDensityUnit.MilliwattPerCubicInch); + public QuantityValue MilliwattsPerCubicInch => this.As(PowerDensityUnit.MilliwattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliwattsPerCubicMeter => As(PowerDensityUnit.MilliwattPerCubicMeter); + public QuantityValue MilliwattsPerCubicMeter => this.As(PowerDensityUnit.MilliwattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliwattsPerLiter => As(PowerDensityUnit.MilliwattPerLiter); + public QuantityValue MilliwattsPerLiter => this.As(PowerDensityUnit.MilliwattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanowattsPerCubicFoot => As(PowerDensityUnit.NanowattPerCubicFoot); + public QuantityValue NanowattsPerCubicFoot => this.As(PowerDensityUnit.NanowattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanowattsPerCubicInch => As(PowerDensityUnit.NanowattPerCubicInch); + public QuantityValue NanowattsPerCubicInch => this.As(PowerDensityUnit.NanowattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanowattsPerCubicMeter => As(PowerDensityUnit.NanowattPerCubicMeter); + public QuantityValue NanowattsPerCubicMeter => this.As(PowerDensityUnit.NanowattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanowattsPerLiter => As(PowerDensityUnit.NanowattPerLiter); + public QuantityValue NanowattsPerLiter => this.As(PowerDensityUnit.NanowattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicowattsPerCubicFoot => As(PowerDensityUnit.PicowattPerCubicFoot); + public QuantityValue PicowattsPerCubicFoot => this.As(PowerDensityUnit.PicowattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicowattsPerCubicInch => As(PowerDensityUnit.PicowattPerCubicInch); + public QuantityValue PicowattsPerCubicInch => this.As(PowerDensityUnit.PicowattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicowattsPerCubicMeter => As(PowerDensityUnit.PicowattPerCubicMeter); + public QuantityValue PicowattsPerCubicMeter => this.As(PowerDensityUnit.PicowattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicowattsPerLiter => As(PowerDensityUnit.PicowattPerLiter); + public QuantityValue PicowattsPerLiter => this.As(PowerDensityUnit.PicowattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TerawattsPerCubicFoot => As(PowerDensityUnit.TerawattPerCubicFoot); + public QuantityValue TerawattsPerCubicFoot => this.As(PowerDensityUnit.TerawattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TerawattsPerCubicInch => As(PowerDensityUnit.TerawattPerCubicInch); + public QuantityValue TerawattsPerCubicInch => this.As(PowerDensityUnit.TerawattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TerawattsPerCubicMeter => As(PowerDensityUnit.TerawattPerCubicMeter); + public QuantityValue TerawattsPerCubicMeter => this.As(PowerDensityUnit.TerawattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TerawattsPerLiter => As(PowerDensityUnit.TerawattPerLiter); + public QuantityValue TerawattsPerLiter => this.As(PowerDensityUnit.TerawattPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattsPerCubicFoot => As(PowerDensityUnit.WattPerCubicFoot); + public QuantityValue WattsPerCubicFoot => this.As(PowerDensityUnit.WattPerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattsPerCubicInch => As(PowerDensityUnit.WattPerCubicInch); + public QuantityValue WattsPerCubicInch => this.As(PowerDensityUnit.WattPerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattsPerCubicMeter => As(PowerDensityUnit.WattPerCubicMeter); + public QuantityValue WattsPerCubicMeter => this.As(PowerDensityUnit.WattPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattsPerLiter => As(PowerDensityUnit.WattPerLiter); + public QuantityValue WattsPerLiter => this.As(PowerDensityUnit.WattPerLiter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: PowerDensityUnit -> BaseUnit - unitConverter.SetConversionFunction(PowerDensityUnit.DecawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.DecawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.DecawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.DecawattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.DeciwattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.DeciwattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.DeciwattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.DeciwattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.GigawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.GigawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.GigawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.GigawattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.KilowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.KilowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.KilowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.KilowattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.MegawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.MegawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.MegawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.MegawattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.MicrowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.MicrowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.MicrowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.MicrowattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.MilliwattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.MilliwattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.MilliwattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.MilliwattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.NanowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.NanowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.NanowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.NanowattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.PicowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.PicowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.PicowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.PicowattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.TerawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.TerawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.TerawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.TerawattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicInch, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerLiter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> PowerDensityUnit - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.DecawattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.DecawattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.DecawattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.DecawattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.DeciwattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.DeciwattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.DeciwattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.DeciwattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.GigawattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.GigawattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.GigawattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.GigawattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.KilowattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.KilowattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.KilowattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.KilowattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.MegawattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.MegawattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.MegawattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.MegawattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.MicrowattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.MicrowattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.MicrowattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.MicrowattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.MilliwattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.MilliwattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.MilliwattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.MilliwattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.NanowattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.NanowattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.NanowattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.NanowattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.PicowattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.PicowattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.PicowattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.PicowattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.TerawattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.TerawattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicMeter, quantity => quantity.ToUnit(PowerDensityUnit.TerawattPerCubicMeter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.TerawattPerLiter)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerCubicFoot, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicFoot)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerCubicInch, quantity => quantity.ToUnit(PowerDensityUnit.WattPerCubicInch)); - unitConverter.SetConversionFunction(PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerLiter, quantity => quantity.ToUnit(PowerDensityUnit.WattPerLiter)); - } - /// /// Get unit abbreviation string. /// @@ -622,7 +604,7 @@ public static string GetAbbreviation(PowerDensityUnit unit, IFormatProvider? pro /// /// Creates a from . /// - public static PowerDensity FromDecawattsPerCubicFoot(double value) + public static PowerDensity FromDecawattsPerCubicFoot(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicFoot); } @@ -630,7 +612,7 @@ public static PowerDensity FromDecawattsPerCubicFoot(double value) /// /// Creates a from . /// - public static PowerDensity FromDecawattsPerCubicInch(double value) + public static PowerDensity FromDecawattsPerCubicInch(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicInch); } @@ -638,7 +620,7 @@ public static PowerDensity FromDecawattsPerCubicInch(double value) /// /// Creates a from . /// - public static PowerDensity FromDecawattsPerCubicMeter(double value) + public static PowerDensity FromDecawattsPerCubicMeter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.DecawattPerCubicMeter); } @@ -646,7 +628,7 @@ public static PowerDensity FromDecawattsPerCubicMeter(double value) /// /// Creates a from . /// - public static PowerDensity FromDecawattsPerLiter(double value) + public static PowerDensity FromDecawattsPerLiter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.DecawattPerLiter); } @@ -654,7 +636,7 @@ public static PowerDensity FromDecawattsPerLiter(double value) /// /// Creates a from . /// - public static PowerDensity FromDeciwattsPerCubicFoot(double value) + public static PowerDensity FromDeciwattsPerCubicFoot(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicFoot); } @@ -662,7 +644,7 @@ public static PowerDensity FromDeciwattsPerCubicFoot(double value) /// /// Creates a from . /// - public static PowerDensity FromDeciwattsPerCubicInch(double value) + public static PowerDensity FromDeciwattsPerCubicInch(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicInch); } @@ -670,7 +652,7 @@ public static PowerDensity FromDeciwattsPerCubicInch(double value) /// /// Creates a from . /// - public static PowerDensity FromDeciwattsPerCubicMeter(double value) + public static PowerDensity FromDeciwattsPerCubicMeter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.DeciwattPerCubicMeter); } @@ -678,7 +660,7 @@ public static PowerDensity FromDeciwattsPerCubicMeter(double value) /// /// Creates a from . /// - public static PowerDensity FromDeciwattsPerLiter(double value) + public static PowerDensity FromDeciwattsPerLiter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.DeciwattPerLiter); } @@ -686,7 +668,7 @@ public static PowerDensity FromDeciwattsPerLiter(double value) /// /// Creates a from . /// - public static PowerDensity FromGigawattsPerCubicFoot(double value) + public static PowerDensity FromGigawattsPerCubicFoot(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicFoot); } @@ -694,7 +676,7 @@ public static PowerDensity FromGigawattsPerCubicFoot(double value) /// /// Creates a from . /// - public static PowerDensity FromGigawattsPerCubicInch(double value) + public static PowerDensity FromGigawattsPerCubicInch(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicInch); } @@ -702,7 +684,7 @@ public static PowerDensity FromGigawattsPerCubicInch(double value) /// /// Creates a from . /// - public static PowerDensity FromGigawattsPerCubicMeter(double value) + public static PowerDensity FromGigawattsPerCubicMeter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.GigawattPerCubicMeter); } @@ -710,7 +692,7 @@ public static PowerDensity FromGigawattsPerCubicMeter(double value) /// /// Creates a from . /// - public static PowerDensity FromGigawattsPerLiter(double value) + public static PowerDensity FromGigawattsPerLiter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.GigawattPerLiter); } @@ -718,7 +700,7 @@ public static PowerDensity FromGigawattsPerLiter(double value) /// /// Creates a from . /// - public static PowerDensity FromKilowattsPerCubicFoot(double value) + public static PowerDensity FromKilowattsPerCubicFoot(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicFoot); } @@ -726,7 +708,7 @@ public static PowerDensity FromKilowattsPerCubicFoot(double value) /// /// Creates a from . /// - public static PowerDensity FromKilowattsPerCubicInch(double value) + public static PowerDensity FromKilowattsPerCubicInch(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicInch); } @@ -734,7 +716,7 @@ public static PowerDensity FromKilowattsPerCubicInch(double value) /// /// Creates a from . /// - public static PowerDensity FromKilowattsPerCubicMeter(double value) + public static PowerDensity FromKilowattsPerCubicMeter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.KilowattPerCubicMeter); } @@ -742,7 +724,7 @@ public static PowerDensity FromKilowattsPerCubicMeter(double value) /// /// Creates a from . /// - public static PowerDensity FromKilowattsPerLiter(double value) + public static PowerDensity FromKilowattsPerLiter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.KilowattPerLiter); } @@ -750,7 +732,7 @@ public static PowerDensity FromKilowattsPerLiter(double value) /// /// Creates a from . /// - public static PowerDensity FromMegawattsPerCubicFoot(double value) + public static PowerDensity FromMegawattsPerCubicFoot(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicFoot); } @@ -758,7 +740,7 @@ public static PowerDensity FromMegawattsPerCubicFoot(double value) /// /// Creates a from . /// - public static PowerDensity FromMegawattsPerCubicInch(double value) + public static PowerDensity FromMegawattsPerCubicInch(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicInch); } @@ -766,7 +748,7 @@ public static PowerDensity FromMegawattsPerCubicInch(double value) /// /// Creates a from . /// - public static PowerDensity FromMegawattsPerCubicMeter(double value) + public static PowerDensity FromMegawattsPerCubicMeter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.MegawattPerCubicMeter); } @@ -774,7 +756,7 @@ public static PowerDensity FromMegawattsPerCubicMeter(double value) /// /// Creates a from . /// - public static PowerDensity FromMegawattsPerLiter(double value) + public static PowerDensity FromMegawattsPerLiter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.MegawattPerLiter); } @@ -782,7 +764,7 @@ public static PowerDensity FromMegawattsPerLiter(double value) /// /// Creates a from . /// - public static PowerDensity FromMicrowattsPerCubicFoot(double value) + public static PowerDensity FromMicrowattsPerCubicFoot(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicFoot); } @@ -790,7 +772,7 @@ public static PowerDensity FromMicrowattsPerCubicFoot(double value) /// /// Creates a from . /// - public static PowerDensity FromMicrowattsPerCubicInch(double value) + public static PowerDensity FromMicrowattsPerCubicInch(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicInch); } @@ -798,7 +780,7 @@ public static PowerDensity FromMicrowattsPerCubicInch(double value) /// /// Creates a from . /// - public static PowerDensity FromMicrowattsPerCubicMeter(double value) + public static PowerDensity FromMicrowattsPerCubicMeter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.MicrowattPerCubicMeter); } @@ -806,7 +788,7 @@ public static PowerDensity FromMicrowattsPerCubicMeter(double value) /// /// Creates a from . /// - public static PowerDensity FromMicrowattsPerLiter(double value) + public static PowerDensity FromMicrowattsPerLiter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.MicrowattPerLiter); } @@ -814,7 +796,7 @@ public static PowerDensity FromMicrowattsPerLiter(double value) /// /// Creates a from . /// - public static PowerDensity FromMilliwattsPerCubicFoot(double value) + public static PowerDensity FromMilliwattsPerCubicFoot(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicFoot); } @@ -822,7 +804,7 @@ public static PowerDensity FromMilliwattsPerCubicFoot(double value) /// /// Creates a from . /// - public static PowerDensity FromMilliwattsPerCubicInch(double value) + public static PowerDensity FromMilliwattsPerCubicInch(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicInch); } @@ -830,7 +812,7 @@ public static PowerDensity FromMilliwattsPerCubicInch(double value) /// /// Creates a from . /// - public static PowerDensity FromMilliwattsPerCubicMeter(double value) + public static PowerDensity FromMilliwattsPerCubicMeter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.MilliwattPerCubicMeter); } @@ -838,7 +820,7 @@ public static PowerDensity FromMilliwattsPerCubicMeter(double value) /// /// Creates a from . /// - public static PowerDensity FromMilliwattsPerLiter(double value) + public static PowerDensity FromMilliwattsPerLiter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.MilliwattPerLiter); } @@ -846,7 +828,7 @@ public static PowerDensity FromMilliwattsPerLiter(double value) /// /// Creates a from . /// - public static PowerDensity FromNanowattsPerCubicFoot(double value) + public static PowerDensity FromNanowattsPerCubicFoot(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicFoot); } @@ -854,7 +836,7 @@ public static PowerDensity FromNanowattsPerCubicFoot(double value) /// /// Creates a from . /// - public static PowerDensity FromNanowattsPerCubicInch(double value) + public static PowerDensity FromNanowattsPerCubicInch(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicInch); } @@ -862,7 +844,7 @@ public static PowerDensity FromNanowattsPerCubicInch(double value) /// /// Creates a from . /// - public static PowerDensity FromNanowattsPerCubicMeter(double value) + public static PowerDensity FromNanowattsPerCubicMeter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.NanowattPerCubicMeter); } @@ -870,7 +852,7 @@ public static PowerDensity FromNanowattsPerCubicMeter(double value) /// /// Creates a from . /// - public static PowerDensity FromNanowattsPerLiter(double value) + public static PowerDensity FromNanowattsPerLiter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.NanowattPerLiter); } @@ -878,7 +860,7 @@ public static PowerDensity FromNanowattsPerLiter(double value) /// /// Creates a from . /// - public static PowerDensity FromPicowattsPerCubicFoot(double value) + public static PowerDensity FromPicowattsPerCubicFoot(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicFoot); } @@ -886,7 +868,7 @@ public static PowerDensity FromPicowattsPerCubicFoot(double value) /// /// Creates a from . /// - public static PowerDensity FromPicowattsPerCubicInch(double value) + public static PowerDensity FromPicowattsPerCubicInch(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicInch); } @@ -894,7 +876,7 @@ public static PowerDensity FromPicowattsPerCubicInch(double value) /// /// Creates a from . /// - public static PowerDensity FromPicowattsPerCubicMeter(double value) + public static PowerDensity FromPicowattsPerCubicMeter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.PicowattPerCubicMeter); } @@ -902,7 +884,7 @@ public static PowerDensity FromPicowattsPerCubicMeter(double value) /// /// Creates a from . /// - public static PowerDensity FromPicowattsPerLiter(double value) + public static PowerDensity FromPicowattsPerLiter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.PicowattPerLiter); } @@ -910,7 +892,7 @@ public static PowerDensity FromPicowattsPerLiter(double value) /// /// Creates a from . /// - public static PowerDensity FromTerawattsPerCubicFoot(double value) + public static PowerDensity FromTerawattsPerCubicFoot(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicFoot); } @@ -918,7 +900,7 @@ public static PowerDensity FromTerawattsPerCubicFoot(double value) /// /// Creates a from . /// - public static PowerDensity FromTerawattsPerCubicInch(double value) + public static PowerDensity FromTerawattsPerCubicInch(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicInch); } @@ -926,7 +908,7 @@ public static PowerDensity FromTerawattsPerCubicInch(double value) /// /// Creates a from . /// - public static PowerDensity FromTerawattsPerCubicMeter(double value) + public static PowerDensity FromTerawattsPerCubicMeter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.TerawattPerCubicMeter); } @@ -934,7 +916,7 @@ public static PowerDensity FromTerawattsPerCubicMeter(double value) /// /// Creates a from . /// - public static PowerDensity FromTerawattsPerLiter(double value) + public static PowerDensity FromTerawattsPerLiter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.TerawattPerLiter); } @@ -942,7 +924,7 @@ public static PowerDensity FromTerawattsPerLiter(double value) /// /// Creates a from . /// - public static PowerDensity FromWattsPerCubicFoot(double value) + public static PowerDensity FromWattsPerCubicFoot(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.WattPerCubicFoot); } @@ -950,7 +932,7 @@ public static PowerDensity FromWattsPerCubicFoot(double value) /// /// Creates a from . /// - public static PowerDensity FromWattsPerCubicInch(double value) + public static PowerDensity FromWattsPerCubicInch(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.WattPerCubicInch); } @@ -958,7 +940,7 @@ public static PowerDensity FromWattsPerCubicInch(double value) /// /// Creates a from . /// - public static PowerDensity FromWattsPerCubicMeter(double value) + public static PowerDensity FromWattsPerCubicMeter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.WattPerCubicMeter); } @@ -966,7 +948,7 @@ public static PowerDensity FromWattsPerCubicMeter(double value) /// /// Creates a from . /// - public static PowerDensity FromWattsPerLiter(double value) + public static PowerDensity FromWattsPerLiter(QuantityValue value) { return new PowerDensity(value, PowerDensityUnit.WattPerLiter); } @@ -977,7 +959,7 @@ public static PowerDensity FromWattsPerLiter(double value) /// Value to convert from. /// Unit to convert from. /// PowerDensity unit value. - public static PowerDensity From(double value, PowerDensityUnit fromUnit) + public static PowerDensity From(QuantityValue value, PowerDensityUnit fromUnit) { return new PowerDensity(value, fromUnit); } @@ -1038,10 +1020,7 @@ public static PowerDensity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static PowerDensity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -1069,11 +1048,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out PowerDensity res /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out PowerDensity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -1094,7 +1069,7 @@ public static PowerDensityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -1105,7 +1080,7 @@ public static PowerDensityUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out PowerDensityUnit unit) { return TryParseUnit(str, null, out unit); @@ -1120,7 +1095,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out PowerDensity /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out PowerDensityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -1139,35 +1114,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static PowerDensity operator +(PowerDensity left, PowerDensity right) { - return new PowerDensity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new PowerDensity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static PowerDensity operator -(PowerDensity left, PowerDensity right) { - return new PowerDensity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new PowerDensity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -1179,97 +1154,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(PowerDensity left, PowerDensity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(PowerDensity left, PowerDensity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(PowerDensity left, PowerDensity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(PowerDensity left, PowerDensity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(PowerDensity other, PowerDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(PowerDensity left, PowerDensity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(PowerDensity other, PowerDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(PowerDensity left, PowerDensity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(PowerDensity other, PowerDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is PowerDensity otherQuantity)) + if (obj is not PowerDensity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(PowerDensity other, PowerDensity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(PowerDensity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current PowerDensity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(PowerDensity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is PowerDensity otherQuantity)) throw new ArgumentException("Expected type PowerDensity.", nameof(obj)); + if (obj is not PowerDensity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1281,232 +1241,24 @@ public int CompareTo(object? obj) /// public int CompareTo(PowerDensity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PowerDensityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this PowerDensity to another PowerDensity with the unit representation . - /// - /// The unit to convert to. - /// A PowerDensity with the specified unit. - public PowerDensity ToUnit(PowerDensityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A PowerDensity with the specified unit. - public PowerDensity ToUnit(PowerDensityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(PowerDensity), Unit, typeof(PowerDensity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (PowerDensity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(PowerDensityUnit unit, [NotNullWhen(true)] out PowerDensity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - PowerDensity? convertedOrNull = (Unit, unit) switch - { - // PowerDensityUnit -> BaseUnit - (PowerDensityUnit.DecawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 0.028316846592) * 1e1d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.DecawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 1.6387064e-5) * 1e1d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.DecawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e1d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.DecawattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e1d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.DeciwattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 0.028316846592) * 1e-1d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.DeciwattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 1.6387064e-5) * 1e-1d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.DeciwattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e-1d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.DeciwattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e-1d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.GigawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 0.028316846592) * 1e9d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.GigawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 1.6387064e-5) * 1e9d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.GigawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e9d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.GigawattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e9d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.KilowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 0.028316846592) * 1e3d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.KilowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 1.6387064e-5) * 1e3d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.KilowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e3d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.KilowattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e3d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.MegawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 0.028316846592) * 1e6d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.MegawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 1.6387064e-5) * 1e6d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.MegawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e6d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.MegawattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e6d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.MicrowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 0.028316846592) * 1e-6d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.MicrowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 1.6387064e-5) * 1e-6d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.MicrowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e-6d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.MicrowattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e-6d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.MilliwattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 0.028316846592) * 1e-3d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.MilliwattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 1.6387064e-5) * 1e-3d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.MilliwattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e-3d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.MilliwattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e-3d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.NanowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 0.028316846592) * 1e-9d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.NanowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 1.6387064e-5) * 1e-9d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.NanowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e-9d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.NanowattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e-9d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.PicowattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 0.028316846592) * 1e-12d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.PicowattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 1.6387064e-5) * 1e-12d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.PicowattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e-12d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.PicowattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e-12d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.TerawattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 0.028316846592) * 1e12d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.TerawattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value / 1.6387064e-5) * 1e12d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.TerawattPerCubicMeter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value) * 1e12d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.TerawattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity((_value * 1.0e3) * 1e12d, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.WattPerCubicFoot, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity(_value / 0.028316846592, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.WattPerCubicInch, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity(_value / 1.6387064e-5, PowerDensityUnit.WattPerCubicMeter), - (PowerDensityUnit.WattPerLiter, PowerDensityUnit.WattPerCubicMeter) => new PowerDensity(_value * 1.0e3, PowerDensityUnit.WattPerCubicMeter), - - // BaseUnit -> PowerDensityUnit - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicFoot) => new PowerDensity((_value * 0.028316846592) / 1e1d, PowerDensityUnit.DecawattPerCubicFoot), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicInch) => new PowerDensity((_value * 1.6387064e-5) / 1e1d, PowerDensityUnit.DecawattPerCubicInch), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerCubicMeter) => new PowerDensity((_value) / 1e1d, PowerDensityUnit.DecawattPerCubicMeter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DecawattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e1d, PowerDensityUnit.DecawattPerLiter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicFoot) => new PowerDensity((_value * 0.028316846592) / 1e-1d, PowerDensityUnit.DeciwattPerCubicFoot), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicInch) => new PowerDensity((_value * 1.6387064e-5) / 1e-1d, PowerDensityUnit.DeciwattPerCubicInch), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerCubicMeter) => new PowerDensity((_value) / 1e-1d, PowerDensityUnit.DeciwattPerCubicMeter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.DeciwattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e-1d, PowerDensityUnit.DeciwattPerLiter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicFoot) => new PowerDensity((_value * 0.028316846592) / 1e9d, PowerDensityUnit.GigawattPerCubicFoot), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicInch) => new PowerDensity((_value * 1.6387064e-5) / 1e9d, PowerDensityUnit.GigawattPerCubicInch), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerCubicMeter) => new PowerDensity((_value) / 1e9d, PowerDensityUnit.GigawattPerCubicMeter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.GigawattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e9d, PowerDensityUnit.GigawattPerLiter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicFoot) => new PowerDensity((_value * 0.028316846592) / 1e3d, PowerDensityUnit.KilowattPerCubicFoot), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicInch) => new PowerDensity((_value * 1.6387064e-5) / 1e3d, PowerDensityUnit.KilowattPerCubicInch), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerCubicMeter) => new PowerDensity((_value) / 1e3d, PowerDensityUnit.KilowattPerCubicMeter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.KilowattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e3d, PowerDensityUnit.KilowattPerLiter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicFoot) => new PowerDensity((_value * 0.028316846592) / 1e6d, PowerDensityUnit.MegawattPerCubicFoot), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicInch) => new PowerDensity((_value * 1.6387064e-5) / 1e6d, PowerDensityUnit.MegawattPerCubicInch), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerCubicMeter) => new PowerDensity((_value) / 1e6d, PowerDensityUnit.MegawattPerCubicMeter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MegawattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e6d, PowerDensityUnit.MegawattPerLiter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicFoot) => new PowerDensity((_value * 0.028316846592) / 1e-6d, PowerDensityUnit.MicrowattPerCubicFoot), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicInch) => new PowerDensity((_value * 1.6387064e-5) / 1e-6d, PowerDensityUnit.MicrowattPerCubicInch), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerCubicMeter) => new PowerDensity((_value) / 1e-6d, PowerDensityUnit.MicrowattPerCubicMeter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MicrowattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e-6d, PowerDensityUnit.MicrowattPerLiter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicFoot) => new PowerDensity((_value * 0.028316846592) / 1e-3d, PowerDensityUnit.MilliwattPerCubicFoot), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicInch) => new PowerDensity((_value * 1.6387064e-5) / 1e-3d, PowerDensityUnit.MilliwattPerCubicInch), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerCubicMeter) => new PowerDensity((_value) / 1e-3d, PowerDensityUnit.MilliwattPerCubicMeter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.MilliwattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e-3d, PowerDensityUnit.MilliwattPerLiter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicFoot) => new PowerDensity((_value * 0.028316846592) / 1e-9d, PowerDensityUnit.NanowattPerCubicFoot), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicInch) => new PowerDensity((_value * 1.6387064e-5) / 1e-9d, PowerDensityUnit.NanowattPerCubicInch), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerCubicMeter) => new PowerDensity((_value) / 1e-9d, PowerDensityUnit.NanowattPerCubicMeter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.NanowattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e-9d, PowerDensityUnit.NanowattPerLiter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicFoot) => new PowerDensity((_value * 0.028316846592) / 1e-12d, PowerDensityUnit.PicowattPerCubicFoot), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicInch) => new PowerDensity((_value * 1.6387064e-5) / 1e-12d, PowerDensityUnit.PicowattPerCubicInch), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerCubicMeter) => new PowerDensity((_value) / 1e-12d, PowerDensityUnit.PicowattPerCubicMeter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.PicowattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e-12d, PowerDensityUnit.PicowattPerLiter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicFoot) => new PowerDensity((_value * 0.028316846592) / 1e12d, PowerDensityUnit.TerawattPerCubicFoot), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicInch) => new PowerDensity((_value * 1.6387064e-5) / 1e12d, PowerDensityUnit.TerawattPerCubicInch), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerCubicMeter) => new PowerDensity((_value) / 1e12d, PowerDensityUnit.TerawattPerCubicMeter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.TerawattPerLiter) => new PowerDensity((_value / 1.0e3) / 1e12d, PowerDensityUnit.TerawattPerLiter), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerCubicFoot) => new PowerDensity(_value * 0.028316846592, PowerDensityUnit.WattPerCubicFoot), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerCubicInch) => new PowerDensity(_value * 1.6387064e-5, PowerDensityUnit.WattPerCubicInch), - (PowerDensityUnit.WattPerCubicMeter, PowerDensityUnit.WattPerLiter) => new PowerDensity(_value / 1.0e3, PowerDensityUnit.WattPerLiter), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public PowerDensity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not PowerDensityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerDensityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(PowerDensityUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(PowerDensityUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1521,7 +1273,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs b/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs index 8d1093e2d5..a8ce3c5957 100644 --- a/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PowerRatio.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// The strength of a signal expressed in decibels (dB) relative to one watt. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct PowerRatio : ILogarithmicQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly PowerRatioUnit? _unit; /// @@ -116,16 +115,17 @@ public static PowerRatioInfo CreateDefault(FuncAn of representing the default unit mappings for PowerRatio. public static IEnumerable> GetDefaultMappings() { - yield return new (PowerRatioUnit.DecibelMilliwatt, "DecibelMilliwatt", "DecibelMilliwatts", BaseUnits.Undefined); + yield return new (PowerRatioUnit.DecibelMilliwatt, "DecibelMilliwatt", "DecibelMilliwatts", BaseUnits.Undefined, + new ConversionExpression(1, 30), + new ConversionExpression(1, -30) + ); yield return new (PowerRatioUnit.DecibelWatt, "DecibelWatt", "DecibelWatts", BaseUnits.Undefined); } } static PowerRatio() { - Info = PowerRatioInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(PowerRatioInfo.CreateDefault); } /// @@ -133,7 +133,7 @@ static PowerRatio() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public PowerRatio(double value, PowerRatioUnit unit) + public PowerRatio(QuantityValue value, PowerRatioUnit unit) { _value = value; _unit = unit; @@ -144,7 +144,8 @@ public PowerRatio(double value, PowerRatioUnit unit) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -170,16 +171,14 @@ public PowerRatio(double value, PowerRatioUnit unit) public static PowerRatio Zero => Info.Zero; /// - public static double LogarithmicScalingFactor {get;} = 10; + public static QuantityValue LogarithmicScalingFactor {get;} = 10; #endregion #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public PowerRatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -212,7 +211,7 @@ public PowerRatio(double value, PowerRatioUnit unit) #endif #if NETSTANDARD2_0 - double ILogarithmicQuantity.LogarithmicScalingFactor => LogarithmicScalingFactor; + QuantityValue ILogarithmicQuantity.LogarithmicScalingFactor => LogarithmicScalingFactor; #endif #endregion @@ -222,35 +221,19 @@ public PowerRatio(double value, PowerRatioUnit unit) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecibelMilliwatts => As(PowerRatioUnit.DecibelMilliwatt); + public QuantityValue DecibelMilliwatts => this.As(PowerRatioUnit.DecibelMilliwatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecibelWatts => As(PowerRatioUnit.DecibelWatt); + public QuantityValue DecibelWatts => this.As(PowerRatioUnit.DecibelWatt); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: PowerRatioUnit -> BaseUnit - unitConverter.SetConversionFunction(PowerRatioUnit.DecibelMilliwatt, PowerRatioUnit.DecibelWatt, quantity => quantity.ToUnit(PowerRatioUnit.DecibelWatt)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(PowerRatioUnit.DecibelWatt, PowerRatioUnit.DecibelWatt, quantity => quantity); - - // Register in unit converter: BaseUnit -> PowerRatioUnit - unitConverter.SetConversionFunction(PowerRatioUnit.DecibelWatt, PowerRatioUnit.DecibelMilliwatt, quantity => quantity.ToUnit(PowerRatioUnit.DecibelMilliwatt)); - } - /// /// Get unit abbreviation string. /// @@ -279,7 +262,7 @@ public static string GetAbbreviation(PowerRatioUnit unit, IFormatProvider? provi /// /// Creates a from . /// - public static PowerRatio FromDecibelMilliwatts(double value) + public static PowerRatio FromDecibelMilliwatts(QuantityValue value) { return new PowerRatio(value, PowerRatioUnit.DecibelMilliwatt); } @@ -287,7 +270,7 @@ public static PowerRatio FromDecibelMilliwatts(double value) /// /// Creates a from . /// - public static PowerRatio FromDecibelWatts(double value) + public static PowerRatio FromDecibelWatts(QuantityValue value) { return new PowerRatio(value, PowerRatioUnit.DecibelWatt); } @@ -298,7 +281,7 @@ public static PowerRatio FromDecibelWatts(double value) /// Value to convert from. /// Unit to convert from. /// PowerRatio unit value. - public static PowerRatio From(double value, PowerRatioUnit fromUnit) + public static PowerRatio From(QuantityValue value, PowerRatioUnit fromUnit) { return new PowerRatio(value, fromUnit); } @@ -359,10 +342,7 @@ public static PowerRatio Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static PowerRatio Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -390,11 +370,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out PowerRatio resul /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out PowerRatio result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -415,7 +391,7 @@ public static PowerRatioUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -426,7 +402,7 @@ public static PowerRatioUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out PowerRatioUnit unit) { return TryParseUnit(str, null, out unit); @@ -441,7 +417,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out PowerRatioUn /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out PowerRatioUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -452,53 +428,61 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? #region Logarithmic Arithmetic Operators /// Negate the value. - public static PowerRatio operator -(PowerRatio right) + public static PowerRatio operator -(PowerRatio quantity) { - return new PowerRatio(-right.Value, right.Unit); + return new PowerRatio(-quantity.Value, quantity.Unit); } /// Get from logarithmic addition of two . + /// This operation involves a conversion of the values to linear space, which is not guaranteed to produce an exact value. + /// The final result is rounded to 15 significant digits. + /// public static PowerRatio operator +(PowerRatio left, PowerRatio right) { // 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.ToUnit(left.Unit).Value / 10)), left.Unit); + var leftUnit = left.Unit; + return new PowerRatio(QuantityValueExtensions.AddWithLogScaling(left.Value, right.As(leftUnit), LogarithmicScalingFactor), leftUnit); } /// Get from logarithmic subtraction of two . + /// This operation involves a conversion of the values to linear space, which is not guaranteed to produce an exact value. + /// The final result is rounded to 15 significant digits. + /// public static PowerRatio operator -(PowerRatio left, PowerRatio right) { // 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.ToUnit(left.Unit).Value / 10)), left.Unit); + var leftUnit = left.Unit; + return new PowerRatio(QuantityValueExtensions.SubtractWithLogScaling(left.Value, right.As(leftUnit), LogarithmicScalingFactor), leftUnit); } /// 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); } /// Get from logarithmic multiplication of value and . - public static PowerRatio operator *(PowerRatio left, double right) + public static PowerRatio operator *(PowerRatio left, QuantityValue right) { // Logarithmic multiplication = addition return new PowerRatio(left.Value + right, left.Unit); } /// Get from logarithmic division of by value. - public static PowerRatio operator /(PowerRatio left, double right) + public static PowerRatio operator /(PowerRatio left, QuantityValue right) { // Logarithmic division = subtraction return new PowerRatio(left.Value - right, left.Unit); } /// Get ratio value from logarithmic division of by . - public static double operator /(PowerRatio left, PowerRatio right) + public static QuantityValue operator /(PowerRatio left, PowerRatio right) { // Logarithmic division = subtraction - return Convert.ToDouble(left.Value - right.ToUnit(left.Unit).Value); + return left.Value - right.As(left.Unit); } #endregion @@ -508,97 +492,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(PowerRatio left, PowerRatio right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(PowerRatio left, PowerRatio right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(PowerRatio left, PowerRatio right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(PowerRatio left, PowerRatio right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(PowerRatio other, PowerRatio tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(PowerRatio left, PowerRatio right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(PowerRatio other, PowerRatio tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(PowerRatio left, PowerRatio right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(PowerRatio other, PowerRatio tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is PowerRatio otherQuantity)) + if (obj is not PowerRatio otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(PowerRatio other, PowerRatio tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(PowerRatio other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current PowerRatio. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(PowerRatio), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is PowerRatio otherQuantity)) throw new ArgumentException("Expected type PowerRatio.", nameof(obj)); + if (obj is not PowerRatio otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -610,148 +579,24 @@ public int CompareTo(object? obj) /// public int CompareTo(PowerRatio other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PowerRatioUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this PowerRatio to another PowerRatio with the unit representation . - /// - /// The unit to convert to. - /// A PowerRatio with the specified unit. - public PowerRatio ToUnit(PowerRatioUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A PowerRatio with the specified unit. - public PowerRatio ToUnit(PowerRatioUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(PowerRatio), Unit, typeof(PowerRatio), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (PowerRatio)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(PowerRatioUnit unit, [NotNullWhen(true)] out PowerRatio? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - PowerRatio? convertedOrNull = (Unit, unit) switch - { - // PowerRatioUnit -> BaseUnit - (PowerRatioUnit.DecibelMilliwatt, PowerRatioUnit.DecibelWatt) => new PowerRatio(_value - 30, PowerRatioUnit.DecibelWatt), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> PowerRatioUnit - (PowerRatioUnit.DecibelWatt, PowerRatioUnit.DecibelMilliwatt) => new PowerRatio(_value + 30, PowerRatioUnit.DecibelMilliwatt), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public PowerRatio ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not PowerRatioUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerRatioUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is PowerRatioUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PowerRatioUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(PowerRatioUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(PowerRatioUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -766,7 +611,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs index 9f10ec036f..af6cd82f45 100644 --- a/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Pressure.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Pressure : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -62,13 +61,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly PressureUnit? _unit; /// @@ -113,7 +112,7 @@ public static PressureInfo CreateDefault(Func - /// The for is [T^-2][L^-1][M]. + /// The for is T^-2L^-1M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 1, -2, 0, 0, 0, 0); @@ -128,62 +127,154 @@ public static PressureInfo CreateDefault(FuncAn of representing the default unit mappings for Pressure. public static IEnumerable> GetDefaultMappings() { - yield return new (PressureUnit.Atmosphere, "Atmosphere", "Atmospheres", BaseUnits.Undefined); - yield return new (PressureUnit.Bar, "Bar", "Bars", BaseUnits.Undefined); - yield return new (PressureUnit.Centibar, "Centibar", "Centibars", BaseUnits.Undefined); - yield return new (PressureUnit.CentimeterOfWaterColumn, "CentimeterOfWaterColumn", "CentimetersOfWaterColumn", BaseUnits.Undefined); - yield return new (PressureUnit.Decapascal, "Decapascal", "Decapascals", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PressureUnit.Decibar, "Decibar", "Decibars", BaseUnits.Undefined); - yield return new (PressureUnit.DynePerSquareCentimeter, "DynePerSquareCentimeter", "DynesPerSquareCentimeter", BaseUnits.Undefined); - yield return new (PressureUnit.FootOfHead, "FootOfHead", "FeetOfHead", BaseUnits.Undefined); - yield return new (PressureUnit.Gigapascal, "Gigapascal", "Gigapascals", new BaseUnits(length: LengthUnit.Nanometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PressureUnit.Hectopascal, "Hectopascal", "Hectopascals", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PressureUnit.InchOfMercury, "InchOfMercury", "InchesOfMercury", BaseUnits.Undefined); - yield return new (PressureUnit.InchOfWaterColumn, "InchOfWaterColumn", "InchesOfWaterColumn", BaseUnits.Undefined); - yield return new (PressureUnit.Kilobar, "Kilobar", "Kilobars", BaseUnits.Undefined); - yield return new (PressureUnit.KilogramForcePerSquareCentimeter, "KilogramForcePerSquareCentimeter", "KilogramsForcePerSquareCentimeter", BaseUnits.Undefined); - yield return new (PressureUnit.KilogramForcePerSquareMeter, "KilogramForcePerSquareMeter", "KilogramsForcePerSquareMeter", BaseUnits.Undefined); - yield return new (PressureUnit.KilogramForcePerSquareMillimeter, "KilogramForcePerSquareMillimeter", "KilogramsForcePerSquareMillimeter", BaseUnits.Undefined); - yield return new (PressureUnit.KilonewtonPerSquareCentimeter, "KilonewtonPerSquareCentimeter", "KilonewtonsPerSquareCentimeter", BaseUnits.Undefined); - yield return new (PressureUnit.KilonewtonPerSquareMeter, "KilonewtonPerSquareMeter", "KilonewtonsPerSquareMeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PressureUnit.KilonewtonPerSquareMillimeter, "KilonewtonPerSquareMillimeter", "KilonewtonsPerSquareMillimeter", BaseUnits.Undefined); - yield return new (PressureUnit.Kilopascal, "Kilopascal", "Kilopascals", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PressureUnit.KilopoundForcePerSquareFoot, "KilopoundForcePerSquareFoot", "KilopoundsForcePerSquareFoot", BaseUnits.Undefined); - yield return new (PressureUnit.KilopoundForcePerSquareInch, "KilopoundForcePerSquareInch", "KilopoundsForcePerSquareInch", BaseUnits.Undefined); - yield return new (PressureUnit.KilopoundForcePerSquareMil, "KilopoundForcePerSquareMil", "KilopoundsForcePerSquareMil", BaseUnits.Undefined); - yield return new (PressureUnit.Megabar, "Megabar", "Megabars", BaseUnits.Undefined); - yield return new (PressureUnit.MeganewtonPerSquareMeter, "MeganewtonPerSquareMeter", "MeganewtonsPerSquareMeter", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PressureUnit.Megapascal, "Megapascal", "Megapascals", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PressureUnit.MeterOfHead, "MeterOfHead", "MetersOfHead", BaseUnits.Undefined); - yield return new (PressureUnit.MeterOfWaterColumn, "MeterOfWaterColumn", "MetersOfWaterColumn", BaseUnits.Undefined); - yield return new (PressureUnit.Microbar, "Microbar", "Microbars", BaseUnits.Undefined); - yield return new (PressureUnit.Micropascal, "Micropascal", "Micropascals", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second)); - yield return new (PressureUnit.Millibar, "Millibar", "Millibars", BaseUnits.Undefined); - yield return new (PressureUnit.MillimeterOfMercury, "MillimeterOfMercury", "MillimetersOfMercury", BaseUnits.Undefined); - yield return new (PressureUnit.MillimeterOfWaterColumn, "MillimeterOfWaterColumn", "MillimetersOfWaterColumn", BaseUnits.Undefined); - yield return new (PressureUnit.Millipascal, "Millipascal", "Millipascals", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second)); - yield return new (PressureUnit.Millitorr, "Millitorr", "Millitorrs", BaseUnits.Undefined); - yield return new (PressureUnit.NewtonPerSquareCentimeter, "NewtonPerSquareCentimeter", "NewtonsPerSquareCentimeter", BaseUnits.Undefined); - yield return new (PressureUnit.NewtonPerSquareMeter, "NewtonPerSquareMeter", "NewtonsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PressureUnit.NewtonPerSquareMillimeter, "NewtonPerSquareMillimeter", "NewtonsPerSquareMillimeter", BaseUnits.Undefined); + yield return new (PressureUnit.Atmosphere, "Atmosphere", "Atmospheres", BaseUnits.Undefined, + new QuantityValue(1, 101325) + ); + yield return new (PressureUnit.Bar, "Bar", "Bars", BaseUnits.Undefined, + new QuantityValue(1, 100000) + ); + yield return new (PressureUnit.Centibar, "Centibar", "Centibars", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (PressureUnit.CentimeterOfWaterColumn, "CentimeterOfWaterColumn", "CentimetersOfWaterColumn", BaseUnits.Undefined, + new QuantityValue(2000, 196133) + ); + yield return new (PressureUnit.Decapascal, "Decapascal", "Decapascals", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 10) + ); + yield return new (PressureUnit.Decibar, "Decibar", "Decibars", BaseUnits.Undefined, + new QuantityValue(1, 10000) + ); + yield return new (PressureUnit.DynePerSquareCentimeter, "DynePerSquareCentimeter", "DynesPerSquareCentimeter", BaseUnits.Undefined, + 10 + ); + yield return new (PressureUnit.FootOfHead, "FootOfHead", "FeetOfHead", BaseUnits.Undefined, + new QuantityValue(156250000, 466922140449) + ); + yield return new (PressureUnit.Gigapascal, "Gigapascal", "Gigapascals", new BaseUnits(length: LengthUnit.Nanometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000000) + ); + yield return new (PressureUnit.Hectopascal, "Hectopascal", "Hectopascals", new BaseUnits(length: LengthUnit.Centimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 100) + ); + yield return new (PressureUnit.InchOfMercury, "InchOfMercury", "InchesOfMercury", BaseUnits.Undefined, + new QuantityValue(1000000000, 3386388640341) + ); + yield return new (PressureUnit.InchOfWaterColumn, "InchOfWaterColumn", "InchesOfWaterColumn", BaseUnits.Undefined, + new QuantityValue(100000, 24908891) + ); + yield return new (PressureUnit.Kilobar, "Kilobar", "Kilobars", BaseUnits.Undefined, + new QuantityValue(1, 100000000) + ); + yield return new (PressureUnit.KilogramForcePerSquareCentimeter, "KilogramForcePerSquareCentimeter", "KilogramsForcePerSquareCentimeter", BaseUnits.Undefined, + new QuantityValue(2, 196133) + ); + yield return new (PressureUnit.KilogramForcePerSquareMeter, "KilogramForcePerSquareMeter", "KilogramsForcePerSquareMeter", BaseUnits.Undefined, + new QuantityValue(20000, 196133) + ); + yield return new (PressureUnit.KilogramForcePerSquareMillimeter, "KilogramForcePerSquareMillimeter", "KilogramsForcePerSquareMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 9806650) + ); + yield return new (PressureUnit.KilonewtonPerSquareCentimeter, "KilonewtonPerSquareCentimeter", "KilonewtonsPerSquareCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 10000000) + ); + yield return new (PressureUnit.KilonewtonPerSquareMeter, "KilonewtonPerSquareMeter", "KilonewtonsPerSquareMeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000) + ); + yield return new (PressureUnit.KilonewtonPerSquareMillimeter, "KilonewtonPerSquareMillimeter", "KilonewtonsPerSquareMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 1000000000) + ); + yield return new (PressureUnit.Kilopascal, "Kilopascal", "Kilopascals", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000) + ); + yield return new (PressureUnit.KilopoundForcePerSquareFoot, "KilopoundForcePerSquareFoot", "KilopoundsForcePerSquareFoot", BaseUnits.Undefined, + new QuantityValue(185806080, 8896443230521) + ); + yield return new (PressureUnit.KilopoundForcePerSquareInch, "KilopoundForcePerSquareInch", "KilopoundsForcePerSquareInch", BaseUnits.Undefined, + new QuantityValue(1290320, 8896443230521) + ); + yield return new (PressureUnit.KilopoundForcePerSquareMil, "KilopoundForcePerSquareMil", "KilopoundsForcePerSquareMil", BaseUnits.Undefined, + new QuantityValue(16129, 111205540381512500) + ); + yield return new (PressureUnit.Megabar, "Megabar", "Megabars", BaseUnits.Undefined, + new QuantityValue(1, 100000000000) + ); + yield return new (PressureUnit.MeganewtonPerSquareMeter, "MeganewtonPerSquareMeter", "MeganewtonsPerSquareMeter", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (PressureUnit.Megapascal, "Megapascal", "Megapascals", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (PressureUnit.MeterOfHead, "MeterOfHead", "MetersOfHead", BaseUnits.Undefined, + new QuantityValue(125000, 1225517429) + ); + yield return new (PressureUnit.MeterOfWaterColumn, "MeterOfWaterColumn", "MetersOfWaterColumn", BaseUnits.Undefined, + new QuantityValue(20, 196133) + ); + yield return new (PressureUnit.Microbar, "Microbar", "Microbars", BaseUnits.Undefined, + 10 + ); + yield return new (PressureUnit.Micropascal, "Micropascal", "Micropascals", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Milligram, time: DurationUnit.Second), + 1000000 + ); + yield return new (PressureUnit.Millibar, "Millibar", "Millibars", BaseUnits.Undefined, + new QuantityValue(1, 100) + ); + yield return new (PressureUnit.MillimeterOfMercury, "MillimeterOfMercury", "MillimetersOfMercury", BaseUnits.Undefined, + new QuantityValue(200000000, 26664477483) + ); + yield return new (PressureUnit.MillimeterOfWaterColumn, "MillimeterOfWaterColumn", "MillimetersOfWaterColumn", BaseUnits.Undefined, + new QuantityValue(20000, 196133) + ); + yield return new (PressureUnit.Millipascal, "Millipascal", "Millipascals", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Gram, time: DurationUnit.Second), + 1000 + ); + yield return new (PressureUnit.Millitorr, "Millitorr", "Millitorrs", BaseUnits.Undefined, + new QuantityValue(30400, 4053) + ); + yield return new (PressureUnit.NewtonPerSquareCentimeter, "NewtonPerSquareCentimeter", "NewtonsPerSquareCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 10000) + ); + yield return new (PressureUnit.NewtonPerSquareMeter, "NewtonPerSquareMeter", "NewtonsPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + 1 + ); + yield return new (PressureUnit.NewtonPerSquareMillimeter, "NewtonPerSquareMillimeter", "NewtonsPerSquareMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 1000000) + ); yield return new (PressureUnit.Pascal, "Pascal", "Pascals", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PressureUnit.PoundForcePerSquareFoot, "PoundForcePerSquareFoot", "PoundsForcePerSquareFoot", BaseUnits.Undefined); - yield return new (PressureUnit.PoundForcePerSquareInch, "PoundForcePerSquareInch", "PoundsForcePerSquareInch", BaseUnits.Undefined); - yield return new (PressureUnit.PoundForcePerSquareMil, "PoundForcePerSquareMil", "PoundsForcePerSquareMil", BaseUnits.Undefined); - yield return new (PressureUnit.PoundPerInchSecondSquared, "PoundPerInchSecondSquared", "PoundsPerInchSecondSquared", BaseUnits.Undefined); - yield return new (PressureUnit.TechnicalAtmosphere, "TechnicalAtmosphere", "TechnicalAtmospheres", BaseUnits.Undefined); - yield return new (PressureUnit.TonneForcePerSquareCentimeter, "TonneForcePerSquareCentimeter", "TonnesForcePerSquareCentimeter", BaseUnits.Undefined); - yield return new (PressureUnit.TonneForcePerSquareMeter, "TonneForcePerSquareMeter", "TonnesForcePerSquareMeter", BaseUnits.Undefined); - yield return new (PressureUnit.TonneForcePerSquareMillimeter, "TonneForcePerSquareMillimeter", "TonnesForcePerSquareMillimeter", BaseUnits.Undefined); - yield return new (PressureUnit.Torr, "Torr", "Torrs", BaseUnits.Undefined); + yield return new (PressureUnit.PoundForcePerSquareFoot, "PoundForcePerSquareFoot", "PoundsForcePerSquareFoot", BaseUnits.Undefined, + new QuantityValue(185806080000, 8896443230521) + ); + yield return new (PressureUnit.PoundForcePerSquareInch, "PoundForcePerSquareInch", "PoundsForcePerSquareInch", BaseUnits.Undefined, + new QuantityValue(1290320000, 8896443230521) + ); + yield return new (PressureUnit.PoundForcePerSquareMil, "PoundForcePerSquareMil", "PoundsForcePerSquareMil", BaseUnits.Undefined, + new QuantityValue(32258, 222411080763025) + ); + yield return new (PressureUnit.PoundPerInchSecondSquared, "PoundPerInchSecondSquared", "PoundsPerInchSecondSquared", BaseUnits.Undefined, + new QuantityValue(498177842352, 8896443230521) + ); + yield return new (PressureUnit.TechnicalAtmosphere, "TechnicalAtmosphere", "TechnicalAtmospheres", BaseUnits.Undefined, + new QuantityValue(2, 196133) + ); + yield return new (PressureUnit.TonneForcePerSquareCentimeter, "TonneForcePerSquareCentimeter", "TonnesForcePerSquareCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 98066500) + ); + yield return new (PressureUnit.TonneForcePerSquareMeter, "TonneForcePerSquareMeter", "TonnesForcePerSquareMeter", BaseUnits.Undefined, + new QuantityValue(20, 196133) + ); + yield return new (PressureUnit.TonneForcePerSquareMillimeter, "TonneForcePerSquareMillimeter", "TonnesForcePerSquareMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 9806650000) + ); + yield return new (PressureUnit.Torr, "Torr", "Torrs", BaseUnits.Undefined, + new QuantityValue(152, 20265) + ); } } static Pressure() { - Info = PressureInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(PressureInfo.CreateDefault); } /// @@ -191,7 +282,7 @@ static Pressure() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Pressure(double value, PressureUnit unit) + public Pressure(QuantityValue value, PressureUnit unit) { _value = value; _unit = unit; @@ -205,7 +296,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -216,7 +307,8 @@ public Pressure(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -245,10 +337,8 @@ public Pressure(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public PressureUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -287,357 +377,249 @@ public Pressure(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Atmospheres => As(PressureUnit.Atmosphere); + public QuantityValue Atmospheres => this.As(PressureUnit.Atmosphere); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Bars => As(PressureUnit.Bar); + public QuantityValue Bars => this.As(PressureUnit.Bar); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Centibars => As(PressureUnit.Centibar); + public QuantityValue Centibars => this.As(PressureUnit.Centibar); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentimetersOfWaterColumn => As(PressureUnit.CentimeterOfWaterColumn); + public QuantityValue CentimetersOfWaterColumn => this.As(PressureUnit.CentimeterOfWaterColumn); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Decapascals => As(PressureUnit.Decapascal); + public QuantityValue Decapascals => this.As(PressureUnit.Decapascal); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Decibars => As(PressureUnit.Decibar); + public QuantityValue Decibars => this.As(PressureUnit.Decibar); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DynesPerSquareCentimeter => As(PressureUnit.DynePerSquareCentimeter); + public QuantityValue DynesPerSquareCentimeter => this.As(PressureUnit.DynePerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double FeetOfHead => As(PressureUnit.FootOfHead); + public QuantityValue FeetOfHead => this.As(PressureUnit.FootOfHead); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigapascals => As(PressureUnit.Gigapascal); + public QuantityValue Gigapascals => this.As(PressureUnit.Gigapascal); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Hectopascals => As(PressureUnit.Hectopascal); + public QuantityValue Hectopascals => this.As(PressureUnit.Hectopascal); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InchesOfMercury => As(PressureUnit.InchOfMercury); + public QuantityValue InchesOfMercury => this.As(PressureUnit.InchOfMercury); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InchesOfWaterColumn => As(PressureUnit.InchOfWaterColumn); + public QuantityValue InchesOfWaterColumn => this.As(PressureUnit.InchOfWaterColumn); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilobars => As(PressureUnit.Kilobar); + public QuantityValue Kilobars => this.As(PressureUnit.Kilobar); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsForcePerSquareCentimeter => As(PressureUnit.KilogramForcePerSquareCentimeter); + public QuantityValue KilogramsForcePerSquareCentimeter => this.As(PressureUnit.KilogramForcePerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsForcePerSquareMeter => As(PressureUnit.KilogramForcePerSquareMeter); + public QuantityValue KilogramsForcePerSquareMeter => this.As(PressureUnit.KilogramForcePerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsForcePerSquareMillimeter => As(PressureUnit.KilogramForcePerSquareMillimeter); + public QuantityValue KilogramsForcePerSquareMillimeter => this.As(PressureUnit.KilogramForcePerSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonsPerSquareCentimeter => As(PressureUnit.KilonewtonPerSquareCentimeter); + public QuantityValue KilonewtonsPerSquareCentimeter => this.As(PressureUnit.KilonewtonPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonsPerSquareMeter => As(PressureUnit.KilonewtonPerSquareMeter); + public QuantityValue KilonewtonsPerSquareMeter => this.As(PressureUnit.KilonewtonPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonsPerSquareMillimeter => As(PressureUnit.KilonewtonPerSquareMillimeter); + public QuantityValue KilonewtonsPerSquareMillimeter => this.As(PressureUnit.KilonewtonPerSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilopascals => As(PressureUnit.Kilopascal); + public QuantityValue Kilopascals => this.As(PressureUnit.Kilopascal); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsForcePerSquareFoot => As(PressureUnit.KilopoundForcePerSquareFoot); + public QuantityValue KilopoundsForcePerSquareFoot => this.As(PressureUnit.KilopoundForcePerSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsForcePerSquareInch => As(PressureUnit.KilopoundForcePerSquareInch); + public QuantityValue KilopoundsForcePerSquareInch => this.As(PressureUnit.KilopoundForcePerSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsForcePerSquareMil => As(PressureUnit.KilopoundForcePerSquareMil); + public QuantityValue KilopoundsForcePerSquareMil => this.As(PressureUnit.KilopoundForcePerSquareMil); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megabars => As(PressureUnit.Megabar); + public QuantityValue Megabars => this.As(PressureUnit.Megabar); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MeganewtonsPerSquareMeter => As(PressureUnit.MeganewtonPerSquareMeter); + public QuantityValue MeganewtonsPerSquareMeter => this.As(PressureUnit.MeganewtonPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megapascals => As(PressureUnit.Megapascal); + public QuantityValue Megapascals => this.As(PressureUnit.Megapascal); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MetersOfHead => As(PressureUnit.MeterOfHead); + public QuantityValue MetersOfHead => this.As(PressureUnit.MeterOfHead); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MetersOfWaterColumn => As(PressureUnit.MeterOfWaterColumn); + public QuantityValue MetersOfWaterColumn => this.As(PressureUnit.MeterOfWaterColumn); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microbars => As(PressureUnit.Microbar); + public QuantityValue Microbars => this.As(PressureUnit.Microbar); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Micropascals => As(PressureUnit.Micropascal); + public QuantityValue Micropascals => this.As(PressureUnit.Micropascal); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millibars => As(PressureUnit.Millibar); + public QuantityValue Millibars => this.As(PressureUnit.Millibar); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimetersOfMercury => As(PressureUnit.MillimeterOfMercury); + public QuantityValue MillimetersOfMercury => this.As(PressureUnit.MillimeterOfMercury); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimetersOfWaterColumn => As(PressureUnit.MillimeterOfWaterColumn); + public QuantityValue MillimetersOfWaterColumn => this.As(PressureUnit.MillimeterOfWaterColumn); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millipascals => As(PressureUnit.Millipascal); + public QuantityValue Millipascals => this.As(PressureUnit.Millipascal); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millitorrs => As(PressureUnit.Millitorr); + public QuantityValue Millitorrs => this.As(PressureUnit.Millitorr); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonsPerSquareCentimeter => As(PressureUnit.NewtonPerSquareCentimeter); + public QuantityValue NewtonsPerSquareCentimeter => this.As(PressureUnit.NewtonPerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonsPerSquareMeter => As(PressureUnit.NewtonPerSquareMeter); + public QuantityValue NewtonsPerSquareMeter => this.As(PressureUnit.NewtonPerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonsPerSquareMillimeter => As(PressureUnit.NewtonPerSquareMillimeter); + public QuantityValue NewtonsPerSquareMillimeter => this.As(PressureUnit.NewtonPerSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Pascals => As(PressureUnit.Pascal); + public QuantityValue Pascals => this.As(PressureUnit.Pascal); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsForcePerSquareFoot => As(PressureUnit.PoundForcePerSquareFoot); + public QuantityValue PoundsForcePerSquareFoot => this.As(PressureUnit.PoundForcePerSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsForcePerSquareInch => As(PressureUnit.PoundForcePerSquareInch); + public QuantityValue PoundsForcePerSquareInch => this.As(PressureUnit.PoundForcePerSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsForcePerSquareMil => As(PressureUnit.PoundForcePerSquareMil); + public QuantityValue PoundsForcePerSquareMil => this.As(PressureUnit.PoundForcePerSquareMil); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsPerInchSecondSquared => As(PressureUnit.PoundPerInchSecondSquared); + public QuantityValue PoundsPerInchSecondSquared => this.As(PressureUnit.PoundPerInchSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TechnicalAtmospheres => As(PressureUnit.TechnicalAtmosphere); + public QuantityValue TechnicalAtmospheres => this.As(PressureUnit.TechnicalAtmosphere); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesForcePerSquareCentimeter => As(PressureUnit.TonneForcePerSquareCentimeter); + public QuantityValue TonnesForcePerSquareCentimeter => this.As(PressureUnit.TonneForcePerSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesForcePerSquareMeter => As(PressureUnit.TonneForcePerSquareMeter); + public QuantityValue TonnesForcePerSquareMeter => this.As(PressureUnit.TonneForcePerSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesForcePerSquareMillimeter => As(PressureUnit.TonneForcePerSquareMillimeter); + public QuantityValue TonnesForcePerSquareMillimeter => this.As(PressureUnit.TonneForcePerSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Torrs => As(PressureUnit.Torr); + public QuantityValue Torrs => this.As(PressureUnit.Torr); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: PressureUnit -> BaseUnit - unitConverter.SetConversionFunction(PressureUnit.Atmosphere, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.Bar, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.Centibar, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.CentimeterOfWaterColumn, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.Decapascal, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.Decibar, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.DynePerSquareCentimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.FootOfHead, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.Gigapascal, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.Hectopascal, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.InchOfMercury, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.InchOfWaterColumn, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.Kilobar, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.KilogramForcePerSquareCentimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.KilogramForcePerSquareMeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.KilogramForcePerSquareMillimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.KilonewtonPerSquareCentimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.KilonewtonPerSquareMeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.KilonewtonPerSquareMillimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.Kilopascal, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.KilopoundForcePerSquareFoot, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.KilopoundForcePerSquareInch, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.KilopoundForcePerSquareMil, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.Megabar, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.MeganewtonPerSquareMeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.Megapascal, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.MeterOfHead, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.MeterOfWaterColumn, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.Microbar, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.Micropascal, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.Millibar, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.MillimeterOfMercury, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.MillimeterOfWaterColumn, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.Millipascal, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.Millitorr, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.NewtonPerSquareCentimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.NewtonPerSquareMeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.NewtonPerSquareMillimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.PoundForcePerSquareFoot, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.PoundForcePerSquareInch, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.PoundForcePerSquareMil, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.PoundPerInchSecondSquared, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.TechnicalAtmosphere, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.TonneForcePerSquareCentimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.TonneForcePerSquareMeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.TonneForcePerSquareMillimeter, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - unitConverter.SetConversionFunction(PressureUnit.Torr, PressureUnit.Pascal, quantity => quantity.ToUnit(PressureUnit.Pascal)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Pascal, quantity => quantity); - - // Register in unit converter: BaseUnit -> PressureUnit - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Atmosphere, quantity => quantity.ToUnit(PressureUnit.Atmosphere)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Bar, quantity => quantity.ToUnit(PressureUnit.Bar)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Centibar, quantity => quantity.ToUnit(PressureUnit.Centibar)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.CentimeterOfWaterColumn, quantity => quantity.ToUnit(PressureUnit.CentimeterOfWaterColumn)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Decapascal, quantity => quantity.ToUnit(PressureUnit.Decapascal)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Decibar, quantity => quantity.ToUnit(PressureUnit.Decibar)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.DynePerSquareCentimeter, quantity => quantity.ToUnit(PressureUnit.DynePerSquareCentimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.FootOfHead, quantity => quantity.ToUnit(PressureUnit.FootOfHead)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Gigapascal, quantity => quantity.ToUnit(PressureUnit.Gigapascal)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Hectopascal, quantity => quantity.ToUnit(PressureUnit.Hectopascal)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.InchOfMercury, quantity => quantity.ToUnit(PressureUnit.InchOfMercury)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.InchOfWaterColumn, quantity => quantity.ToUnit(PressureUnit.InchOfWaterColumn)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Kilobar, quantity => quantity.ToUnit(PressureUnit.Kilobar)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareCentimeter, quantity => quantity.ToUnit(PressureUnit.KilogramForcePerSquareCentimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareMeter, quantity => quantity.ToUnit(PressureUnit.KilogramForcePerSquareMeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareMillimeter, quantity => quantity.ToUnit(PressureUnit.KilogramForcePerSquareMillimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareCentimeter, quantity => quantity.ToUnit(PressureUnit.KilonewtonPerSquareCentimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareMeter, quantity => quantity.ToUnit(PressureUnit.KilonewtonPerSquareMeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareMillimeter, quantity => quantity.ToUnit(PressureUnit.KilonewtonPerSquareMillimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Kilopascal, quantity => quantity.ToUnit(PressureUnit.Kilopascal)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilopoundForcePerSquareFoot, quantity => quantity.ToUnit(PressureUnit.KilopoundForcePerSquareFoot)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilopoundForcePerSquareInch, quantity => quantity.ToUnit(PressureUnit.KilopoundForcePerSquareInch)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.KilopoundForcePerSquareMil, quantity => quantity.ToUnit(PressureUnit.KilopoundForcePerSquareMil)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Megabar, quantity => quantity.ToUnit(PressureUnit.Megabar)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.MeganewtonPerSquareMeter, quantity => quantity.ToUnit(PressureUnit.MeganewtonPerSquareMeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Megapascal, quantity => quantity.ToUnit(PressureUnit.Megapascal)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.MeterOfHead, quantity => quantity.ToUnit(PressureUnit.MeterOfHead)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.MeterOfWaterColumn, quantity => quantity.ToUnit(PressureUnit.MeterOfWaterColumn)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Microbar, quantity => quantity.ToUnit(PressureUnit.Microbar)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Micropascal, quantity => quantity.ToUnit(PressureUnit.Micropascal)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Millibar, quantity => quantity.ToUnit(PressureUnit.Millibar)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.MillimeterOfMercury, quantity => quantity.ToUnit(PressureUnit.MillimeterOfMercury)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.MillimeterOfWaterColumn, quantity => quantity.ToUnit(PressureUnit.MillimeterOfWaterColumn)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Millipascal, quantity => quantity.ToUnit(PressureUnit.Millipascal)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Millitorr, quantity => quantity.ToUnit(PressureUnit.Millitorr)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.NewtonPerSquareCentimeter, quantity => quantity.ToUnit(PressureUnit.NewtonPerSquareCentimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.NewtonPerSquareMeter, quantity => quantity.ToUnit(PressureUnit.NewtonPerSquareMeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.NewtonPerSquareMillimeter, quantity => quantity.ToUnit(PressureUnit.NewtonPerSquareMillimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.PoundForcePerSquareFoot, quantity => quantity.ToUnit(PressureUnit.PoundForcePerSquareFoot)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.PoundForcePerSquareInch, quantity => quantity.ToUnit(PressureUnit.PoundForcePerSquareInch)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.PoundForcePerSquareMil, quantity => quantity.ToUnit(PressureUnit.PoundForcePerSquareMil)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.PoundPerInchSecondSquared, quantity => quantity.ToUnit(PressureUnit.PoundPerInchSecondSquared)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.TechnicalAtmosphere, quantity => quantity.ToUnit(PressureUnit.TechnicalAtmosphere)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.TonneForcePerSquareCentimeter, quantity => quantity.ToUnit(PressureUnit.TonneForcePerSquareCentimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.TonneForcePerSquareMeter, quantity => quantity.ToUnit(PressureUnit.TonneForcePerSquareMeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.TonneForcePerSquareMillimeter, quantity => quantity.ToUnit(PressureUnit.TonneForcePerSquareMillimeter)); - unitConverter.SetConversionFunction(PressureUnit.Pascal, PressureUnit.Torr, quantity => quantity.ToUnit(PressureUnit.Torr)); - } - /// /// Get unit abbreviation string. /// @@ -666,7 +648,7 @@ public static string GetAbbreviation(PressureUnit unit, IFormatProvider? provide /// /// Creates a from . /// - public static Pressure FromAtmospheres(double value) + public static Pressure FromAtmospheres(QuantityValue value) { return new Pressure(value, PressureUnit.Atmosphere); } @@ -674,7 +656,7 @@ public static Pressure FromAtmospheres(double value) /// /// Creates a from . /// - public static Pressure FromBars(double value) + public static Pressure FromBars(QuantityValue value) { return new Pressure(value, PressureUnit.Bar); } @@ -682,7 +664,7 @@ public static Pressure FromBars(double value) /// /// Creates a from . /// - public static Pressure FromCentibars(double value) + public static Pressure FromCentibars(QuantityValue value) { return new Pressure(value, PressureUnit.Centibar); } @@ -690,7 +672,7 @@ public static Pressure FromCentibars(double value) /// /// Creates a from . /// - public static Pressure FromCentimetersOfWaterColumn(double value) + public static Pressure FromCentimetersOfWaterColumn(QuantityValue value) { return new Pressure(value, PressureUnit.CentimeterOfWaterColumn); } @@ -698,7 +680,7 @@ public static Pressure FromCentimetersOfWaterColumn(double value) /// /// Creates a from . /// - public static Pressure FromDecapascals(double value) + public static Pressure FromDecapascals(QuantityValue value) { return new Pressure(value, PressureUnit.Decapascal); } @@ -706,7 +688,7 @@ public static Pressure FromDecapascals(double value) /// /// Creates a from . /// - public static Pressure FromDecibars(double value) + public static Pressure FromDecibars(QuantityValue value) { return new Pressure(value, PressureUnit.Decibar); } @@ -714,7 +696,7 @@ public static Pressure FromDecibars(double value) /// /// Creates a from . /// - public static Pressure FromDynesPerSquareCentimeter(double value) + public static Pressure FromDynesPerSquareCentimeter(QuantityValue value) { return new Pressure(value, PressureUnit.DynePerSquareCentimeter); } @@ -722,7 +704,7 @@ public static Pressure FromDynesPerSquareCentimeter(double value) /// /// Creates a from . /// - public static Pressure FromFeetOfHead(double value) + public static Pressure FromFeetOfHead(QuantityValue value) { return new Pressure(value, PressureUnit.FootOfHead); } @@ -730,7 +712,7 @@ public static Pressure FromFeetOfHead(double value) /// /// Creates a from . /// - public static Pressure FromGigapascals(double value) + public static Pressure FromGigapascals(QuantityValue value) { return new Pressure(value, PressureUnit.Gigapascal); } @@ -738,7 +720,7 @@ public static Pressure FromGigapascals(double value) /// /// Creates a from . /// - public static Pressure FromHectopascals(double value) + public static Pressure FromHectopascals(QuantityValue value) { return new Pressure(value, PressureUnit.Hectopascal); } @@ -746,7 +728,7 @@ public static Pressure FromHectopascals(double value) /// /// Creates a from . /// - public static Pressure FromInchesOfMercury(double value) + public static Pressure FromInchesOfMercury(QuantityValue value) { return new Pressure(value, PressureUnit.InchOfMercury); } @@ -754,7 +736,7 @@ public static Pressure FromInchesOfMercury(double value) /// /// Creates a from . /// - public static Pressure FromInchesOfWaterColumn(double value) + public static Pressure FromInchesOfWaterColumn(QuantityValue value) { return new Pressure(value, PressureUnit.InchOfWaterColumn); } @@ -762,7 +744,7 @@ public static Pressure FromInchesOfWaterColumn(double value) /// /// Creates a from . /// - public static Pressure FromKilobars(double value) + public static Pressure FromKilobars(QuantityValue value) { return new Pressure(value, PressureUnit.Kilobar); } @@ -770,7 +752,7 @@ public static Pressure FromKilobars(double value) /// /// Creates a from . /// - public static Pressure FromKilogramsForcePerSquareCentimeter(double value) + public static Pressure FromKilogramsForcePerSquareCentimeter(QuantityValue value) { return new Pressure(value, PressureUnit.KilogramForcePerSquareCentimeter); } @@ -778,7 +760,7 @@ public static Pressure FromKilogramsForcePerSquareCentimeter(double value) /// /// Creates a from . /// - public static Pressure FromKilogramsForcePerSquareMeter(double value) + public static Pressure FromKilogramsForcePerSquareMeter(QuantityValue value) { return new Pressure(value, PressureUnit.KilogramForcePerSquareMeter); } @@ -786,7 +768,7 @@ public static Pressure FromKilogramsForcePerSquareMeter(double value) /// /// Creates a from . /// - public static Pressure FromKilogramsForcePerSquareMillimeter(double value) + public static Pressure FromKilogramsForcePerSquareMillimeter(QuantityValue value) { return new Pressure(value, PressureUnit.KilogramForcePerSquareMillimeter); } @@ -794,7 +776,7 @@ public static Pressure FromKilogramsForcePerSquareMillimeter(double value) /// /// Creates a from . /// - public static Pressure FromKilonewtonsPerSquareCentimeter(double value) + public static Pressure FromKilonewtonsPerSquareCentimeter(QuantityValue value) { return new Pressure(value, PressureUnit.KilonewtonPerSquareCentimeter); } @@ -802,7 +784,7 @@ public static Pressure FromKilonewtonsPerSquareCentimeter(double value) /// /// Creates a from . /// - public static Pressure FromKilonewtonsPerSquareMeter(double value) + public static Pressure FromKilonewtonsPerSquareMeter(QuantityValue value) { return new Pressure(value, PressureUnit.KilonewtonPerSquareMeter); } @@ -810,7 +792,7 @@ public static Pressure FromKilonewtonsPerSquareMeter(double value) /// /// Creates a from . /// - public static Pressure FromKilonewtonsPerSquareMillimeter(double value) + public static Pressure FromKilonewtonsPerSquareMillimeter(QuantityValue value) { return new Pressure(value, PressureUnit.KilonewtonPerSquareMillimeter); } @@ -818,7 +800,7 @@ public static Pressure FromKilonewtonsPerSquareMillimeter(double value) /// /// Creates a from . /// - public static Pressure FromKilopascals(double value) + public static Pressure FromKilopascals(QuantityValue value) { return new Pressure(value, PressureUnit.Kilopascal); } @@ -826,7 +808,7 @@ public static Pressure FromKilopascals(double value) /// /// Creates a from . /// - public static Pressure FromKilopoundsForcePerSquareFoot(double value) + public static Pressure FromKilopoundsForcePerSquareFoot(QuantityValue value) { return new Pressure(value, PressureUnit.KilopoundForcePerSquareFoot); } @@ -834,7 +816,7 @@ public static Pressure FromKilopoundsForcePerSquareFoot(double value) /// /// Creates a from . /// - public static Pressure FromKilopoundsForcePerSquareInch(double value) + public static Pressure FromKilopoundsForcePerSquareInch(QuantityValue value) { return new Pressure(value, PressureUnit.KilopoundForcePerSquareInch); } @@ -842,7 +824,7 @@ public static Pressure FromKilopoundsForcePerSquareInch(double value) /// /// Creates a from . /// - public static Pressure FromKilopoundsForcePerSquareMil(double value) + public static Pressure FromKilopoundsForcePerSquareMil(QuantityValue value) { return new Pressure(value, PressureUnit.KilopoundForcePerSquareMil); } @@ -850,7 +832,7 @@ public static Pressure FromKilopoundsForcePerSquareMil(double value) /// /// Creates a from . /// - public static Pressure FromMegabars(double value) + public static Pressure FromMegabars(QuantityValue value) { return new Pressure(value, PressureUnit.Megabar); } @@ -858,7 +840,7 @@ public static Pressure FromMegabars(double value) /// /// Creates a from . /// - public static Pressure FromMeganewtonsPerSquareMeter(double value) + public static Pressure FromMeganewtonsPerSquareMeter(QuantityValue value) { return new Pressure(value, PressureUnit.MeganewtonPerSquareMeter); } @@ -866,7 +848,7 @@ public static Pressure FromMeganewtonsPerSquareMeter(double value) /// /// Creates a from . /// - public static Pressure FromMegapascals(double value) + public static Pressure FromMegapascals(QuantityValue value) { return new Pressure(value, PressureUnit.Megapascal); } @@ -874,7 +856,7 @@ public static Pressure FromMegapascals(double value) /// /// Creates a from . /// - public static Pressure FromMetersOfHead(double value) + public static Pressure FromMetersOfHead(QuantityValue value) { return new Pressure(value, PressureUnit.MeterOfHead); } @@ -882,7 +864,7 @@ public static Pressure FromMetersOfHead(double value) /// /// Creates a from . /// - public static Pressure FromMetersOfWaterColumn(double value) + public static Pressure FromMetersOfWaterColumn(QuantityValue value) { return new Pressure(value, PressureUnit.MeterOfWaterColumn); } @@ -890,7 +872,7 @@ public static Pressure FromMetersOfWaterColumn(double value) /// /// Creates a from . /// - public static Pressure FromMicrobars(double value) + public static Pressure FromMicrobars(QuantityValue value) { return new Pressure(value, PressureUnit.Microbar); } @@ -898,7 +880,7 @@ public static Pressure FromMicrobars(double value) /// /// Creates a from . /// - public static Pressure FromMicropascals(double value) + public static Pressure FromMicropascals(QuantityValue value) { return new Pressure(value, PressureUnit.Micropascal); } @@ -906,7 +888,7 @@ public static Pressure FromMicropascals(double value) /// /// Creates a from . /// - public static Pressure FromMillibars(double value) + public static Pressure FromMillibars(QuantityValue value) { return new Pressure(value, PressureUnit.Millibar); } @@ -914,7 +896,7 @@ public static Pressure FromMillibars(double value) /// /// Creates a from . /// - public static Pressure FromMillimetersOfMercury(double value) + public static Pressure FromMillimetersOfMercury(QuantityValue value) { return new Pressure(value, PressureUnit.MillimeterOfMercury); } @@ -922,7 +904,7 @@ public static Pressure FromMillimetersOfMercury(double value) /// /// Creates a from . /// - public static Pressure FromMillimetersOfWaterColumn(double value) + public static Pressure FromMillimetersOfWaterColumn(QuantityValue value) { return new Pressure(value, PressureUnit.MillimeterOfWaterColumn); } @@ -930,7 +912,7 @@ public static Pressure FromMillimetersOfWaterColumn(double value) /// /// Creates a from . /// - public static Pressure FromMillipascals(double value) + public static Pressure FromMillipascals(QuantityValue value) { return new Pressure(value, PressureUnit.Millipascal); } @@ -938,7 +920,7 @@ public static Pressure FromMillipascals(double value) /// /// Creates a from . /// - public static Pressure FromMillitorrs(double value) + public static Pressure FromMillitorrs(QuantityValue value) { return new Pressure(value, PressureUnit.Millitorr); } @@ -946,7 +928,7 @@ public static Pressure FromMillitorrs(double value) /// /// Creates a from . /// - public static Pressure FromNewtonsPerSquareCentimeter(double value) + public static Pressure FromNewtonsPerSquareCentimeter(QuantityValue value) { return new Pressure(value, PressureUnit.NewtonPerSquareCentimeter); } @@ -954,7 +936,7 @@ public static Pressure FromNewtonsPerSquareCentimeter(double value) /// /// Creates a from . /// - public static Pressure FromNewtonsPerSquareMeter(double value) + public static Pressure FromNewtonsPerSquareMeter(QuantityValue value) { return new Pressure(value, PressureUnit.NewtonPerSquareMeter); } @@ -962,7 +944,7 @@ public static Pressure FromNewtonsPerSquareMeter(double value) /// /// Creates a from . /// - public static Pressure FromNewtonsPerSquareMillimeter(double value) + public static Pressure FromNewtonsPerSquareMillimeter(QuantityValue value) { return new Pressure(value, PressureUnit.NewtonPerSquareMillimeter); } @@ -970,7 +952,7 @@ public static Pressure FromNewtonsPerSquareMillimeter(double value) /// /// Creates a from . /// - public static Pressure FromPascals(double value) + public static Pressure FromPascals(QuantityValue value) { return new Pressure(value, PressureUnit.Pascal); } @@ -978,7 +960,7 @@ public static Pressure FromPascals(double value) /// /// Creates a from . /// - public static Pressure FromPoundsForcePerSquareFoot(double value) + public static Pressure FromPoundsForcePerSquareFoot(QuantityValue value) { return new Pressure(value, PressureUnit.PoundForcePerSquareFoot); } @@ -986,7 +968,7 @@ public static Pressure FromPoundsForcePerSquareFoot(double value) /// /// Creates a from . /// - public static Pressure FromPoundsForcePerSquareInch(double value) + public static Pressure FromPoundsForcePerSquareInch(QuantityValue value) { return new Pressure(value, PressureUnit.PoundForcePerSquareInch); } @@ -994,7 +976,7 @@ public static Pressure FromPoundsForcePerSquareInch(double value) /// /// Creates a from . /// - public static Pressure FromPoundsForcePerSquareMil(double value) + public static Pressure FromPoundsForcePerSquareMil(QuantityValue value) { return new Pressure(value, PressureUnit.PoundForcePerSquareMil); } @@ -1002,7 +984,7 @@ public static Pressure FromPoundsForcePerSquareMil(double value) /// /// Creates a from . /// - public static Pressure FromPoundsPerInchSecondSquared(double value) + public static Pressure FromPoundsPerInchSecondSquared(QuantityValue value) { return new Pressure(value, PressureUnit.PoundPerInchSecondSquared); } @@ -1010,7 +992,7 @@ public static Pressure FromPoundsPerInchSecondSquared(double value) /// /// Creates a from . /// - public static Pressure FromTechnicalAtmospheres(double value) + public static Pressure FromTechnicalAtmospheres(QuantityValue value) { return new Pressure(value, PressureUnit.TechnicalAtmosphere); } @@ -1018,7 +1000,7 @@ public static Pressure FromTechnicalAtmospheres(double value) /// /// Creates a from . /// - public static Pressure FromTonnesForcePerSquareCentimeter(double value) + public static Pressure FromTonnesForcePerSquareCentimeter(QuantityValue value) { return new Pressure(value, PressureUnit.TonneForcePerSquareCentimeter); } @@ -1026,7 +1008,7 @@ public static Pressure FromTonnesForcePerSquareCentimeter(double value) /// /// Creates a from . /// - public static Pressure FromTonnesForcePerSquareMeter(double value) + public static Pressure FromTonnesForcePerSquareMeter(QuantityValue value) { return new Pressure(value, PressureUnit.TonneForcePerSquareMeter); } @@ -1034,7 +1016,7 @@ public static Pressure FromTonnesForcePerSquareMeter(double value) /// /// Creates a from . /// - public static Pressure FromTonnesForcePerSquareMillimeter(double value) + public static Pressure FromTonnesForcePerSquareMillimeter(QuantityValue value) { return new Pressure(value, PressureUnit.TonneForcePerSquareMillimeter); } @@ -1042,7 +1024,7 @@ public static Pressure FromTonnesForcePerSquareMillimeter(double value) /// /// Creates a from . /// - public static Pressure FromTorrs(double value) + public static Pressure FromTorrs(QuantityValue value) { return new Pressure(value, PressureUnit.Torr); } @@ -1053,7 +1035,7 @@ public static Pressure FromTorrs(double value) /// Value to convert from. /// Unit to convert from. /// Pressure unit value. - public static Pressure From(double value, PressureUnit fromUnit) + public static Pressure From(QuantityValue value, PressureUnit fromUnit) { return new Pressure(value, fromUnit); } @@ -1114,10 +1096,7 @@ public static Pressure Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Pressure Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -1145,11 +1124,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Pressure result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Pressure result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -1170,7 +1145,7 @@ public static PressureUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -1181,7 +1156,7 @@ public static PressureUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out PressureUnit unit) { return TryParseUnit(str, null, out unit); @@ -1196,7 +1171,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out PressureUnit /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out PressureUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -1215,35 +1190,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Pressure operator +(Pressure left, Pressure right) { - return new Pressure(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Pressure(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Pressure operator -(Pressure left, Pressure right) { - return new Pressure(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Pressure(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -1319,97 +1294,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Pressure left, Pressure right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Pressure left, Pressure right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Pressure left, Pressure right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Pressure left, Pressure right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Pressure other, Pressure tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Pressure left, Pressure right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Pressure other, Pressure tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Pressure left, Pressure right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Pressure other, Pressure tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Pressure otherQuantity)) + if (obj is not Pressure otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Pressure other, Pressure tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Pressure other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Pressure. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Pressure), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Pressure otherQuantity)) throw new ArgumentException("Expected type Pressure.", nameof(obj)); + if (obj is not Pressure otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1421,240 +1381,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Pressure other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PressureUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Pressure to another Pressure with the unit representation . - /// - /// The unit to convert to. - /// A Pressure with the specified unit. - public Pressure ToUnit(PressureUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Pressure with the specified unit. - public Pressure ToUnit(PressureUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Pressure), Unit, typeof(Pressure), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Pressure)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(PressureUnit unit, [NotNullWhen(true)] out Pressure? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Pressure? convertedOrNull = (Unit, unit) switch - { - // PressureUnit -> BaseUnit - (PressureUnit.Atmosphere, PressureUnit.Pascal) => new Pressure(_value * 1.01325 * 1e5, PressureUnit.Pascal), - (PressureUnit.Bar, PressureUnit.Pascal) => new Pressure(_value * 1e5, PressureUnit.Pascal), - (PressureUnit.Centibar, PressureUnit.Pascal) => new Pressure((_value * 1e5) * 1e-2d, PressureUnit.Pascal), - (PressureUnit.CentimeterOfWaterColumn, PressureUnit.Pascal) => new Pressure((_value * 9.80665e3) * 1e-2d, PressureUnit.Pascal), - (PressureUnit.Decapascal, PressureUnit.Pascal) => new Pressure((_value) * 1e1d, PressureUnit.Pascal), - (PressureUnit.Decibar, PressureUnit.Pascal) => new Pressure((_value * 1e5) * 1e-1d, PressureUnit.Pascal), - (PressureUnit.DynePerSquareCentimeter, PressureUnit.Pascal) => new Pressure(_value * 1.0e-1, PressureUnit.Pascal), - (PressureUnit.FootOfHead, PressureUnit.Pascal) => new Pressure(_value * 9804.139432 * 0.3048, PressureUnit.Pascal), - (PressureUnit.Gigapascal, PressureUnit.Pascal) => new Pressure((_value) * 1e9d, PressureUnit.Pascal), - (PressureUnit.Hectopascal, PressureUnit.Pascal) => new Pressure((_value) * 1e2d, PressureUnit.Pascal), - (PressureUnit.InchOfMercury, PressureUnit.Pascal) => new Pressure(_value * 2.54e1 * 133.322387415, PressureUnit.Pascal), - (PressureUnit.InchOfWaterColumn, PressureUnit.Pascal) => new Pressure(_value * 2.54e-2 * 9.80665e3, PressureUnit.Pascal), - (PressureUnit.Kilobar, PressureUnit.Pascal) => new Pressure((_value * 1e5) * 1e3d, PressureUnit.Pascal), - (PressureUnit.KilogramForcePerSquareCentimeter, PressureUnit.Pascal) => new Pressure(_value * 9.80665e4, PressureUnit.Pascal), - (PressureUnit.KilogramForcePerSquareMeter, PressureUnit.Pascal) => new Pressure(_value * 9.80665, PressureUnit.Pascal), - (PressureUnit.KilogramForcePerSquareMillimeter, PressureUnit.Pascal) => new Pressure(_value * 9.80665e6, PressureUnit.Pascal), - (PressureUnit.KilonewtonPerSquareCentimeter, PressureUnit.Pascal) => new Pressure((_value * 1e4) * 1e3d, PressureUnit.Pascal), - (PressureUnit.KilonewtonPerSquareMeter, PressureUnit.Pascal) => new Pressure((_value) * 1e3d, PressureUnit.Pascal), - (PressureUnit.KilonewtonPerSquareMillimeter, PressureUnit.Pascal) => new Pressure((_value * 1e6) * 1e3d, PressureUnit.Pascal), - (PressureUnit.Kilopascal, PressureUnit.Pascal) => new Pressure((_value) * 1e3d, PressureUnit.Pascal), - (PressureUnit.KilopoundForcePerSquareFoot, PressureUnit.Pascal) => new Pressure((_value * 4.4482216152605 / 9.290304e-2) * 1e3d, PressureUnit.Pascal), - (PressureUnit.KilopoundForcePerSquareInch, PressureUnit.Pascal) => new Pressure((_value * 4.4482216152605 / 0.00064516) * 1e3d, PressureUnit.Pascal), - (PressureUnit.KilopoundForcePerSquareMil, PressureUnit.Pascal) => new Pressure((_value * 4.4482216152605 / (2.54e-5 * 2.54e-5)) * 1e3d, PressureUnit.Pascal), - (PressureUnit.Megabar, PressureUnit.Pascal) => new Pressure((_value * 1e5) * 1e6d, PressureUnit.Pascal), - (PressureUnit.MeganewtonPerSquareMeter, PressureUnit.Pascal) => new Pressure((_value) * 1e6d, PressureUnit.Pascal), - (PressureUnit.Megapascal, PressureUnit.Pascal) => new Pressure((_value) * 1e6d, PressureUnit.Pascal), - (PressureUnit.MeterOfHead, PressureUnit.Pascal) => new Pressure(_value * 9804.139432, PressureUnit.Pascal), - (PressureUnit.MeterOfWaterColumn, PressureUnit.Pascal) => new Pressure(_value * 9.80665e3, PressureUnit.Pascal), - (PressureUnit.Microbar, PressureUnit.Pascal) => new Pressure((_value * 1e5) * 1e-6d, PressureUnit.Pascal), - (PressureUnit.Micropascal, PressureUnit.Pascal) => new Pressure((_value) * 1e-6d, PressureUnit.Pascal), - (PressureUnit.Millibar, PressureUnit.Pascal) => new Pressure((_value * 1e5) * 1e-3d, PressureUnit.Pascal), - (PressureUnit.MillimeterOfMercury, PressureUnit.Pascal) => new Pressure(_value * 133.322387415, PressureUnit.Pascal), - (PressureUnit.MillimeterOfWaterColumn, PressureUnit.Pascal) => new Pressure((_value * 9.80665e3) * 1e-3d, PressureUnit.Pascal), - (PressureUnit.Millipascal, PressureUnit.Pascal) => new Pressure((_value) * 1e-3d, PressureUnit.Pascal), - (PressureUnit.Millitorr, PressureUnit.Pascal) => new Pressure((_value * 101325 / 760) * 1e-3d, PressureUnit.Pascal), - (PressureUnit.NewtonPerSquareCentimeter, PressureUnit.Pascal) => new Pressure(_value * 1e4, PressureUnit.Pascal), - (PressureUnit.NewtonPerSquareMeter, PressureUnit.Pascal) => new Pressure(_value, PressureUnit.Pascal), - (PressureUnit.NewtonPerSquareMillimeter, PressureUnit.Pascal) => new Pressure(_value * 1e6, PressureUnit.Pascal), - (PressureUnit.PoundForcePerSquareFoot, PressureUnit.Pascal) => new Pressure(_value * 4.4482216152605 / 9.290304e-2, PressureUnit.Pascal), - (PressureUnit.PoundForcePerSquareInch, PressureUnit.Pascal) => new Pressure(_value * 4.4482216152605 / 0.00064516, PressureUnit.Pascal), - (PressureUnit.PoundForcePerSquareMil, PressureUnit.Pascal) => new Pressure(_value * 4.4482216152605 / (2.54e-5 * 2.54e-5), PressureUnit.Pascal), - (PressureUnit.PoundPerInchSecondSquared, PressureUnit.Pascal) => new Pressure(_value * (4.4482216152605 / 0.00064516) / 386.0886, PressureUnit.Pascal), - (PressureUnit.TechnicalAtmosphere, PressureUnit.Pascal) => new Pressure(_value * 9.80665e4, PressureUnit.Pascal), - (PressureUnit.TonneForcePerSquareCentimeter, PressureUnit.Pascal) => new Pressure(_value * 9.80665e7, PressureUnit.Pascal), - (PressureUnit.TonneForcePerSquareMeter, PressureUnit.Pascal) => new Pressure(_value * 9.80665e3, PressureUnit.Pascal), - (PressureUnit.TonneForcePerSquareMillimeter, PressureUnit.Pascal) => new Pressure(_value * 9.80665e9, PressureUnit.Pascal), - (PressureUnit.Torr, PressureUnit.Pascal) => new Pressure(_value * 101325 / 760, PressureUnit.Pascal), - - // BaseUnit -> PressureUnit - (PressureUnit.Pascal, PressureUnit.Atmosphere) => new Pressure(_value / (1.01325 * 1e5), PressureUnit.Atmosphere), - (PressureUnit.Pascal, PressureUnit.Bar) => new Pressure(_value / 1e5, PressureUnit.Bar), - (PressureUnit.Pascal, PressureUnit.Centibar) => new Pressure((_value / 1e5) / 1e-2d, PressureUnit.Centibar), - (PressureUnit.Pascal, PressureUnit.CentimeterOfWaterColumn) => new Pressure((_value / 9.80665e3) / 1e-2d, PressureUnit.CentimeterOfWaterColumn), - (PressureUnit.Pascal, PressureUnit.Decapascal) => new Pressure((_value) / 1e1d, PressureUnit.Decapascal), - (PressureUnit.Pascal, PressureUnit.Decibar) => new Pressure((_value / 1e5) / 1e-1d, PressureUnit.Decibar), - (PressureUnit.Pascal, PressureUnit.DynePerSquareCentimeter) => new Pressure(_value / 1.0e-1, PressureUnit.DynePerSquareCentimeter), - (PressureUnit.Pascal, PressureUnit.FootOfHead) => new Pressure(_value / (9804.139432 * 0.3048), PressureUnit.FootOfHead), - (PressureUnit.Pascal, PressureUnit.Gigapascal) => new Pressure((_value) / 1e9d, PressureUnit.Gigapascal), - (PressureUnit.Pascal, PressureUnit.Hectopascal) => new Pressure((_value) / 1e2d, PressureUnit.Hectopascal), - (PressureUnit.Pascal, PressureUnit.InchOfMercury) => new Pressure(_value / (2.54e1 * 133.322387415), PressureUnit.InchOfMercury), - (PressureUnit.Pascal, PressureUnit.InchOfWaterColumn) => new Pressure(_value / (2.54e-2 * 9.80665e3), PressureUnit.InchOfWaterColumn), - (PressureUnit.Pascal, PressureUnit.Kilobar) => new Pressure((_value / 1e5) / 1e3d, PressureUnit.Kilobar), - (PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareCentimeter) => new Pressure(_value / 9.80665e4, PressureUnit.KilogramForcePerSquareCentimeter), - (PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareMeter) => new Pressure(_value / 9.80665, PressureUnit.KilogramForcePerSquareMeter), - (PressureUnit.Pascal, PressureUnit.KilogramForcePerSquareMillimeter) => new Pressure(_value / 9.80665e6, PressureUnit.KilogramForcePerSquareMillimeter), - (PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareCentimeter) => new Pressure((_value / 1e4) / 1e3d, PressureUnit.KilonewtonPerSquareCentimeter), - (PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareMeter) => new Pressure((_value) / 1e3d, PressureUnit.KilonewtonPerSquareMeter), - (PressureUnit.Pascal, PressureUnit.KilonewtonPerSquareMillimeter) => new Pressure((_value / 1e6) / 1e3d, PressureUnit.KilonewtonPerSquareMillimeter), - (PressureUnit.Pascal, PressureUnit.Kilopascal) => new Pressure((_value) / 1e3d, PressureUnit.Kilopascal), - (PressureUnit.Pascal, PressureUnit.KilopoundForcePerSquareFoot) => new Pressure((_value * 9.290304e-2 / 4.4482216152605) / 1e3d, PressureUnit.KilopoundForcePerSquareFoot), - (PressureUnit.Pascal, PressureUnit.KilopoundForcePerSquareInch) => new Pressure((_value * 0.00064516 / 4.4482216152605) / 1e3d, PressureUnit.KilopoundForcePerSquareInch), - (PressureUnit.Pascal, PressureUnit.KilopoundForcePerSquareMil) => new Pressure((_value * (2.54e-5 * 2.54e-5) / 4.4482216152605) / 1e3d, PressureUnit.KilopoundForcePerSquareMil), - (PressureUnit.Pascal, PressureUnit.Megabar) => new Pressure((_value / 1e5) / 1e6d, PressureUnit.Megabar), - (PressureUnit.Pascal, PressureUnit.MeganewtonPerSquareMeter) => new Pressure((_value) / 1e6d, PressureUnit.MeganewtonPerSquareMeter), - (PressureUnit.Pascal, PressureUnit.Megapascal) => new Pressure((_value) / 1e6d, PressureUnit.Megapascal), - (PressureUnit.Pascal, PressureUnit.MeterOfHead) => new Pressure(_value / 9804.139432, PressureUnit.MeterOfHead), - (PressureUnit.Pascal, PressureUnit.MeterOfWaterColumn) => new Pressure(_value / 9.80665e3, PressureUnit.MeterOfWaterColumn), - (PressureUnit.Pascal, PressureUnit.Microbar) => new Pressure((_value / 1e5) / 1e-6d, PressureUnit.Microbar), - (PressureUnit.Pascal, PressureUnit.Micropascal) => new Pressure((_value) / 1e-6d, PressureUnit.Micropascal), - (PressureUnit.Pascal, PressureUnit.Millibar) => new Pressure((_value / 1e5) / 1e-3d, PressureUnit.Millibar), - (PressureUnit.Pascal, PressureUnit.MillimeterOfMercury) => new Pressure(_value / 133.322387415, PressureUnit.MillimeterOfMercury), - (PressureUnit.Pascal, PressureUnit.MillimeterOfWaterColumn) => new Pressure((_value / 9.80665e3) / 1e-3d, PressureUnit.MillimeterOfWaterColumn), - (PressureUnit.Pascal, PressureUnit.Millipascal) => new Pressure((_value) / 1e-3d, PressureUnit.Millipascal), - (PressureUnit.Pascal, PressureUnit.Millitorr) => new Pressure((_value * 760 / 101325) / 1e-3d, PressureUnit.Millitorr), - (PressureUnit.Pascal, PressureUnit.NewtonPerSquareCentimeter) => new Pressure(_value / 1e4, PressureUnit.NewtonPerSquareCentimeter), - (PressureUnit.Pascal, PressureUnit.NewtonPerSquareMeter) => new Pressure(_value, PressureUnit.NewtonPerSquareMeter), - (PressureUnit.Pascal, PressureUnit.NewtonPerSquareMillimeter) => new Pressure(_value / 1e6, PressureUnit.NewtonPerSquareMillimeter), - (PressureUnit.Pascal, PressureUnit.PoundForcePerSquareFoot) => new Pressure(_value * 9.290304e-2 / 4.4482216152605, PressureUnit.PoundForcePerSquareFoot), - (PressureUnit.Pascal, PressureUnit.PoundForcePerSquareInch) => new Pressure(_value * 0.00064516 / 4.4482216152605, PressureUnit.PoundForcePerSquareInch), - (PressureUnit.Pascal, PressureUnit.PoundForcePerSquareMil) => new Pressure(_value * (2.54e-5 * 2.54e-5) / 4.4482216152605, PressureUnit.PoundForcePerSquareMil), - (PressureUnit.Pascal, PressureUnit.PoundPerInchSecondSquared) => new Pressure(_value * 386.0886 / (4.4482216152605 / 0.00064516), PressureUnit.PoundPerInchSecondSquared), - (PressureUnit.Pascal, PressureUnit.TechnicalAtmosphere) => new Pressure(_value / 9.80665e4, PressureUnit.TechnicalAtmosphere), - (PressureUnit.Pascal, PressureUnit.TonneForcePerSquareCentimeter) => new Pressure(_value / 9.80665e7, PressureUnit.TonneForcePerSquareCentimeter), - (PressureUnit.Pascal, PressureUnit.TonneForcePerSquareMeter) => new Pressure(_value / 9.80665e3, PressureUnit.TonneForcePerSquareMeter), - (PressureUnit.Pascal, PressureUnit.TonneForcePerSquareMillimeter) => new Pressure(_value / 9.80665e9, PressureUnit.TonneForcePerSquareMillimeter), - (PressureUnit.Pascal, PressureUnit.Torr) => new Pressure(_value * 760 / 101325, PressureUnit.Torr), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Pressure ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not PressureUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PressureUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(PressureUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(PressureUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1669,7 +1413,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs index 3a92170c4d..6b624efe28 100644 --- a/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/PressureChangeRate.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct PressureChangeRate : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly PressureChangeRateUnit? _unit; /// @@ -104,7 +103,7 @@ public static PressureChangeRateInfo CreateDefault(Func - /// The for is [T^-3][L^-1][M]. + /// The for is T^-3L^-1M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 1, -3, 0, 0, 0, 0); @@ -119,32 +118,64 @@ public static PressureChangeRateInfo CreateDefault(FuncAn of representing the default unit mappings for PressureChangeRate. public static IEnumerable> GetDefaultMappings() { - yield return new (PressureChangeRateUnit.AtmospherePerSecond, "AtmospherePerSecond", "AtmospheresPerSecond", BaseUnits.Undefined); - yield return new (PressureChangeRateUnit.BarPerMinute, "BarPerMinute", "BarsPerMinute", BaseUnits.Undefined); - yield return new (PressureChangeRateUnit.BarPerSecond, "BarPerSecond", "BarsPerSecond", BaseUnits.Undefined); - yield return new (PressureChangeRateUnit.KilopascalPerMinute, "KilopascalPerMinute", "KilopascalsPerMinute", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Minute)); - yield return new (PressureChangeRateUnit.KilopascalPerSecond, "KilopascalPerSecond", "KilopascalsPerSecond", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, "KilopoundForcePerSquareInchPerMinute", "KilopoundsForcePerSquareInchPerMinute", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Kilopound, time: DurationUnit.Minute)); - yield return new (PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, "KilopoundForcePerSquareInchPerSecond", "KilopoundsForcePerSquareInchPerSecond", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Kilopound, time: DurationUnit.Second)); - yield return new (PressureChangeRateUnit.MegapascalPerMinute, "MegapascalPerMinute", "MegapascalsPerMinute", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Minute)); - yield return new (PressureChangeRateUnit.MegapascalPerSecond, "MegapascalPerSecond", "MegapascalsPerSecond", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, "MegapoundForcePerSquareInchPerMinute", "MegapoundsForcePerSquareInchPerMinute", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Megapound, time: DurationUnit.Minute)); - yield return new (PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, "MegapoundForcePerSquareInchPerSecond", "MegapoundsForcePerSquareInchPerSecond", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Megapound, time: DurationUnit.Second)); - yield return new (PressureChangeRateUnit.MillibarPerMinute, "MillibarPerMinute", "MillibarsPerMinute", BaseUnits.Undefined); - yield return new (PressureChangeRateUnit.MillibarPerSecond, "MillibarPerSecond", "MillibarsPerSecond", BaseUnits.Undefined); - yield return new (PressureChangeRateUnit.MillimeterOfMercuryPerSecond, "MillimeterOfMercuryPerSecond", "MillimetersOfMercuryPerSecond", BaseUnits.Undefined); - yield return new (PressureChangeRateUnit.PascalPerMinute, "PascalPerMinute", "PascalsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute)); + yield return new (PressureChangeRateUnit.AtmospherePerSecond, "AtmospherePerSecond", "AtmospheresPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 101325) + ); + yield return new (PressureChangeRateUnit.BarPerMinute, "BarPerMinute", "BarsPerMinute", BaseUnits.Undefined, + new QuantityValue(3, 5000) + ); + yield return new (PressureChangeRateUnit.BarPerSecond, "BarPerSecond", "BarsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 100000) + ); + yield return new (PressureChangeRateUnit.KilopascalPerMinute, "KilopascalPerMinute", "KilopascalsPerMinute", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Minute), + new QuantityValue(3, 50) + ); + yield return new (PressureChangeRateUnit.KilopascalPerSecond, "KilopascalPerSecond", "KilopascalsPerSecond", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000) + ); + yield return new (PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, "KilopoundForcePerSquareInchPerMinute", "KilopoundsForcePerSquareInchPerMinute", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Kilopound, time: DurationUnit.Minute), + new QuantityValue(77419200, 8896443230521) + ); + yield return new (PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, "KilopoundForcePerSquareInchPerSecond", "KilopoundsForcePerSquareInchPerSecond", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Kilopound, time: DurationUnit.Second), + new QuantityValue(1290320, 8896443230521) + ); + yield return new (PressureChangeRateUnit.MegapascalPerMinute, "MegapascalPerMinute", "MegapascalsPerMinute", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Minute), + new QuantityValue(3, 50000) + ); + yield return new (PressureChangeRateUnit.MegapascalPerSecond, "MegapascalPerSecond", "MegapascalsPerSecond", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, "MegapoundForcePerSquareInchPerMinute", "MegapoundsForcePerSquareInchPerMinute", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Megapound, time: DurationUnit.Minute), + new QuantityValue(387096, 44482216152605) + ); + yield return new (PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, "MegapoundForcePerSquareInchPerSecond", "MegapoundsForcePerSquareInchPerSecond", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Megapound, time: DurationUnit.Second), + new QuantityValue(32258, 222411080763025) + ); + yield return new (PressureChangeRateUnit.MillibarPerMinute, "MillibarPerMinute", "MillibarsPerMinute", BaseUnits.Undefined, + new QuantityValue(3, 5) + ); + yield return new (PressureChangeRateUnit.MillibarPerSecond, "MillibarPerSecond", "MillibarsPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 100) + ); + yield return new (PressureChangeRateUnit.MillimeterOfMercuryPerSecond, "MillimeterOfMercuryPerSecond", "MillimetersOfMercuryPerSecond", BaseUnits.Undefined, + new QuantityValue(200000000, 26664477483) + ); + yield return new (PressureChangeRateUnit.PascalPerMinute, "PascalPerMinute", "PascalsPerMinute", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Minute), + 60 + ); yield return new (PressureChangeRateUnit.PascalPerSecond, "PascalPerSecond", "PascalsPerSecond", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, "PoundForcePerSquareInchPerMinute", "PoundsForcePerSquareInchPerMinute", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound, time: DurationUnit.Minute)); - yield return new (PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, "PoundForcePerSquareInchPerSecond", "PoundsForcePerSquareInchPerSecond", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound, time: DurationUnit.Second)); + yield return new (PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, "PoundForcePerSquareInchPerMinute", "PoundsForcePerSquareInchPerMinute", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound, time: DurationUnit.Minute), + new QuantityValue(77419200000, 8896443230521) + ); + yield return new (PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, "PoundForcePerSquareInchPerSecond", "PoundsForcePerSquareInchPerSecond", new BaseUnits(length: LengthUnit.Inch, mass: MassUnit.Pound, time: DurationUnit.Second), + new QuantityValue(1290320000, 8896443230521) + ); } } static PressureChangeRate() { - Info = PressureChangeRateInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(PressureChangeRateInfo.CreateDefault); } /// @@ -152,7 +183,7 @@ static PressureChangeRate() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public PressureChangeRate(double value, PressureChangeRateUnit unit) + public PressureChangeRate(QuantityValue value, PressureChangeRateUnit unit) { _value = value; _unit = unit; @@ -166,7 +197,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -177,7 +208,8 @@ public PressureChangeRate(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -206,10 +238,8 @@ public PressureChangeRate(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public PressureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -248,147 +278,99 @@ public PressureChangeRate(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AtmospheresPerSecond => As(PressureChangeRateUnit.AtmospherePerSecond); + public QuantityValue AtmospheresPerSecond => this.As(PressureChangeRateUnit.AtmospherePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BarsPerMinute => As(PressureChangeRateUnit.BarPerMinute); + public QuantityValue BarsPerMinute => this.As(PressureChangeRateUnit.BarPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BarsPerSecond => As(PressureChangeRateUnit.BarPerSecond); + public QuantityValue BarsPerSecond => this.As(PressureChangeRateUnit.BarPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopascalsPerMinute => As(PressureChangeRateUnit.KilopascalPerMinute); + public QuantityValue KilopascalsPerMinute => this.As(PressureChangeRateUnit.KilopascalPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopascalsPerSecond => As(PressureChangeRateUnit.KilopascalPerSecond); + public QuantityValue KilopascalsPerSecond => this.As(PressureChangeRateUnit.KilopascalPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsForcePerSquareInchPerMinute => As(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute); + public QuantityValue KilopoundsForcePerSquareInchPerMinute => this.As(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsForcePerSquareInchPerSecond => As(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond); + public QuantityValue KilopoundsForcePerSquareInchPerSecond => this.As(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegapascalsPerMinute => As(PressureChangeRateUnit.MegapascalPerMinute); + public QuantityValue MegapascalsPerMinute => this.As(PressureChangeRateUnit.MegapascalPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegapascalsPerSecond => As(PressureChangeRateUnit.MegapascalPerSecond); + public QuantityValue MegapascalsPerSecond => this.As(PressureChangeRateUnit.MegapascalPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegapoundsForcePerSquareInchPerMinute => As(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute); + public QuantityValue MegapoundsForcePerSquareInchPerMinute => this.As(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegapoundsForcePerSquareInchPerSecond => As(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond); + public QuantityValue MegapoundsForcePerSquareInchPerSecond => this.As(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillibarsPerMinute => As(PressureChangeRateUnit.MillibarPerMinute); + public QuantityValue MillibarsPerMinute => this.As(PressureChangeRateUnit.MillibarPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillibarsPerSecond => As(PressureChangeRateUnit.MillibarPerSecond); + public QuantityValue MillibarsPerSecond => this.As(PressureChangeRateUnit.MillibarPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimetersOfMercuryPerSecond => As(PressureChangeRateUnit.MillimeterOfMercuryPerSecond); + public QuantityValue MillimetersOfMercuryPerSecond => this.As(PressureChangeRateUnit.MillimeterOfMercuryPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PascalsPerMinute => As(PressureChangeRateUnit.PascalPerMinute); + public QuantityValue PascalsPerMinute => this.As(PressureChangeRateUnit.PascalPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PascalsPerSecond => As(PressureChangeRateUnit.PascalPerSecond); + public QuantityValue PascalsPerSecond => this.As(PressureChangeRateUnit.PascalPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsForcePerSquareInchPerMinute => As(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute); + public QuantityValue PoundsForcePerSquareInchPerMinute => this.As(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsForcePerSquareInchPerSecond => As(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond); + public QuantityValue PoundsForcePerSquareInchPerSecond => this.As(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: PressureChangeRateUnit -> BaseUnit - unitConverter.SetConversionFunction(PressureChangeRateUnit.AtmospherePerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.BarPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.BarPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.KilopascalPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.KilopascalPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.MegapascalPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.MegapascalPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.MillibarPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.MillibarPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.MillimeterOfMercuryPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PascalPerSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> PressureChangeRateUnit - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.AtmospherePerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.AtmospherePerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.BarPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.BarPerMinute)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.BarPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.BarPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopascalPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.KilopascalPerMinute)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.KilopascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapascalPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.MegapascalPerMinute)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapascalPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.MegapascalPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MillibarPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.MillibarPerMinute)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MillibarPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.MillibarPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MillimeterOfMercuryPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.MillimeterOfMercuryPerSecond)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PascalPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.PascalPerMinute)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, quantity => quantity.ToUnit(PressureChangeRateUnit.PoundForcePerSquareInchPerMinute)); - unitConverter.SetConversionFunction(PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, quantity => quantity.ToUnit(PressureChangeRateUnit.PoundForcePerSquareInchPerSecond)); - } - /// /// Get unit abbreviation string. /// @@ -417,7 +399,7 @@ public static string GetAbbreviation(PressureChangeRateUnit unit, IFormatProvide /// /// Creates a from . /// - public static PressureChangeRate FromAtmospheresPerSecond(double value) + public static PressureChangeRate FromAtmospheresPerSecond(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.AtmospherePerSecond); } @@ -425,7 +407,7 @@ public static PressureChangeRate FromAtmospheresPerSecond(double value) /// /// Creates a from . /// - public static PressureChangeRate FromBarsPerMinute(double value) + public static PressureChangeRate FromBarsPerMinute(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.BarPerMinute); } @@ -433,7 +415,7 @@ public static PressureChangeRate FromBarsPerMinute(double value) /// /// Creates a from . /// - public static PressureChangeRate FromBarsPerSecond(double value) + public static PressureChangeRate FromBarsPerSecond(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.BarPerSecond); } @@ -441,7 +423,7 @@ public static PressureChangeRate FromBarsPerSecond(double value) /// /// Creates a from . /// - public static PressureChangeRate FromKilopascalsPerMinute(double value) + public static PressureChangeRate FromKilopascalsPerMinute(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.KilopascalPerMinute); } @@ -449,7 +431,7 @@ public static PressureChangeRate FromKilopascalsPerMinute(double value) /// /// Creates a from . /// - public static PressureChangeRate FromKilopascalsPerSecond(double value) + public static PressureChangeRate FromKilopascalsPerSecond(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.KilopascalPerSecond); } @@ -457,7 +439,7 @@ public static PressureChangeRate FromKilopascalsPerSecond(double value) /// /// Creates a from . /// - public static PressureChangeRate FromKilopoundsForcePerSquareInchPerMinute(double value) + public static PressureChangeRate FromKilopoundsForcePerSquareInchPerMinute(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute); } @@ -465,7 +447,7 @@ public static PressureChangeRate FromKilopoundsForcePerSquareInchPerMinute(doubl /// /// Creates a from . /// - public static PressureChangeRate FromKilopoundsForcePerSquareInchPerSecond(double value) + public static PressureChangeRate FromKilopoundsForcePerSquareInchPerSecond(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond); } @@ -473,7 +455,7 @@ public static PressureChangeRate FromKilopoundsForcePerSquareInchPerSecond(doubl /// /// Creates a from . /// - public static PressureChangeRate FromMegapascalsPerMinute(double value) + public static PressureChangeRate FromMegapascalsPerMinute(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.MegapascalPerMinute); } @@ -481,7 +463,7 @@ public static PressureChangeRate FromMegapascalsPerMinute(double value) /// /// Creates a from . /// - public static PressureChangeRate FromMegapascalsPerSecond(double value) + public static PressureChangeRate FromMegapascalsPerSecond(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.MegapascalPerSecond); } @@ -489,7 +471,7 @@ public static PressureChangeRate FromMegapascalsPerSecond(double value) /// /// Creates a from . /// - public static PressureChangeRate FromMegapoundsForcePerSquareInchPerMinute(double value) + public static PressureChangeRate FromMegapoundsForcePerSquareInchPerMinute(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute); } @@ -497,7 +479,7 @@ public static PressureChangeRate FromMegapoundsForcePerSquareInchPerMinute(doubl /// /// Creates a from . /// - public static PressureChangeRate FromMegapoundsForcePerSquareInchPerSecond(double value) + public static PressureChangeRate FromMegapoundsForcePerSquareInchPerSecond(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond); } @@ -505,7 +487,7 @@ public static PressureChangeRate FromMegapoundsForcePerSquareInchPerSecond(doubl /// /// Creates a from . /// - public static PressureChangeRate FromMillibarsPerMinute(double value) + public static PressureChangeRate FromMillibarsPerMinute(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.MillibarPerMinute); } @@ -513,7 +495,7 @@ public static PressureChangeRate FromMillibarsPerMinute(double value) /// /// Creates a from . /// - public static PressureChangeRate FromMillibarsPerSecond(double value) + public static PressureChangeRate FromMillibarsPerSecond(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.MillibarPerSecond); } @@ -521,7 +503,7 @@ public static PressureChangeRate FromMillibarsPerSecond(double value) /// /// Creates a from . /// - public static PressureChangeRate FromMillimetersOfMercuryPerSecond(double value) + public static PressureChangeRate FromMillimetersOfMercuryPerSecond(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.MillimeterOfMercuryPerSecond); } @@ -529,7 +511,7 @@ public static PressureChangeRate FromMillimetersOfMercuryPerSecond(double value) /// /// Creates a from . /// - public static PressureChangeRate FromPascalsPerMinute(double value) + public static PressureChangeRate FromPascalsPerMinute(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.PascalPerMinute); } @@ -537,7 +519,7 @@ public static PressureChangeRate FromPascalsPerMinute(double value) /// /// Creates a from . /// - public static PressureChangeRate FromPascalsPerSecond(double value) + public static PressureChangeRate FromPascalsPerSecond(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.PascalPerSecond); } @@ -545,7 +527,7 @@ public static PressureChangeRate FromPascalsPerSecond(double value) /// /// Creates a from . /// - public static PressureChangeRate FromPoundsForcePerSquareInchPerMinute(double value) + public static PressureChangeRate FromPoundsForcePerSquareInchPerMinute(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.PoundForcePerSquareInchPerMinute); } @@ -553,7 +535,7 @@ public static PressureChangeRate FromPoundsForcePerSquareInchPerMinute(double va /// /// Creates a from . /// - public static PressureChangeRate FromPoundsForcePerSquareInchPerSecond(double value) + public static PressureChangeRate FromPoundsForcePerSquareInchPerSecond(QuantityValue value) { return new PressureChangeRate(value, PressureChangeRateUnit.PoundForcePerSquareInchPerSecond); } @@ -564,7 +546,7 @@ public static PressureChangeRate FromPoundsForcePerSquareInchPerSecond(double va /// Value to convert from. /// Unit to convert from. /// PressureChangeRate unit value. - public static PressureChangeRate From(double value, PressureChangeRateUnit fromUnit) + public static PressureChangeRate From(QuantityValue value, PressureChangeRateUnit fromUnit) { return new PressureChangeRate(value, fromUnit); } @@ -625,10 +607,7 @@ public static PressureChangeRate Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static PressureChangeRate Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -656,11 +635,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out PressureChangeRa /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out PressureChangeRate result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -681,7 +656,7 @@ public static PressureChangeRateUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -692,7 +667,7 @@ public static PressureChangeRateUnit ParseUnit(string str, IFormatProvider? prov return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out PressureChangeRateUnit unit) { return TryParseUnit(str, null, out unit); @@ -707,7 +682,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out PressureChan /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out PressureChangeRateUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -726,35 +701,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static PressureChangeRate operator +(PressureChangeRate left, PressureChangeRate right) { - return new PressureChangeRate(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new PressureChangeRate(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static PressureChangeRate operator -(PressureChangeRate left, PressureChangeRate right) { - return new PressureChangeRate(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new PressureChangeRate(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -776,97 +751,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(PressureChangeRate left, PressureChangeRate right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(PressureChangeRate left, PressureChangeRate right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(PressureChangeRate left, PressureChangeRate right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(PressureChangeRate left, PressureChangeRate right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(PressureChangeRate other, PressureChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(PressureChangeRate left, PressureChangeRate right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(PressureChangeRate other, PressureChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(PressureChangeRate left, PressureChangeRate right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(PressureChangeRate other, PressureChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is PressureChangeRate otherQuantity)) + if (obj is not PressureChangeRate otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(PressureChangeRate other, PressureChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(PressureChangeRate other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current PressureChangeRate. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(PressureChangeRate), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is PressureChangeRate otherQuantity)) throw new ArgumentException("Expected type PressureChangeRate.", nameof(obj)); + if (obj is not PressureChangeRate otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -878,180 +838,24 @@ public int CompareTo(object? obj) /// public int CompareTo(PressureChangeRate other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(PressureChangeRateUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this PressureChangeRate to another PressureChangeRate with the unit representation . - /// - /// The unit to convert to. - /// A PressureChangeRate with the specified unit. - public PressureChangeRate ToUnit(PressureChangeRateUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A PressureChangeRate with the specified unit. - public PressureChangeRate ToUnit(PressureChangeRateUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(PressureChangeRate), Unit, typeof(PressureChangeRate), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (PressureChangeRate)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(PressureChangeRateUnit unit, [NotNullWhen(true)] out PressureChangeRate? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - PressureChangeRate? convertedOrNull = (Unit, unit) switch - { - // PressureChangeRateUnit -> BaseUnit - (PressureChangeRateUnit.AtmospherePerSecond, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate(_value * 1.01325 * 1e5, PressureChangeRateUnit.PascalPerSecond), - (PressureChangeRateUnit.BarPerMinute, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate(_value * 1e5 / 60, PressureChangeRateUnit.PascalPerSecond), - (PressureChangeRateUnit.BarPerSecond, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate(_value * 1e5, PressureChangeRateUnit.PascalPerSecond), - (PressureChangeRateUnit.KilopascalPerMinute, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value / 60) * 1e3d, PressureChangeRateUnit.PascalPerSecond), - (PressureChangeRateUnit.KilopascalPerSecond, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value) * 1e3d, PressureChangeRateUnit.PascalPerSecond), - (PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value * (4.4482216152605 / 0.00064516) / 60) * 1e3d, PressureChangeRateUnit.PascalPerSecond), - (PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value * 4.4482216152605 / 0.00064516) * 1e3d, PressureChangeRateUnit.PascalPerSecond), - (PressureChangeRateUnit.MegapascalPerMinute, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value / 60) * 1e6d, PressureChangeRateUnit.PascalPerSecond), - (PressureChangeRateUnit.MegapascalPerSecond, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value) * 1e6d, PressureChangeRateUnit.PascalPerSecond), - (PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value * (4.4482216152605 / 0.00064516) / 60) * 1e6d, PressureChangeRateUnit.PascalPerSecond), - (PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value * 4.4482216152605 / 0.00064516) * 1e6d, PressureChangeRateUnit.PascalPerSecond), - (PressureChangeRateUnit.MillibarPerMinute, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value * 1e5 / 60) * 1e-3d, PressureChangeRateUnit.PascalPerSecond), - (PressureChangeRateUnit.MillibarPerSecond, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate((_value * 1e5) * 1e-3d, PressureChangeRateUnit.PascalPerSecond), - (PressureChangeRateUnit.MillimeterOfMercuryPerSecond, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate(_value * 133.322387415, PressureChangeRateUnit.PascalPerSecond), - (PressureChangeRateUnit.PascalPerMinute, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate(_value / 60, PressureChangeRateUnit.PascalPerSecond), - (PressureChangeRateUnit.PoundForcePerSquareInchPerMinute, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate(_value * (4.4482216152605 / 0.00064516) / 60, PressureChangeRateUnit.PascalPerSecond), - (PressureChangeRateUnit.PoundForcePerSquareInchPerSecond, PressureChangeRateUnit.PascalPerSecond) => new PressureChangeRate(_value * 4.4482216152605 / 0.00064516, PressureChangeRateUnit.PascalPerSecond), - - // BaseUnit -> PressureChangeRateUnit - (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.AtmospherePerSecond) => new PressureChangeRate(_value / (1.01325 * 1e5), PressureChangeRateUnit.AtmospherePerSecond), - (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.BarPerMinute) => new PressureChangeRate(_value / 1e5 * 60, PressureChangeRateUnit.BarPerMinute), - (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.BarPerSecond) => new PressureChangeRate(_value / 1e5, PressureChangeRateUnit.BarPerSecond), - (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopascalPerMinute) => new PressureChangeRate((_value * 60) / 1e3d, PressureChangeRateUnit.KilopascalPerMinute), - (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopascalPerSecond) => new PressureChangeRate((_value) / 1e3d, PressureChangeRateUnit.KilopascalPerSecond), - (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute) => new PressureChangeRate((_value * 60 / (4.4482216152605 / 0.00064516)) / 1e3d, PressureChangeRateUnit.KilopoundForcePerSquareInchPerMinute), - (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond) => new PressureChangeRate((_value * 0.00064516 / 4.4482216152605) / 1e3d, PressureChangeRateUnit.KilopoundForcePerSquareInchPerSecond), - (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapascalPerMinute) => new PressureChangeRate((_value * 60) / 1e6d, PressureChangeRateUnit.MegapascalPerMinute), - (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapascalPerSecond) => new PressureChangeRate((_value) / 1e6d, PressureChangeRateUnit.MegapascalPerSecond), - (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute) => new PressureChangeRate((_value * 60 / (4.4482216152605 / 0.00064516)) / 1e6d, PressureChangeRateUnit.MegapoundForcePerSquareInchPerMinute), - (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond) => new PressureChangeRate((_value * 0.00064516 / 4.4482216152605) / 1e6d, PressureChangeRateUnit.MegapoundForcePerSquareInchPerSecond), - (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MillibarPerMinute) => new PressureChangeRate((_value / 1e5 * 60) / 1e-3d, PressureChangeRateUnit.MillibarPerMinute), - (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MillibarPerSecond) => new PressureChangeRate((_value / 1e5) / 1e-3d, PressureChangeRateUnit.MillibarPerSecond), - (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.MillimeterOfMercuryPerSecond) => new PressureChangeRate(_value / 133.322387415, PressureChangeRateUnit.MillimeterOfMercuryPerSecond), - (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PascalPerMinute) => new PressureChangeRate(_value * 60, PressureChangeRateUnit.PascalPerMinute), - (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PoundForcePerSquareInchPerMinute) => new PressureChangeRate(_value * 60 / (4.4482216152605 / 0.00064516), PressureChangeRateUnit.PoundForcePerSquareInchPerMinute), - (PressureChangeRateUnit.PascalPerSecond, PressureChangeRateUnit.PoundForcePerSquareInchPerSecond) => new PressureChangeRate(_value * 0.00064516 / 4.4482216152605, PressureChangeRateUnit.PoundForcePerSquareInchPerSecond), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public PressureChangeRate ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not PressureChangeRateUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(PressureChangeRateUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(PressureChangeRateUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(PressureChangeRateUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1066,7 +870,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/RadiationEquivalentDose.g.cs b/UnitsNet/GeneratedCode/Quantities/RadiationEquivalentDose.g.cs index deffb18848..6d9fee1bb6 100644 --- a/UnitsNet/GeneratedCode/Quantities/RadiationEquivalentDose.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RadiationEquivalentDose.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// Equivalent dose is a dose quantity representing the stochastic health effects of low levels of ionizing radiation on the human body which represents the probability of radiation-induced cancer and genetic damage. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct RadiationEquivalentDose : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -54,13 +53,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly RadiationEquivalentDoseUnit? _unit; /// @@ -105,7 +104,7 @@ public static RadiationEquivalentDoseInfo CreateDefault(Func - /// The for is [T^-2][L^2]. + /// The for is T^-2L^2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, -2, 0, 0, 0, 0); @@ -120,20 +119,28 @@ public static RadiationEquivalentDoseInfo CreateDefault(FuncAn of representing the default unit mappings for RadiationEquivalentDose. public static IEnumerable> GetDefaultMappings() { - yield return new (RadiationEquivalentDoseUnit.Microsievert, "Microsievert", "Microsieverts", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second)); - yield return new (RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan, "MilliroentgenEquivalentMan", "MilliroentgensEquivalentMan", BaseUnits.Undefined); - yield return new (RadiationEquivalentDoseUnit.Millisievert, "Millisievert", "Millisieverts", BaseUnits.Undefined); - yield return new (RadiationEquivalentDoseUnit.Nanosievert, "Nanosievert", "Nanosieverts", BaseUnits.Undefined); - yield return new (RadiationEquivalentDoseUnit.RoentgenEquivalentMan, "RoentgenEquivalentMan", "RoentgensEquivalentMan", BaseUnits.Undefined); + yield return new (RadiationEquivalentDoseUnit.Microsievert, "Microsievert", "Microsieverts", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second), + 1000000 + ); + yield return new (RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan, "MilliroentgenEquivalentMan", "MilliroentgensEquivalentMan", BaseUnits.Undefined, + 100000 + ); + yield return new (RadiationEquivalentDoseUnit.Millisievert, "Millisievert", "Millisieverts", BaseUnits.Undefined, + 1000 + ); + yield return new (RadiationEquivalentDoseUnit.Nanosievert, "Nanosievert", "Nanosieverts", BaseUnits.Undefined, + 1000000000 + ); + yield return new (RadiationEquivalentDoseUnit.RoentgenEquivalentMan, "RoentgenEquivalentMan", "RoentgensEquivalentMan", BaseUnits.Undefined, + 100 + ); yield return new (RadiationEquivalentDoseUnit.Sievert, "Sievert", "Sieverts", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)); } } static RadiationEquivalentDose() { - Info = RadiationEquivalentDoseInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(RadiationEquivalentDoseInfo.CreateDefault); } /// @@ -141,7 +148,7 @@ static RadiationEquivalentDose() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public RadiationEquivalentDose(double value, RadiationEquivalentDoseUnit unit) + public RadiationEquivalentDose(QuantityValue value, RadiationEquivalentDoseUnit unit) { _value = value; _unit = unit; @@ -155,7 +162,7 @@ public RadiationEquivalentDose(double value, RadiationEquivalentDoseUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public RadiationEquivalentDose(double value, UnitSystem unitSystem) + public RadiationEquivalentDose(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -166,7 +173,8 @@ public RadiationEquivalentDose(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -195,10 +203,8 @@ public RadiationEquivalentDose(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public RadiationEquivalentDoseUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -237,63 +243,39 @@ public RadiationEquivalentDose(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microsieverts => As(RadiationEquivalentDoseUnit.Microsievert); + public QuantityValue Microsieverts => this.As(RadiationEquivalentDoseUnit.Microsievert); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliroentgensEquivalentMan => As(RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan); + public QuantityValue MilliroentgensEquivalentMan => this.As(RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millisieverts => As(RadiationEquivalentDoseUnit.Millisievert); + public QuantityValue Millisieverts => this.As(RadiationEquivalentDoseUnit.Millisievert); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanosieverts => As(RadiationEquivalentDoseUnit.Nanosievert); + public QuantityValue Nanosieverts => this.As(RadiationEquivalentDoseUnit.Nanosievert); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double RoentgensEquivalentMan => As(RadiationEquivalentDoseUnit.RoentgenEquivalentMan); + public QuantityValue RoentgensEquivalentMan => this.As(RadiationEquivalentDoseUnit.RoentgenEquivalentMan); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Sieverts => As(RadiationEquivalentDoseUnit.Sievert); + public QuantityValue Sieverts => this.As(RadiationEquivalentDoseUnit.Sievert); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: RadiationEquivalentDoseUnit -> BaseUnit - unitConverter.SetConversionFunction(RadiationEquivalentDoseUnit.Microsievert, RadiationEquivalentDoseUnit.Sievert, quantity => quantity.ToUnit(RadiationEquivalentDoseUnit.Sievert)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan, RadiationEquivalentDoseUnit.Sievert, quantity => quantity.ToUnit(RadiationEquivalentDoseUnit.Sievert)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseUnit.Millisievert, RadiationEquivalentDoseUnit.Sievert, quantity => quantity.ToUnit(RadiationEquivalentDoseUnit.Sievert)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseUnit.Nanosievert, RadiationEquivalentDoseUnit.Sievert, quantity => quantity.ToUnit(RadiationEquivalentDoseUnit.Sievert)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseUnit.RoentgenEquivalentMan, RadiationEquivalentDoseUnit.Sievert, quantity => quantity.ToUnit(RadiationEquivalentDoseUnit.Sievert)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(RadiationEquivalentDoseUnit.Sievert, RadiationEquivalentDoseUnit.Sievert, quantity => quantity); - - // Register in unit converter: BaseUnit -> RadiationEquivalentDoseUnit - unitConverter.SetConversionFunction(RadiationEquivalentDoseUnit.Sievert, RadiationEquivalentDoseUnit.Microsievert, quantity => quantity.ToUnit(RadiationEquivalentDoseUnit.Microsievert)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseUnit.Sievert, RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan, quantity => quantity.ToUnit(RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseUnit.Sievert, RadiationEquivalentDoseUnit.Millisievert, quantity => quantity.ToUnit(RadiationEquivalentDoseUnit.Millisievert)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseUnit.Sievert, RadiationEquivalentDoseUnit.Nanosievert, quantity => quantity.ToUnit(RadiationEquivalentDoseUnit.Nanosievert)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseUnit.Sievert, RadiationEquivalentDoseUnit.RoentgenEquivalentMan, quantity => quantity.ToUnit(RadiationEquivalentDoseUnit.RoentgenEquivalentMan)); - } - /// /// Get unit abbreviation string. /// @@ -322,7 +304,7 @@ public static string GetAbbreviation(RadiationEquivalentDoseUnit unit, IFormatPr /// /// Creates a from . /// - public static RadiationEquivalentDose FromMicrosieverts(double value) + public static RadiationEquivalentDose FromMicrosieverts(QuantityValue value) { return new RadiationEquivalentDose(value, RadiationEquivalentDoseUnit.Microsievert); } @@ -330,7 +312,7 @@ public static RadiationEquivalentDose FromMicrosieverts(double value) /// /// Creates a from . /// - public static RadiationEquivalentDose FromMilliroentgensEquivalentMan(double value) + public static RadiationEquivalentDose FromMilliroentgensEquivalentMan(QuantityValue value) { return new RadiationEquivalentDose(value, RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan); } @@ -338,7 +320,7 @@ public static RadiationEquivalentDose FromMilliroentgensEquivalentMan(double val /// /// Creates a from . /// - public static RadiationEquivalentDose FromMillisieverts(double value) + public static RadiationEquivalentDose FromMillisieverts(QuantityValue value) { return new RadiationEquivalentDose(value, RadiationEquivalentDoseUnit.Millisievert); } @@ -346,7 +328,7 @@ public static RadiationEquivalentDose FromMillisieverts(double value) /// /// Creates a from . /// - public static RadiationEquivalentDose FromNanosieverts(double value) + public static RadiationEquivalentDose FromNanosieverts(QuantityValue value) { return new RadiationEquivalentDose(value, RadiationEquivalentDoseUnit.Nanosievert); } @@ -354,7 +336,7 @@ public static RadiationEquivalentDose FromNanosieverts(double value) /// /// Creates a from . /// - public static RadiationEquivalentDose FromRoentgensEquivalentMan(double value) + public static RadiationEquivalentDose FromRoentgensEquivalentMan(QuantityValue value) { return new RadiationEquivalentDose(value, RadiationEquivalentDoseUnit.RoentgenEquivalentMan); } @@ -362,7 +344,7 @@ public static RadiationEquivalentDose FromRoentgensEquivalentMan(double value) /// /// Creates a from . /// - public static RadiationEquivalentDose FromSieverts(double value) + public static RadiationEquivalentDose FromSieverts(QuantityValue value) { return new RadiationEquivalentDose(value, RadiationEquivalentDoseUnit.Sievert); } @@ -373,7 +355,7 @@ public static RadiationEquivalentDose FromSieverts(double value) /// Value to convert from. /// Unit to convert from. /// RadiationEquivalentDose unit value. - public static RadiationEquivalentDose From(double value, RadiationEquivalentDoseUnit fromUnit) + public static RadiationEquivalentDose From(QuantityValue value, RadiationEquivalentDoseUnit fromUnit) { return new RadiationEquivalentDose(value, fromUnit); } @@ -434,10 +416,7 @@ public static RadiationEquivalentDose Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static RadiationEquivalentDose Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -465,11 +444,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out RadiationEquival /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out RadiationEquivalentDose result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -490,7 +465,7 @@ public static RadiationEquivalentDoseUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -501,7 +476,7 @@ public static RadiationEquivalentDoseUnit ParseUnit(string str, IFormatProvider? return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out RadiationEquivalentDoseUnit unit) { return TryParseUnit(str, null, out unit); @@ -516,7 +491,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out RadiationEqu /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out RadiationEquivalentDoseUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -535,35 +510,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static RadiationEquivalentDose operator +(RadiationEquivalentDose left, RadiationEquivalentDose right) { - return new RadiationEquivalentDose(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new RadiationEquivalentDose(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static RadiationEquivalentDose operator -(RadiationEquivalentDose left, RadiationEquivalentDose right) { - return new RadiationEquivalentDose(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new RadiationEquivalentDose(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static RadiationEquivalentDose operator *(double left, RadiationEquivalentDose right) + public static RadiationEquivalentDose operator *(QuantityValue left, RadiationEquivalentDose right) { return new RadiationEquivalentDose(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static RadiationEquivalentDose operator *(RadiationEquivalentDose left, double right) + public static RadiationEquivalentDose operator *(RadiationEquivalentDose left, QuantityValue right) { return new RadiationEquivalentDose(left.Value * right, left.Unit); } /// Get from dividing by value. - public static RadiationEquivalentDose operator /(RadiationEquivalentDose left, double right) + public static RadiationEquivalentDose operator /(RadiationEquivalentDose left, QuantityValue right) { return new RadiationEquivalentDose(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(RadiationEquivalentDose left, RadiationEquivalentDose right) + public static QuantityValue operator /(RadiationEquivalentDose left, RadiationEquivalentDose right) { return left.Sieverts / right.Sieverts; } @@ -591,97 +566,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(RadiationEquivalentDose left, RadiationEquivalentDose right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(RadiationEquivalentDose left, RadiationEquivalentDose right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(RadiationEquivalentDose left, RadiationEquivalentDose right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(RadiationEquivalentDose left, RadiationEquivalentDose right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RadiationEquivalentDose other, RadiationEquivalentDose tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(RadiationEquivalentDose left, RadiationEquivalentDose right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RadiationEquivalentDose other, RadiationEquivalentDose tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(RadiationEquivalentDose left, RadiationEquivalentDose right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RadiationEquivalentDose other, RadiationEquivalentDose tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is RadiationEquivalentDose otherQuantity)) + if (obj is not RadiationEquivalentDose otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RadiationEquivalentDose other, RadiationEquivalentDose tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(RadiationEquivalentDose other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current RadiationEquivalentDose. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(RadiationEquivalentDose), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is RadiationEquivalentDose otherQuantity)) throw new ArgumentException("Expected type RadiationEquivalentDose.", nameof(obj)); + if (obj is not RadiationEquivalentDose otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -693,156 +653,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RadiationEquivalentDose other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RadiationEquivalentDoseUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this RadiationEquivalentDose to another RadiationEquivalentDose with the unit representation . - /// - /// The unit to convert to. - /// A RadiationEquivalentDose with the specified unit. - public RadiationEquivalentDose ToUnit(RadiationEquivalentDoseUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A RadiationEquivalentDose with the specified unit. - public RadiationEquivalentDose ToUnit(RadiationEquivalentDoseUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(RadiationEquivalentDose), Unit, typeof(RadiationEquivalentDose), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (RadiationEquivalentDose)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(RadiationEquivalentDoseUnit unit, [NotNullWhen(true)] out RadiationEquivalentDose? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - RadiationEquivalentDose? convertedOrNull = (Unit, unit) switch - { - // RadiationEquivalentDoseUnit -> BaseUnit - (RadiationEquivalentDoseUnit.Microsievert, RadiationEquivalentDoseUnit.Sievert) => new RadiationEquivalentDose((_value) * 1e-6d, RadiationEquivalentDoseUnit.Sievert), - (RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan, RadiationEquivalentDoseUnit.Sievert) => new RadiationEquivalentDose((_value / 100) * 1e-3d, RadiationEquivalentDoseUnit.Sievert), - (RadiationEquivalentDoseUnit.Millisievert, RadiationEquivalentDoseUnit.Sievert) => new RadiationEquivalentDose((_value) * 1e-3d, RadiationEquivalentDoseUnit.Sievert), - (RadiationEquivalentDoseUnit.Nanosievert, RadiationEquivalentDoseUnit.Sievert) => new RadiationEquivalentDose((_value) * 1e-9d, RadiationEquivalentDoseUnit.Sievert), - (RadiationEquivalentDoseUnit.RoentgenEquivalentMan, RadiationEquivalentDoseUnit.Sievert) => new RadiationEquivalentDose(_value / 100, RadiationEquivalentDoseUnit.Sievert), - - // BaseUnit -> RadiationEquivalentDoseUnit - (RadiationEquivalentDoseUnit.Sievert, RadiationEquivalentDoseUnit.Microsievert) => new RadiationEquivalentDose((_value) / 1e-6d, RadiationEquivalentDoseUnit.Microsievert), - (RadiationEquivalentDoseUnit.Sievert, RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan) => new RadiationEquivalentDose((_value * 100) / 1e-3d, RadiationEquivalentDoseUnit.MilliroentgenEquivalentMan), - (RadiationEquivalentDoseUnit.Sievert, RadiationEquivalentDoseUnit.Millisievert) => new RadiationEquivalentDose((_value) / 1e-3d, RadiationEquivalentDoseUnit.Millisievert), - (RadiationEquivalentDoseUnit.Sievert, RadiationEquivalentDoseUnit.Nanosievert) => new RadiationEquivalentDose((_value) / 1e-9d, RadiationEquivalentDoseUnit.Nanosievert), - (RadiationEquivalentDoseUnit.Sievert, RadiationEquivalentDoseUnit.RoentgenEquivalentMan) => new RadiationEquivalentDose(_value * 100, RadiationEquivalentDoseUnit.RoentgenEquivalentMan), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public RadiationEquivalentDose ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not RadiationEquivalentDoseUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RadiationEquivalentDoseUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is RadiationEquivalentDoseUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RadiationEquivalentDoseUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(RadiationEquivalentDoseUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(RadiationEquivalentDoseUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -857,7 +685,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/RadiationEquivalentDoseRate.g.cs b/UnitsNet/GeneratedCode/Quantities/RadiationEquivalentDoseRate.g.cs index a87acf0ce1..b49b48e0b2 100644 --- a/UnitsNet/GeneratedCode/Quantities/RadiationEquivalentDoseRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RadiationEquivalentDoseRate.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// A dose rate is quantity of radiation absorbed or delivered per unit time. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct RadiationEquivalentDoseRate : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly RadiationEquivalentDoseRateUnit? _unit; /// @@ -104,7 +103,7 @@ public static RadiationEquivalentDoseRateInfo CreateDefault(Func - /// The for is [T^-3][L^2]. + /// The for is T^-3L^2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, -3, 0, 0, 0, 0); @@ -119,24 +118,40 @@ public static RadiationEquivalentDoseRateInfo CreateDefault(FuncAn of representing the default unit mappings for RadiationEquivalentDoseRate. public static IEnumerable> GetDefaultMappings() { - yield return new (RadiationEquivalentDoseRateUnit.MicrosievertPerHour, "MicrosievertPerHour", "MicrosievertsPerHour", BaseUnits.Undefined); - yield return new (RadiationEquivalentDoseRateUnit.MicrosievertPerSecond, "MicrosievertPerSecond", "MicrosievertsPerSecond", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second)); - yield return new (RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour, "MilliroentgenEquivalentManPerHour", "MilliroentgensEquivalentManPerHour", BaseUnits.Undefined); - yield return new (RadiationEquivalentDoseRateUnit.MillisievertPerHour, "MillisievertPerHour", "MillisievertsPerHour", BaseUnits.Undefined); - yield return new (RadiationEquivalentDoseRateUnit.MillisievertPerSecond, "MillisievertPerSecond", "MillisievertsPerSecond", BaseUnits.Undefined); - yield return new (RadiationEquivalentDoseRateUnit.NanosievertPerHour, "NanosievertPerHour", "NanosievertsPerHour", BaseUnits.Undefined); - yield return new (RadiationEquivalentDoseRateUnit.NanosievertPerSecond, "NanosievertPerSecond", "NanosievertsPerSecond", BaseUnits.Undefined); - yield return new (RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour, "RoentgenEquivalentManPerHour", "RoentgensEquivalentManPerHour", BaseUnits.Undefined); - yield return new (RadiationEquivalentDoseRateUnit.SievertPerHour, "SievertPerHour", "SievertsPerHour", BaseUnits.Undefined); + yield return new (RadiationEquivalentDoseRateUnit.MicrosievertPerHour, "MicrosievertPerHour", "MicrosievertsPerHour", BaseUnits.Undefined, + 3600000000 + ); + yield return new (RadiationEquivalentDoseRateUnit.MicrosievertPerSecond, "MicrosievertPerSecond", "MicrosievertsPerSecond", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second), + 1000000 + ); + yield return new (RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour, "MilliroentgenEquivalentManPerHour", "MilliroentgensEquivalentManPerHour", BaseUnits.Undefined, + 360000000 + ); + yield return new (RadiationEquivalentDoseRateUnit.MillisievertPerHour, "MillisievertPerHour", "MillisievertsPerHour", BaseUnits.Undefined, + 3600000 + ); + yield return new (RadiationEquivalentDoseRateUnit.MillisievertPerSecond, "MillisievertPerSecond", "MillisievertsPerSecond", BaseUnits.Undefined, + 1000 + ); + yield return new (RadiationEquivalentDoseRateUnit.NanosievertPerHour, "NanosievertPerHour", "NanosievertsPerHour", BaseUnits.Undefined, + 3600000000000 + ); + yield return new (RadiationEquivalentDoseRateUnit.NanosievertPerSecond, "NanosievertPerSecond", "NanosievertsPerSecond", BaseUnits.Undefined, + 1000000000 + ); + yield return new (RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour, "RoentgenEquivalentManPerHour", "RoentgensEquivalentManPerHour", BaseUnits.Undefined, + 360000 + ); + yield return new (RadiationEquivalentDoseRateUnit.SievertPerHour, "SievertPerHour", "SievertsPerHour", BaseUnits.Undefined, + 3600 + ); yield return new (RadiationEquivalentDoseRateUnit.SievertPerSecond, "SievertPerSecond", "SievertsPerSecond", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)); } } static RadiationEquivalentDoseRate() { - Info = RadiationEquivalentDoseRateInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(RadiationEquivalentDoseRateInfo.CreateDefault); } /// @@ -144,7 +159,7 @@ static RadiationEquivalentDoseRate() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public RadiationEquivalentDoseRate(double value, RadiationEquivalentDoseRateUnit unit) + public RadiationEquivalentDoseRate(QuantityValue value, RadiationEquivalentDoseRateUnit unit) { _value = value; _unit = unit; @@ -158,7 +173,7 @@ public RadiationEquivalentDoseRate(double value, RadiationEquivalentDoseRateUnit /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public RadiationEquivalentDoseRate(double value, UnitSystem unitSystem) + public RadiationEquivalentDoseRate(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -169,7 +184,8 @@ public RadiationEquivalentDoseRate(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -198,10 +214,8 @@ public RadiationEquivalentDoseRate(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public RadiationEquivalentDoseRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -240,91 +254,59 @@ public RadiationEquivalentDoseRate(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrosievertsPerHour => As(RadiationEquivalentDoseRateUnit.MicrosievertPerHour); + public QuantityValue MicrosievertsPerHour => this.As(RadiationEquivalentDoseRateUnit.MicrosievertPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrosievertsPerSecond => As(RadiationEquivalentDoseRateUnit.MicrosievertPerSecond); + public QuantityValue MicrosievertsPerSecond => this.As(RadiationEquivalentDoseRateUnit.MicrosievertPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliroentgensEquivalentManPerHour => As(RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour); + public QuantityValue MilliroentgensEquivalentManPerHour => this.As(RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillisievertsPerHour => As(RadiationEquivalentDoseRateUnit.MillisievertPerHour); + public QuantityValue MillisievertsPerHour => this.As(RadiationEquivalentDoseRateUnit.MillisievertPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillisievertsPerSecond => As(RadiationEquivalentDoseRateUnit.MillisievertPerSecond); + public QuantityValue MillisievertsPerSecond => this.As(RadiationEquivalentDoseRateUnit.MillisievertPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanosievertsPerHour => As(RadiationEquivalentDoseRateUnit.NanosievertPerHour); + public QuantityValue NanosievertsPerHour => this.As(RadiationEquivalentDoseRateUnit.NanosievertPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanosievertsPerSecond => As(RadiationEquivalentDoseRateUnit.NanosievertPerSecond); + public QuantityValue NanosievertsPerSecond => this.As(RadiationEquivalentDoseRateUnit.NanosievertPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double RoentgensEquivalentManPerHour => As(RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour); + public QuantityValue RoentgensEquivalentManPerHour => this.As(RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SievertsPerHour => As(RadiationEquivalentDoseRateUnit.SievertPerHour); + public QuantityValue SievertsPerHour => this.As(RadiationEquivalentDoseRateUnit.SievertPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SievertsPerSecond => As(RadiationEquivalentDoseRateUnit.SievertPerSecond); + public QuantityValue SievertsPerSecond => this.As(RadiationEquivalentDoseRateUnit.SievertPerSecond); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: RadiationEquivalentDoseRateUnit -> BaseUnit - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.MicrosievertPerHour, RadiationEquivalentDoseRateUnit.SievertPerSecond, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.SievertPerSecond)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.MicrosievertPerSecond, RadiationEquivalentDoseRateUnit.SievertPerSecond, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.SievertPerSecond)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour, RadiationEquivalentDoseRateUnit.SievertPerSecond, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.SievertPerSecond)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.MillisievertPerHour, RadiationEquivalentDoseRateUnit.SievertPerSecond, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.SievertPerSecond)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.MillisievertPerSecond, RadiationEquivalentDoseRateUnit.SievertPerSecond, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.SievertPerSecond)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.NanosievertPerHour, RadiationEquivalentDoseRateUnit.SievertPerSecond, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.SievertPerSecond)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.NanosievertPerSecond, RadiationEquivalentDoseRateUnit.SievertPerSecond, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.SievertPerSecond)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour, RadiationEquivalentDoseRateUnit.SievertPerSecond, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.SievertPerSecond)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.SievertPerHour, RadiationEquivalentDoseRateUnit.SievertPerSecond, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.SievertPerSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.SievertPerSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> RadiationEquivalentDoseRateUnit - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.MicrosievertPerHour, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.MicrosievertPerHour)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.MicrosievertPerSecond, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.MicrosievertPerSecond)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.MillisievertPerHour, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.MillisievertPerHour)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.MillisievertPerSecond, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.MillisievertPerSecond)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.NanosievertPerHour, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.NanosievertPerHour)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.NanosievertPerSecond, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.NanosievertPerSecond)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour)); - unitConverter.SetConversionFunction(RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.SievertPerHour, quantity => quantity.ToUnit(RadiationEquivalentDoseRateUnit.SievertPerHour)); - } - /// /// Get unit abbreviation string. /// @@ -353,7 +335,7 @@ public static string GetAbbreviation(RadiationEquivalentDoseRateUnit unit, IForm /// /// Creates a from . /// - public static RadiationEquivalentDoseRate FromMicrosievertsPerHour(double value) + public static RadiationEquivalentDoseRate FromMicrosievertsPerHour(QuantityValue value) { return new RadiationEquivalentDoseRate(value, RadiationEquivalentDoseRateUnit.MicrosievertPerHour); } @@ -361,7 +343,7 @@ public static RadiationEquivalentDoseRate FromMicrosievertsPerHour(double value) /// /// Creates a from . /// - public static RadiationEquivalentDoseRate FromMicrosievertsPerSecond(double value) + public static RadiationEquivalentDoseRate FromMicrosievertsPerSecond(QuantityValue value) { return new RadiationEquivalentDoseRate(value, RadiationEquivalentDoseRateUnit.MicrosievertPerSecond); } @@ -369,7 +351,7 @@ public static RadiationEquivalentDoseRate FromMicrosievertsPerSecond(double valu /// /// Creates a from . /// - public static RadiationEquivalentDoseRate FromMilliroentgensEquivalentManPerHour(double value) + public static RadiationEquivalentDoseRate FromMilliroentgensEquivalentManPerHour(QuantityValue value) { return new RadiationEquivalentDoseRate(value, RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour); } @@ -377,7 +359,7 @@ public static RadiationEquivalentDoseRate FromMilliroentgensEquivalentManPerHour /// /// Creates a from . /// - public static RadiationEquivalentDoseRate FromMillisievertsPerHour(double value) + public static RadiationEquivalentDoseRate FromMillisievertsPerHour(QuantityValue value) { return new RadiationEquivalentDoseRate(value, RadiationEquivalentDoseRateUnit.MillisievertPerHour); } @@ -385,7 +367,7 @@ public static RadiationEquivalentDoseRate FromMillisievertsPerHour(double value) /// /// Creates a from . /// - public static RadiationEquivalentDoseRate FromMillisievertsPerSecond(double value) + public static RadiationEquivalentDoseRate FromMillisievertsPerSecond(QuantityValue value) { return new RadiationEquivalentDoseRate(value, RadiationEquivalentDoseRateUnit.MillisievertPerSecond); } @@ -393,7 +375,7 @@ public static RadiationEquivalentDoseRate FromMillisievertsPerSecond(double valu /// /// Creates a from . /// - public static RadiationEquivalentDoseRate FromNanosievertsPerHour(double value) + public static RadiationEquivalentDoseRate FromNanosievertsPerHour(QuantityValue value) { return new RadiationEquivalentDoseRate(value, RadiationEquivalentDoseRateUnit.NanosievertPerHour); } @@ -401,7 +383,7 @@ public static RadiationEquivalentDoseRate FromNanosievertsPerHour(double value) /// /// Creates a from . /// - public static RadiationEquivalentDoseRate FromNanosievertsPerSecond(double value) + public static RadiationEquivalentDoseRate FromNanosievertsPerSecond(QuantityValue value) { return new RadiationEquivalentDoseRate(value, RadiationEquivalentDoseRateUnit.NanosievertPerSecond); } @@ -409,7 +391,7 @@ public static RadiationEquivalentDoseRate FromNanosievertsPerSecond(double value /// /// Creates a from . /// - public static RadiationEquivalentDoseRate FromRoentgensEquivalentManPerHour(double value) + public static RadiationEquivalentDoseRate FromRoentgensEquivalentManPerHour(QuantityValue value) { return new RadiationEquivalentDoseRate(value, RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour); } @@ -417,7 +399,7 @@ public static RadiationEquivalentDoseRate FromRoentgensEquivalentManPerHour(doub /// /// Creates a from . /// - public static RadiationEquivalentDoseRate FromSievertsPerHour(double value) + public static RadiationEquivalentDoseRate FromSievertsPerHour(QuantityValue value) { return new RadiationEquivalentDoseRate(value, RadiationEquivalentDoseRateUnit.SievertPerHour); } @@ -425,7 +407,7 @@ public static RadiationEquivalentDoseRate FromSievertsPerHour(double value) /// /// Creates a from . /// - public static RadiationEquivalentDoseRate FromSievertsPerSecond(double value) + public static RadiationEquivalentDoseRate FromSievertsPerSecond(QuantityValue value) { return new RadiationEquivalentDoseRate(value, RadiationEquivalentDoseRateUnit.SievertPerSecond); } @@ -436,7 +418,7 @@ public static RadiationEquivalentDoseRate FromSievertsPerSecond(double value) /// Value to convert from. /// Unit to convert from. /// RadiationEquivalentDoseRate unit value. - public static RadiationEquivalentDoseRate From(double value, RadiationEquivalentDoseRateUnit fromUnit) + public static RadiationEquivalentDoseRate From(QuantityValue value, RadiationEquivalentDoseRateUnit fromUnit) { return new RadiationEquivalentDoseRate(value, fromUnit); } @@ -497,10 +479,7 @@ public static RadiationEquivalentDoseRate Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static RadiationEquivalentDoseRate Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -528,11 +507,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out RadiationEquival /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out RadiationEquivalentDoseRate result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -553,7 +528,7 @@ public static RadiationEquivalentDoseRateUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -564,7 +539,7 @@ public static RadiationEquivalentDoseRateUnit ParseUnit(string str, IFormatProvi return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out RadiationEquivalentDoseRateUnit unit) { return TryParseUnit(str, null, out unit); @@ -579,7 +554,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out RadiationEqu /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out RadiationEquivalentDoseRateUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -598,35 +573,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static RadiationEquivalentDoseRate operator +(RadiationEquivalentDoseRate left, RadiationEquivalentDoseRate right) { - return new RadiationEquivalentDoseRate(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new RadiationEquivalentDoseRate(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static RadiationEquivalentDoseRate operator -(RadiationEquivalentDoseRate left, RadiationEquivalentDoseRate right) { - return new RadiationEquivalentDoseRate(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new RadiationEquivalentDoseRate(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static RadiationEquivalentDoseRate operator *(double left, RadiationEquivalentDoseRate right) + public static RadiationEquivalentDoseRate operator *(QuantityValue left, RadiationEquivalentDoseRate right) { return new RadiationEquivalentDoseRate(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static RadiationEquivalentDoseRate operator *(RadiationEquivalentDoseRate left, double right) + public static RadiationEquivalentDoseRate operator *(RadiationEquivalentDoseRate left, QuantityValue right) { return new RadiationEquivalentDoseRate(left.Value * right, left.Unit); } /// Get from dividing by value. - public static RadiationEquivalentDoseRate operator /(RadiationEquivalentDoseRate left, double right) + public static RadiationEquivalentDoseRate operator /(RadiationEquivalentDoseRate left, QuantityValue right) { return new RadiationEquivalentDoseRate(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(RadiationEquivalentDoseRate left, RadiationEquivalentDoseRate right) + public static QuantityValue operator /(RadiationEquivalentDoseRate left, RadiationEquivalentDoseRate right) { return left.SievertsPerSecond / right.SievertsPerSecond; } @@ -648,97 +623,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(RadiationEquivalentDoseRate left, RadiationEquivalentDoseRate right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(RadiationEquivalentDoseRate left, RadiationEquivalentDoseRate right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(RadiationEquivalentDoseRate left, RadiationEquivalentDoseRate right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(RadiationEquivalentDoseRate left, RadiationEquivalentDoseRate right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RadiationEquivalentDoseRate other, RadiationEquivalentDoseRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(RadiationEquivalentDoseRate left, RadiationEquivalentDoseRate right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RadiationEquivalentDoseRate other, RadiationEquivalentDoseRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(RadiationEquivalentDoseRate left, RadiationEquivalentDoseRate right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RadiationEquivalentDoseRate other, RadiationEquivalentDoseRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is RadiationEquivalentDoseRate otherQuantity)) + if (obj is not RadiationEquivalentDoseRate otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RadiationEquivalentDoseRate other, RadiationEquivalentDoseRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(RadiationEquivalentDoseRate other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current RadiationEquivalentDoseRate. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(RadiationEquivalentDoseRate), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is RadiationEquivalentDoseRate otherQuantity)) throw new ArgumentException("Expected type RadiationEquivalentDoseRate.", nameof(obj)); + if (obj is not RadiationEquivalentDoseRate otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -750,164 +710,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RadiationEquivalentDoseRate other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RadiationEquivalentDoseRateUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this RadiationEquivalentDoseRate to another RadiationEquivalentDoseRate with the unit representation . - /// - /// The unit to convert to. - /// A RadiationEquivalentDoseRate with the specified unit. - public RadiationEquivalentDoseRate ToUnit(RadiationEquivalentDoseRateUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A RadiationEquivalentDoseRate with the specified unit. - public RadiationEquivalentDoseRate ToUnit(RadiationEquivalentDoseRateUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(RadiationEquivalentDoseRate), Unit, typeof(RadiationEquivalentDoseRate), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (RadiationEquivalentDoseRate)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(RadiationEquivalentDoseRateUnit unit, [NotNullWhen(true)] out RadiationEquivalentDoseRate? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - RadiationEquivalentDoseRate? convertedOrNull = (Unit, unit) switch - { - // RadiationEquivalentDoseRateUnit -> BaseUnit - (RadiationEquivalentDoseRateUnit.MicrosievertPerHour, RadiationEquivalentDoseRateUnit.SievertPerSecond) => new RadiationEquivalentDoseRate((_value/3600) * 1e-6d, RadiationEquivalentDoseRateUnit.SievertPerSecond), - (RadiationEquivalentDoseRateUnit.MicrosievertPerSecond, RadiationEquivalentDoseRateUnit.SievertPerSecond) => new RadiationEquivalentDoseRate((_value) * 1e-6d, RadiationEquivalentDoseRateUnit.SievertPerSecond), - (RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour, RadiationEquivalentDoseRateUnit.SievertPerSecond) => new RadiationEquivalentDoseRate((_value / 100 / 3600) * 1e-3d, RadiationEquivalentDoseRateUnit.SievertPerSecond), - (RadiationEquivalentDoseRateUnit.MillisievertPerHour, RadiationEquivalentDoseRateUnit.SievertPerSecond) => new RadiationEquivalentDoseRate((_value/3600) * 1e-3d, RadiationEquivalentDoseRateUnit.SievertPerSecond), - (RadiationEquivalentDoseRateUnit.MillisievertPerSecond, RadiationEquivalentDoseRateUnit.SievertPerSecond) => new RadiationEquivalentDoseRate((_value) * 1e-3d, RadiationEquivalentDoseRateUnit.SievertPerSecond), - (RadiationEquivalentDoseRateUnit.NanosievertPerHour, RadiationEquivalentDoseRateUnit.SievertPerSecond) => new RadiationEquivalentDoseRate((_value/3600) * 1e-9d, RadiationEquivalentDoseRateUnit.SievertPerSecond), - (RadiationEquivalentDoseRateUnit.NanosievertPerSecond, RadiationEquivalentDoseRateUnit.SievertPerSecond) => new RadiationEquivalentDoseRate((_value) * 1e-9d, RadiationEquivalentDoseRateUnit.SievertPerSecond), - (RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour, RadiationEquivalentDoseRateUnit.SievertPerSecond) => new RadiationEquivalentDoseRate(_value / 100 / 3600, RadiationEquivalentDoseRateUnit.SievertPerSecond), - (RadiationEquivalentDoseRateUnit.SievertPerHour, RadiationEquivalentDoseRateUnit.SievertPerSecond) => new RadiationEquivalentDoseRate(_value/3600, RadiationEquivalentDoseRateUnit.SievertPerSecond), - - // BaseUnit -> RadiationEquivalentDoseRateUnit - (RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.MicrosievertPerHour) => new RadiationEquivalentDoseRate((_value*3600) / 1e-6d, RadiationEquivalentDoseRateUnit.MicrosievertPerHour), - (RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.MicrosievertPerSecond) => new RadiationEquivalentDoseRate((_value) / 1e-6d, RadiationEquivalentDoseRateUnit.MicrosievertPerSecond), - (RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour) => new RadiationEquivalentDoseRate((_value * 100 * 3600) / 1e-3d, RadiationEquivalentDoseRateUnit.MilliroentgenEquivalentManPerHour), - (RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.MillisievertPerHour) => new RadiationEquivalentDoseRate((_value*3600) / 1e-3d, RadiationEquivalentDoseRateUnit.MillisievertPerHour), - (RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.MillisievertPerSecond) => new RadiationEquivalentDoseRate((_value) / 1e-3d, RadiationEquivalentDoseRateUnit.MillisievertPerSecond), - (RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.NanosievertPerHour) => new RadiationEquivalentDoseRate((_value*3600) / 1e-9d, RadiationEquivalentDoseRateUnit.NanosievertPerHour), - (RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.NanosievertPerSecond) => new RadiationEquivalentDoseRate((_value) / 1e-9d, RadiationEquivalentDoseRateUnit.NanosievertPerSecond), - (RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour) => new RadiationEquivalentDoseRate(_value * 100 * 3600, RadiationEquivalentDoseRateUnit.RoentgenEquivalentManPerHour), - (RadiationEquivalentDoseRateUnit.SievertPerSecond, RadiationEquivalentDoseRateUnit.SievertPerHour) => new RadiationEquivalentDoseRate(_value*3600, RadiationEquivalentDoseRateUnit.SievertPerHour), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public RadiationEquivalentDoseRate ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not RadiationEquivalentDoseRateUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RadiationEquivalentDoseRateUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is RadiationEquivalentDoseRateUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RadiationEquivalentDoseRateUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(RadiationEquivalentDoseRateUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(RadiationEquivalentDoseRateUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -922,7 +742,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/RadiationExposure.g.cs b/UnitsNet/GeneratedCode/Quantities/RadiationExposure.g.cs index 5b847e40a9..10ebc3c93c 100644 --- a/UnitsNet/GeneratedCode/Quantities/RadiationExposure.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RadiationExposure.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// Radiation exposure is a measure of the ionization of air due to ionizing radiation from photons. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct RadiationExposure : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly RadiationExposureUnit? _unit; /// @@ -101,7 +100,7 @@ public static RadiationExposureInfo CreateDefault(Func - /// The for is [T][M^-1][I]. + /// The for is TM^-1I. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, -1, 1, 1, 0, 0, 0); @@ -117,21 +116,33 @@ public static RadiationExposureInfo CreateDefault(Func> GetDefaultMappings() { yield return new (RadiationExposureUnit.CoulombPerKilogram, "CoulombPerKilogram", "CoulombsPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); - yield return new (RadiationExposureUnit.MicrocoulombPerKilogram, "MicrocoulombPerKilogram", "MicrocoulombsPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere)); - yield return new (RadiationExposureUnit.Microroentgen, "Microroentgen", "Microroentgens", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere)); - yield return new (RadiationExposureUnit.MillicoulombPerKilogram, "MillicoulombPerKilogram", "MillicoulombsPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere)); - yield return new (RadiationExposureUnit.Milliroentgen, "Milliroentgen", "Milliroentgens", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere)); - yield return new (RadiationExposureUnit.NanocoulombPerKilogram, "NanocoulombPerKilogram", "NanocoulombsPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Nanoampere)); - yield return new (RadiationExposureUnit.PicocoulombPerKilogram, "PicocoulombPerKilogram", "PicocoulombsPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Picoampere)); - yield return new (RadiationExposureUnit.Roentgen, "Roentgen", "Roentgens", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere)); + yield return new (RadiationExposureUnit.MicrocoulombPerKilogram, "MicrocoulombPerKilogram", "MicrocoulombsPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere), + 1000000 + ); + yield return new (RadiationExposureUnit.Microroentgen, "Microroentgen", "Microroentgens", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Microampere), + new QuantityValue(500000000000, 129) + ); + yield return new (RadiationExposureUnit.MillicoulombPerKilogram, "MillicoulombPerKilogram", "MillicoulombsPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), + 1000 + ); + yield return new (RadiationExposureUnit.Milliroentgen, "Milliroentgen", "Milliroentgens", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Milliampere), + new QuantityValue(500000000, 129) + ); + yield return new (RadiationExposureUnit.NanocoulombPerKilogram, "NanocoulombPerKilogram", "NanocoulombsPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Nanoampere), + 1000000000 + ); + yield return new (RadiationExposureUnit.PicocoulombPerKilogram, "PicocoulombPerKilogram", "PicocoulombsPerKilogram", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Picoampere), + 1000000000000 + ); + yield return new (RadiationExposureUnit.Roentgen, "Roentgen", "Roentgens", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, current: ElectricCurrentUnit.Ampere), + new QuantityValue(500000, 129) + ); } } static RadiationExposure() { - Info = RadiationExposureInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(RadiationExposureInfo.CreateDefault); } /// @@ -139,7 +150,7 @@ static RadiationExposure() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public RadiationExposure(double value, RadiationExposureUnit unit) + public RadiationExposure(QuantityValue value, RadiationExposureUnit unit) { _value = value; _unit = unit; @@ -153,7 +164,7 @@ public RadiationExposure(double value, RadiationExposureUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public RadiationExposure(double value, UnitSystem unitSystem) + public RadiationExposure(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -164,7 +175,8 @@ public RadiationExposure(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -193,10 +205,8 @@ public RadiationExposure(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public RadiationExposureUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -235,77 +245,49 @@ public RadiationExposure(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CoulombsPerKilogram => As(RadiationExposureUnit.CoulombPerKilogram); + public QuantityValue CoulombsPerKilogram => this.As(RadiationExposureUnit.CoulombPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrocoulombsPerKilogram => As(RadiationExposureUnit.MicrocoulombPerKilogram); + public QuantityValue MicrocoulombsPerKilogram => this.As(RadiationExposureUnit.MicrocoulombPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microroentgens => As(RadiationExposureUnit.Microroentgen); + public QuantityValue Microroentgens => this.As(RadiationExposureUnit.Microroentgen); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillicoulombsPerKilogram => As(RadiationExposureUnit.MillicoulombPerKilogram); + public QuantityValue MillicoulombsPerKilogram => this.As(RadiationExposureUnit.MillicoulombPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Milliroentgens => As(RadiationExposureUnit.Milliroentgen); + public QuantityValue Milliroentgens => this.As(RadiationExposureUnit.Milliroentgen); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanocoulombsPerKilogram => As(RadiationExposureUnit.NanocoulombPerKilogram); + public QuantityValue NanocoulombsPerKilogram => this.As(RadiationExposureUnit.NanocoulombPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicocoulombsPerKilogram => As(RadiationExposureUnit.PicocoulombPerKilogram); + public QuantityValue PicocoulombsPerKilogram => this.As(RadiationExposureUnit.PicocoulombPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Roentgens => As(RadiationExposureUnit.Roentgen); + public QuantityValue Roentgens => this.As(RadiationExposureUnit.Roentgen); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: RadiationExposureUnit -> BaseUnit - unitConverter.SetConversionFunction(RadiationExposureUnit.MicrocoulombPerKilogram, RadiationExposureUnit.CoulombPerKilogram, quantity => quantity.ToUnit(RadiationExposureUnit.CoulombPerKilogram)); - unitConverter.SetConversionFunction(RadiationExposureUnit.Microroentgen, RadiationExposureUnit.CoulombPerKilogram, quantity => quantity.ToUnit(RadiationExposureUnit.CoulombPerKilogram)); - unitConverter.SetConversionFunction(RadiationExposureUnit.MillicoulombPerKilogram, RadiationExposureUnit.CoulombPerKilogram, quantity => quantity.ToUnit(RadiationExposureUnit.CoulombPerKilogram)); - unitConverter.SetConversionFunction(RadiationExposureUnit.Milliroentgen, RadiationExposureUnit.CoulombPerKilogram, quantity => quantity.ToUnit(RadiationExposureUnit.CoulombPerKilogram)); - unitConverter.SetConversionFunction(RadiationExposureUnit.NanocoulombPerKilogram, RadiationExposureUnit.CoulombPerKilogram, quantity => quantity.ToUnit(RadiationExposureUnit.CoulombPerKilogram)); - unitConverter.SetConversionFunction(RadiationExposureUnit.PicocoulombPerKilogram, RadiationExposureUnit.CoulombPerKilogram, quantity => quantity.ToUnit(RadiationExposureUnit.CoulombPerKilogram)); - unitConverter.SetConversionFunction(RadiationExposureUnit.Roentgen, RadiationExposureUnit.CoulombPerKilogram, quantity => quantity.ToUnit(RadiationExposureUnit.CoulombPerKilogram)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(RadiationExposureUnit.CoulombPerKilogram, RadiationExposureUnit.CoulombPerKilogram, quantity => quantity); - - // Register in unit converter: BaseUnit -> RadiationExposureUnit - unitConverter.SetConversionFunction(RadiationExposureUnit.CoulombPerKilogram, RadiationExposureUnit.MicrocoulombPerKilogram, quantity => quantity.ToUnit(RadiationExposureUnit.MicrocoulombPerKilogram)); - unitConverter.SetConversionFunction(RadiationExposureUnit.CoulombPerKilogram, RadiationExposureUnit.Microroentgen, quantity => quantity.ToUnit(RadiationExposureUnit.Microroentgen)); - unitConverter.SetConversionFunction(RadiationExposureUnit.CoulombPerKilogram, RadiationExposureUnit.MillicoulombPerKilogram, quantity => quantity.ToUnit(RadiationExposureUnit.MillicoulombPerKilogram)); - unitConverter.SetConversionFunction(RadiationExposureUnit.CoulombPerKilogram, RadiationExposureUnit.Milliroentgen, quantity => quantity.ToUnit(RadiationExposureUnit.Milliroentgen)); - unitConverter.SetConversionFunction(RadiationExposureUnit.CoulombPerKilogram, RadiationExposureUnit.NanocoulombPerKilogram, quantity => quantity.ToUnit(RadiationExposureUnit.NanocoulombPerKilogram)); - unitConverter.SetConversionFunction(RadiationExposureUnit.CoulombPerKilogram, RadiationExposureUnit.PicocoulombPerKilogram, quantity => quantity.ToUnit(RadiationExposureUnit.PicocoulombPerKilogram)); - unitConverter.SetConversionFunction(RadiationExposureUnit.CoulombPerKilogram, RadiationExposureUnit.Roentgen, quantity => quantity.ToUnit(RadiationExposureUnit.Roentgen)); - } - /// /// Get unit abbreviation string. /// @@ -334,7 +316,7 @@ public static string GetAbbreviation(RadiationExposureUnit unit, IFormatProvider /// /// Creates a from . /// - public static RadiationExposure FromCoulombsPerKilogram(double value) + public static RadiationExposure FromCoulombsPerKilogram(QuantityValue value) { return new RadiationExposure(value, RadiationExposureUnit.CoulombPerKilogram); } @@ -342,7 +324,7 @@ public static RadiationExposure FromCoulombsPerKilogram(double value) /// /// Creates a from . /// - public static RadiationExposure FromMicrocoulombsPerKilogram(double value) + public static RadiationExposure FromMicrocoulombsPerKilogram(QuantityValue value) { return new RadiationExposure(value, RadiationExposureUnit.MicrocoulombPerKilogram); } @@ -350,7 +332,7 @@ public static RadiationExposure FromMicrocoulombsPerKilogram(double value) /// /// Creates a from . /// - public static RadiationExposure FromMicroroentgens(double value) + public static RadiationExposure FromMicroroentgens(QuantityValue value) { return new RadiationExposure(value, RadiationExposureUnit.Microroentgen); } @@ -358,7 +340,7 @@ public static RadiationExposure FromMicroroentgens(double value) /// /// Creates a from . /// - public static RadiationExposure FromMillicoulombsPerKilogram(double value) + public static RadiationExposure FromMillicoulombsPerKilogram(QuantityValue value) { return new RadiationExposure(value, RadiationExposureUnit.MillicoulombPerKilogram); } @@ -366,7 +348,7 @@ public static RadiationExposure FromMillicoulombsPerKilogram(double value) /// /// Creates a from . /// - public static RadiationExposure FromMilliroentgens(double value) + public static RadiationExposure FromMilliroentgens(QuantityValue value) { return new RadiationExposure(value, RadiationExposureUnit.Milliroentgen); } @@ -374,7 +356,7 @@ public static RadiationExposure FromMilliroentgens(double value) /// /// Creates a from . /// - public static RadiationExposure FromNanocoulombsPerKilogram(double value) + public static RadiationExposure FromNanocoulombsPerKilogram(QuantityValue value) { return new RadiationExposure(value, RadiationExposureUnit.NanocoulombPerKilogram); } @@ -382,7 +364,7 @@ public static RadiationExposure FromNanocoulombsPerKilogram(double value) /// /// Creates a from . /// - public static RadiationExposure FromPicocoulombsPerKilogram(double value) + public static RadiationExposure FromPicocoulombsPerKilogram(QuantityValue value) { return new RadiationExposure(value, RadiationExposureUnit.PicocoulombPerKilogram); } @@ -390,7 +372,7 @@ public static RadiationExposure FromPicocoulombsPerKilogram(double value) /// /// Creates a from . /// - public static RadiationExposure FromRoentgens(double value) + public static RadiationExposure FromRoentgens(QuantityValue value) { return new RadiationExposure(value, RadiationExposureUnit.Roentgen); } @@ -401,7 +383,7 @@ public static RadiationExposure FromRoentgens(double value) /// Value to convert from. /// Unit to convert from. /// RadiationExposure unit value. - public static RadiationExposure From(double value, RadiationExposureUnit fromUnit) + public static RadiationExposure From(QuantityValue value, RadiationExposureUnit fromUnit) { return new RadiationExposure(value, fromUnit); } @@ -462,10 +444,7 @@ public static RadiationExposure Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static RadiationExposure Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -493,11 +472,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out RadiationExposur /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out RadiationExposure result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -518,7 +493,7 @@ public static RadiationExposureUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -529,7 +504,7 @@ public static RadiationExposureUnit ParseUnit(string str, IFormatProvider? provi return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out RadiationExposureUnit unit) { return TryParseUnit(str, null, out unit); @@ -544,7 +519,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out RadiationExp /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out RadiationExposureUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -563,35 +538,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static RadiationExposure operator +(RadiationExposure left, RadiationExposure right) { - return new RadiationExposure(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new RadiationExposure(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static RadiationExposure operator -(RadiationExposure left, RadiationExposure right) { - return new RadiationExposure(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new RadiationExposure(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static RadiationExposure operator *(double left, RadiationExposure right) + public static RadiationExposure operator *(QuantityValue left, RadiationExposure right) { return new RadiationExposure(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static RadiationExposure operator *(RadiationExposure left, double right) + public static RadiationExposure operator *(RadiationExposure left, QuantityValue right) { return new RadiationExposure(left.Value * right, left.Unit); } /// Get from dividing by value. - public static RadiationExposure operator /(RadiationExposure left, double right) + public static RadiationExposure operator /(RadiationExposure left, QuantityValue right) { return new RadiationExposure(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(RadiationExposure left, RadiationExposure right) + public static QuantityValue operator /(RadiationExposure left, RadiationExposure right) { return left.CoulombsPerKilogram / right.CoulombsPerKilogram; } @@ -603,97 +578,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(RadiationExposure left, RadiationExposure right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(RadiationExposure left, RadiationExposure right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(RadiationExposure left, RadiationExposure right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(RadiationExposure left, RadiationExposure right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RadiationExposure other, RadiationExposure tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(RadiationExposure left, RadiationExposure right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RadiationExposure other, RadiationExposure tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(RadiationExposure left, RadiationExposure right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RadiationExposure other, RadiationExposure tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is RadiationExposure otherQuantity)) + if (obj is not RadiationExposure otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RadiationExposure other, RadiationExposure tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(RadiationExposure other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current RadiationExposure. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(RadiationExposure), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is RadiationExposure otherQuantity)) throw new ArgumentException("Expected type RadiationExposure.", nameof(obj)); + if (obj is not RadiationExposure otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -705,160 +665,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RadiationExposure other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RadiationExposureUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this RadiationExposure to another RadiationExposure with the unit representation . - /// - /// The unit to convert to. - /// A RadiationExposure with the specified unit. - public RadiationExposure ToUnit(RadiationExposureUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A RadiationExposure with the specified unit. - public RadiationExposure ToUnit(RadiationExposureUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(RadiationExposure), Unit, typeof(RadiationExposure), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (RadiationExposure)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(RadiationExposureUnit unit, [NotNullWhen(true)] out RadiationExposure? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - RadiationExposure? convertedOrNull = (Unit, unit) switch - { - // RadiationExposureUnit -> BaseUnit - (RadiationExposureUnit.MicrocoulombPerKilogram, RadiationExposureUnit.CoulombPerKilogram) => new RadiationExposure((_value) * 1e-6d, RadiationExposureUnit.CoulombPerKilogram), - (RadiationExposureUnit.Microroentgen, RadiationExposureUnit.CoulombPerKilogram) => new RadiationExposure((_value * 2.58e-4) * 1e-6d, RadiationExposureUnit.CoulombPerKilogram), - (RadiationExposureUnit.MillicoulombPerKilogram, RadiationExposureUnit.CoulombPerKilogram) => new RadiationExposure((_value) * 1e-3d, RadiationExposureUnit.CoulombPerKilogram), - (RadiationExposureUnit.Milliroentgen, RadiationExposureUnit.CoulombPerKilogram) => new RadiationExposure((_value * 2.58e-4) * 1e-3d, RadiationExposureUnit.CoulombPerKilogram), - (RadiationExposureUnit.NanocoulombPerKilogram, RadiationExposureUnit.CoulombPerKilogram) => new RadiationExposure((_value) * 1e-9d, RadiationExposureUnit.CoulombPerKilogram), - (RadiationExposureUnit.PicocoulombPerKilogram, RadiationExposureUnit.CoulombPerKilogram) => new RadiationExposure((_value) * 1e-12d, RadiationExposureUnit.CoulombPerKilogram), - (RadiationExposureUnit.Roentgen, RadiationExposureUnit.CoulombPerKilogram) => new RadiationExposure(_value * 2.58e-4, RadiationExposureUnit.CoulombPerKilogram), - - // BaseUnit -> RadiationExposureUnit - (RadiationExposureUnit.CoulombPerKilogram, RadiationExposureUnit.MicrocoulombPerKilogram) => new RadiationExposure((_value) / 1e-6d, RadiationExposureUnit.MicrocoulombPerKilogram), - (RadiationExposureUnit.CoulombPerKilogram, RadiationExposureUnit.Microroentgen) => new RadiationExposure((_value / 2.58e-4) / 1e-6d, RadiationExposureUnit.Microroentgen), - (RadiationExposureUnit.CoulombPerKilogram, RadiationExposureUnit.MillicoulombPerKilogram) => new RadiationExposure((_value) / 1e-3d, RadiationExposureUnit.MillicoulombPerKilogram), - (RadiationExposureUnit.CoulombPerKilogram, RadiationExposureUnit.Milliroentgen) => new RadiationExposure((_value / 2.58e-4) / 1e-3d, RadiationExposureUnit.Milliroentgen), - (RadiationExposureUnit.CoulombPerKilogram, RadiationExposureUnit.NanocoulombPerKilogram) => new RadiationExposure((_value) / 1e-9d, RadiationExposureUnit.NanocoulombPerKilogram), - (RadiationExposureUnit.CoulombPerKilogram, RadiationExposureUnit.PicocoulombPerKilogram) => new RadiationExposure((_value) / 1e-12d, RadiationExposureUnit.PicocoulombPerKilogram), - (RadiationExposureUnit.CoulombPerKilogram, RadiationExposureUnit.Roentgen) => new RadiationExposure(_value / 2.58e-4, RadiationExposureUnit.Roentgen), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public RadiationExposure ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not RadiationExposureUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RadiationExposureUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is RadiationExposureUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RadiationExposureUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(RadiationExposureUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(RadiationExposureUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -873,7 +697,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Radioactivity.g.cs b/UnitsNet/GeneratedCode/Quantities/Radioactivity.g.cs index 751d486e5f..d9676f8133 100644 --- a/UnitsNet/GeneratedCode/Quantities/Radioactivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Radioactivity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// Amount of ionizing radiation released when an element spontaneously emits energy as a result of the radioactive decay of an unstable atom per unit time. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Radioactivity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly RadioactivityUnit? _unit; /// @@ -101,7 +100,7 @@ public static RadioactivityInfo CreateDefault(Func - /// The for is [T^-1]. + /// The for is T^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); @@ -117,42 +116,96 @@ public static RadioactivityInfo CreateDefault(Func> GetDefaultMappings() { yield return new (RadioactivityUnit.Becquerel, "Becquerel", "Becquerels", new BaseUnits(time: DurationUnit.Second)); - yield return new (RadioactivityUnit.Curie, "Curie", "Curies", new BaseUnits(time: DurationUnit.Second)); - yield return new (RadioactivityUnit.Exabecquerel, "Exabecquerel", "Exabecquerels", BaseUnits.Undefined); - yield return new (RadioactivityUnit.Gigabecquerel, "Gigabecquerel", "Gigabecquerels", new BaseUnits(time: DurationUnit.Nanosecond)); - yield return new (RadioactivityUnit.Gigacurie, "Gigacurie", "Gigacuries", new BaseUnits(time: DurationUnit.Nanosecond)); - yield return new (RadioactivityUnit.Gigarutherford, "Gigarutherford", "Gigarutherfords", new BaseUnits(time: DurationUnit.Nanosecond)); - yield return new (RadioactivityUnit.Kilobecquerel, "Kilobecquerel", "Kilobecquerels", new BaseUnits(time: DurationUnit.Millisecond)); - yield return new (RadioactivityUnit.Kilocurie, "Kilocurie", "Kilocuries", new BaseUnits(time: DurationUnit.Millisecond)); - yield return new (RadioactivityUnit.Kilorutherford, "Kilorutherford", "Kilorutherfords", new BaseUnits(time: DurationUnit.Millisecond)); - yield return new (RadioactivityUnit.Megabecquerel, "Megabecquerel", "Megabecquerels", new BaseUnits(time: DurationUnit.Microsecond)); - yield return new (RadioactivityUnit.Megacurie, "Megacurie", "Megacuries", new BaseUnits(time: DurationUnit.Microsecond)); - yield return new (RadioactivityUnit.Megarutherford, "Megarutherford", "Megarutherfords", new BaseUnits(time: DurationUnit.Microsecond)); - yield return new (RadioactivityUnit.Microbecquerel, "Microbecquerel", "Microbecquerels", BaseUnits.Undefined); - yield return new (RadioactivityUnit.Microcurie, "Microcurie", "Microcuries", BaseUnits.Undefined); - yield return new (RadioactivityUnit.Microrutherford, "Microrutherford", "Microrutherfords", BaseUnits.Undefined); - yield return new (RadioactivityUnit.Millibecquerel, "Millibecquerel", "Millibecquerels", BaseUnits.Undefined); - yield return new (RadioactivityUnit.Millicurie, "Millicurie", "Millicuries", BaseUnits.Undefined); - yield return new (RadioactivityUnit.Millirutherford, "Millirutherford", "Millirutherfords", BaseUnits.Undefined); - yield return new (RadioactivityUnit.Nanobecquerel, "Nanobecquerel", "Nanobecquerels", BaseUnits.Undefined); - yield return new (RadioactivityUnit.Nanocurie, "Nanocurie", "Nanocuries", BaseUnits.Undefined); - yield return new (RadioactivityUnit.Nanorutherford, "Nanorutherford", "Nanorutherfords", BaseUnits.Undefined); - yield return new (RadioactivityUnit.Petabecquerel, "Petabecquerel", "Petabecquerels", BaseUnits.Undefined); - yield return new (RadioactivityUnit.Picobecquerel, "Picobecquerel", "Picobecquerels", BaseUnits.Undefined); - yield return new (RadioactivityUnit.Picocurie, "Picocurie", "Picocuries", BaseUnits.Undefined); - yield return new (RadioactivityUnit.Picorutherford, "Picorutherford", "Picorutherfords", BaseUnits.Undefined); - yield return new (RadioactivityUnit.Rutherford, "Rutherford", "Rutherfords", new BaseUnits(time: DurationUnit.Second)); - yield return new (RadioactivityUnit.Terabecquerel, "Terabecquerel", "Terabecquerels", new BaseUnits(time: DurationUnit.Picosecond)); - yield return new (RadioactivityUnit.Teracurie, "Teracurie", "Teracuries", new BaseUnits(time: DurationUnit.Picosecond)); - yield return new (RadioactivityUnit.Terarutherford, "Terarutherford", "Terarutherfords", new BaseUnits(time: DurationUnit.Picosecond)); + yield return new (RadioactivityUnit.Curie, "Curie", "Curies", new BaseUnits(time: DurationUnit.Second), + new QuantityValue(1, 37000000000) + ); + yield return new (RadioactivityUnit.Exabecquerel, "Exabecquerel", "Exabecquerels", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000000000) + ); + yield return new (RadioactivityUnit.Gigabecquerel, "Gigabecquerel", "Gigabecquerels", new BaseUnits(time: DurationUnit.Nanosecond), + new QuantityValue(1, 1000000000) + ); + yield return new (RadioactivityUnit.Gigacurie, "Gigacurie", "Gigacuries", new BaseUnits(time: DurationUnit.Nanosecond), + new QuantityValue(1, new BigInteger(37) * QuantityValue.PowerOfTen(18)) + ); + yield return new (RadioactivityUnit.Gigarutherford, "Gigarutherford", "Gigarutherfords", new BaseUnits(time: DurationUnit.Nanosecond), + new QuantityValue(1, 1000000000000000) + ); + yield return new (RadioactivityUnit.Kilobecquerel, "Kilobecquerel", "Kilobecquerels", new BaseUnits(time: DurationUnit.Millisecond), + new QuantityValue(1, 1000) + ); + yield return new (RadioactivityUnit.Kilocurie, "Kilocurie", "Kilocuries", new BaseUnits(time: DurationUnit.Millisecond), + new QuantityValue(1, 37000000000000) + ); + yield return new (RadioactivityUnit.Kilorutherford, "Kilorutherford", "Kilorutherfords", new BaseUnits(time: DurationUnit.Millisecond), + new QuantityValue(1, 1000000000) + ); + yield return new (RadioactivityUnit.Megabecquerel, "Megabecquerel", "Megabecquerels", new BaseUnits(time: DurationUnit.Microsecond), + new QuantityValue(1, 1000000) + ); + yield return new (RadioactivityUnit.Megacurie, "Megacurie", "Megacuries", new BaseUnits(time: DurationUnit.Microsecond), + new QuantityValue(1, 37000000000000000) + ); + yield return new (RadioactivityUnit.Megarutherford, "Megarutherford", "Megarutherfords", new BaseUnits(time: DurationUnit.Microsecond), + new QuantityValue(1, 1000000000000) + ); + yield return new (RadioactivityUnit.Microbecquerel, "Microbecquerel", "Microbecquerels", BaseUnits.Undefined, + 1000000 + ); + yield return new (RadioactivityUnit.Microcurie, "Microcurie", "Microcuries", BaseUnits.Undefined, + new QuantityValue(1, 37000) + ); + yield return new (RadioactivityUnit.Microrutherford, "Microrutherford", "Microrutherfords", BaseUnits.Undefined, + 1 + ); + yield return new (RadioactivityUnit.Millibecquerel, "Millibecquerel", "Millibecquerels", BaseUnits.Undefined, + 1000 + ); + yield return new (RadioactivityUnit.Millicurie, "Millicurie", "Millicuries", BaseUnits.Undefined, + new QuantityValue(1, 37000000) + ); + yield return new (RadioactivityUnit.Millirutherford, "Millirutherford", "Millirutherfords", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (RadioactivityUnit.Nanobecquerel, "Nanobecquerel", "Nanobecquerels", BaseUnits.Undefined, + 1000000000 + ); + yield return new (RadioactivityUnit.Nanocurie, "Nanocurie", "Nanocuries", BaseUnits.Undefined, + new QuantityValue(1, 37) + ); + yield return new (RadioactivityUnit.Nanorutherford, "Nanorutherford", "Nanorutherfords", BaseUnits.Undefined, + 1000 + ); + yield return new (RadioactivityUnit.Petabecquerel, "Petabecquerel", "Petabecquerels", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000000) + ); + yield return new (RadioactivityUnit.Picobecquerel, "Picobecquerel", "Picobecquerels", BaseUnits.Undefined, + 1000000000000 + ); + yield return new (RadioactivityUnit.Picocurie, "Picocurie", "Picocuries", BaseUnits.Undefined, + new QuantityValue(1000, 37) + ); + yield return new (RadioactivityUnit.Picorutherford, "Picorutherford", "Picorutherfords", BaseUnits.Undefined, + 1000000 + ); + yield return new (RadioactivityUnit.Rutherford, "Rutherford", "Rutherfords", new BaseUnits(time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (RadioactivityUnit.Terabecquerel, "Terabecquerel", "Terabecquerels", new BaseUnits(time: DurationUnit.Picosecond), + new QuantityValue(1, 1000000000000) + ); + yield return new (RadioactivityUnit.Teracurie, "Teracurie", "Teracuries", new BaseUnits(time: DurationUnit.Picosecond), + new QuantityValue(1, new BigInteger(37) * QuantityValue.PowerOfTen(21)) + ); + yield return new (RadioactivityUnit.Terarutherford, "Terarutherford", "Terarutherfords", new BaseUnits(time: DurationUnit.Picosecond), + new QuantityValue(1, 1000000000000000000) + ); } } static Radioactivity() { - Info = RadioactivityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(RadioactivityInfo.CreateDefault); } /// @@ -160,7 +213,7 @@ static Radioactivity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Radioactivity(double value, RadioactivityUnit unit) + public Radioactivity(QuantityValue value, RadioactivityUnit unit) { _value = value; _unit = unit; @@ -174,7 +227,7 @@ public Radioactivity(double value, RadioactivityUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public Radioactivity(double value, UnitSystem unitSystem) + public Radioactivity(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -185,7 +238,8 @@ public Radioactivity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -214,10 +268,8 @@ public Radioactivity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public RadioactivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -256,224 +308,154 @@ public Radioactivity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Becquerels => As(RadioactivityUnit.Becquerel); + public QuantityValue Becquerels => this.As(RadioactivityUnit.Becquerel); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Curies => As(RadioactivityUnit.Curie); + public QuantityValue Curies => this.As(RadioactivityUnit.Curie); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Exabecquerels => As(RadioactivityUnit.Exabecquerel); + public QuantityValue Exabecquerels => this.As(RadioactivityUnit.Exabecquerel); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigabecquerels => As(RadioactivityUnit.Gigabecquerel); + public QuantityValue Gigabecquerels => this.As(RadioactivityUnit.Gigabecquerel); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigacuries => As(RadioactivityUnit.Gigacurie); + public QuantityValue Gigacuries => this.As(RadioactivityUnit.Gigacurie); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Gigarutherfords => As(RadioactivityUnit.Gigarutherford); + public QuantityValue Gigarutherfords => this.As(RadioactivityUnit.Gigarutherford); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilobecquerels => As(RadioactivityUnit.Kilobecquerel); + public QuantityValue Kilobecquerels => this.As(RadioactivityUnit.Kilobecquerel); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilocuries => As(RadioactivityUnit.Kilocurie); + public QuantityValue Kilocuries => this.As(RadioactivityUnit.Kilocurie); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kilorutherfords => As(RadioactivityUnit.Kilorutherford); + public QuantityValue Kilorutherfords => this.As(RadioactivityUnit.Kilorutherford); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megabecquerels => As(RadioactivityUnit.Megabecquerel); + public QuantityValue Megabecquerels => this.As(RadioactivityUnit.Megabecquerel); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megacuries => As(RadioactivityUnit.Megacurie); + public QuantityValue Megacuries => this.As(RadioactivityUnit.Megacurie); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megarutherfords => As(RadioactivityUnit.Megarutherford); + public QuantityValue Megarutherfords => this.As(RadioactivityUnit.Megarutherford); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microbecquerels => As(RadioactivityUnit.Microbecquerel); + public QuantityValue Microbecquerels => this.As(RadioactivityUnit.Microbecquerel); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microcuries => As(RadioactivityUnit.Microcurie); + public QuantityValue Microcuries => this.As(RadioactivityUnit.Microcurie); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microrutherfords => As(RadioactivityUnit.Microrutherford); + public QuantityValue Microrutherfords => this.As(RadioactivityUnit.Microrutherford); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millibecquerels => As(RadioactivityUnit.Millibecquerel); + public QuantityValue Millibecquerels => this.As(RadioactivityUnit.Millibecquerel); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millicuries => As(RadioactivityUnit.Millicurie); + public QuantityValue Millicuries => this.As(RadioactivityUnit.Millicurie); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Millirutherfords => As(RadioactivityUnit.Millirutherford); + public QuantityValue Millirutherfords => this.As(RadioactivityUnit.Millirutherford); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanobecquerels => As(RadioactivityUnit.Nanobecquerel); + public QuantityValue Nanobecquerels => this.As(RadioactivityUnit.Nanobecquerel); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanocuries => As(RadioactivityUnit.Nanocurie); + public QuantityValue Nanocuries => this.As(RadioactivityUnit.Nanocurie); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanorutherfords => As(RadioactivityUnit.Nanorutherford); + public QuantityValue Nanorutherfords => this.As(RadioactivityUnit.Nanorutherford); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Petabecquerels => As(RadioactivityUnit.Petabecquerel); + public QuantityValue Petabecquerels => this.As(RadioactivityUnit.Petabecquerel); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Picobecquerels => As(RadioactivityUnit.Picobecquerel); + public QuantityValue Picobecquerels => this.As(RadioactivityUnit.Picobecquerel); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Picocuries => As(RadioactivityUnit.Picocurie); + public QuantityValue Picocuries => this.As(RadioactivityUnit.Picocurie); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Picorutherfords => As(RadioactivityUnit.Picorutherford); + public QuantityValue Picorutherfords => this.As(RadioactivityUnit.Picorutherford); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Rutherfords => As(RadioactivityUnit.Rutherford); + public QuantityValue Rutherfords => this.As(RadioactivityUnit.Rutherford); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Terabecquerels => As(RadioactivityUnit.Terabecquerel); + public QuantityValue Terabecquerels => this.As(RadioactivityUnit.Terabecquerel); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Teracuries => As(RadioactivityUnit.Teracurie); + public QuantityValue Teracuries => this.As(RadioactivityUnit.Teracurie); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Terarutherfords => As(RadioactivityUnit.Terarutherford); + public QuantityValue Terarutherfords => this.As(RadioactivityUnit.Terarutherford); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: RadioactivityUnit -> BaseUnit - unitConverter.SetConversionFunction(RadioactivityUnit.Curie, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Exabecquerel, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Gigabecquerel, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Gigacurie, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Gigarutherford, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Kilobecquerel, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Kilocurie, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Kilorutherford, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Megabecquerel, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Megacurie, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Megarutherford, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Microbecquerel, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Microcurie, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Microrutherford, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Millibecquerel, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Millicurie, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Millirutherford, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Nanobecquerel, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Nanocurie, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Nanorutherford, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Petabecquerel, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Picobecquerel, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Picocurie, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Picorutherford, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Rutherford, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Terabecquerel, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Teracurie, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Terarutherford, RadioactivityUnit.Becquerel, quantity => quantity.ToUnit(RadioactivityUnit.Becquerel)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Becquerel, quantity => quantity); - - // Register in unit converter: BaseUnit -> RadioactivityUnit - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Curie, quantity => quantity.ToUnit(RadioactivityUnit.Curie)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Exabecquerel, quantity => quantity.ToUnit(RadioactivityUnit.Exabecquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Gigabecquerel, quantity => quantity.ToUnit(RadioactivityUnit.Gigabecquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Gigacurie, quantity => quantity.ToUnit(RadioactivityUnit.Gigacurie)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Gigarutherford, quantity => quantity.ToUnit(RadioactivityUnit.Gigarutherford)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Kilobecquerel, quantity => quantity.ToUnit(RadioactivityUnit.Kilobecquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Kilocurie, quantity => quantity.ToUnit(RadioactivityUnit.Kilocurie)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Kilorutherford, quantity => quantity.ToUnit(RadioactivityUnit.Kilorutherford)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Megabecquerel, quantity => quantity.ToUnit(RadioactivityUnit.Megabecquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Megacurie, quantity => quantity.ToUnit(RadioactivityUnit.Megacurie)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Megarutherford, quantity => quantity.ToUnit(RadioactivityUnit.Megarutherford)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Microbecquerel, quantity => quantity.ToUnit(RadioactivityUnit.Microbecquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Microcurie, quantity => quantity.ToUnit(RadioactivityUnit.Microcurie)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Microrutherford, quantity => quantity.ToUnit(RadioactivityUnit.Microrutherford)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Millibecquerel, quantity => quantity.ToUnit(RadioactivityUnit.Millibecquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Millicurie, quantity => quantity.ToUnit(RadioactivityUnit.Millicurie)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Millirutherford, quantity => quantity.ToUnit(RadioactivityUnit.Millirutherford)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Nanobecquerel, quantity => quantity.ToUnit(RadioactivityUnit.Nanobecquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Nanocurie, quantity => quantity.ToUnit(RadioactivityUnit.Nanocurie)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Nanorutherford, quantity => quantity.ToUnit(RadioactivityUnit.Nanorutherford)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Petabecquerel, quantity => quantity.ToUnit(RadioactivityUnit.Petabecquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Picobecquerel, quantity => quantity.ToUnit(RadioactivityUnit.Picobecquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Picocurie, quantity => quantity.ToUnit(RadioactivityUnit.Picocurie)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Picorutherford, quantity => quantity.ToUnit(RadioactivityUnit.Picorutherford)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Rutherford, quantity => quantity.ToUnit(RadioactivityUnit.Rutherford)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Terabecquerel, quantity => quantity.ToUnit(RadioactivityUnit.Terabecquerel)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Teracurie, quantity => quantity.ToUnit(RadioactivityUnit.Teracurie)); - unitConverter.SetConversionFunction(RadioactivityUnit.Becquerel, RadioactivityUnit.Terarutherford, quantity => quantity.ToUnit(RadioactivityUnit.Terarutherford)); - } - /// /// Get unit abbreviation string. /// @@ -502,7 +484,7 @@ public static string GetAbbreviation(RadioactivityUnit unit, IFormatProvider? pr /// /// Creates a from . /// - public static Radioactivity FromBecquerels(double value) + public static Radioactivity FromBecquerels(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Becquerel); } @@ -510,7 +492,7 @@ public static Radioactivity FromBecquerels(double value) /// /// Creates a from . /// - public static Radioactivity FromCuries(double value) + public static Radioactivity FromCuries(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Curie); } @@ -518,7 +500,7 @@ public static Radioactivity FromCuries(double value) /// /// Creates a from . /// - public static Radioactivity FromExabecquerels(double value) + public static Radioactivity FromExabecquerels(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Exabecquerel); } @@ -526,7 +508,7 @@ public static Radioactivity FromExabecquerels(double value) /// /// Creates a from . /// - public static Radioactivity FromGigabecquerels(double value) + public static Radioactivity FromGigabecquerels(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Gigabecquerel); } @@ -534,7 +516,7 @@ public static Radioactivity FromGigabecquerels(double value) /// /// Creates a from . /// - public static Radioactivity FromGigacuries(double value) + public static Radioactivity FromGigacuries(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Gigacurie); } @@ -542,7 +524,7 @@ public static Radioactivity FromGigacuries(double value) /// /// Creates a from . /// - public static Radioactivity FromGigarutherfords(double value) + public static Radioactivity FromGigarutherfords(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Gigarutherford); } @@ -550,7 +532,7 @@ public static Radioactivity FromGigarutherfords(double value) /// /// Creates a from . /// - public static Radioactivity FromKilobecquerels(double value) + public static Radioactivity FromKilobecquerels(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Kilobecquerel); } @@ -558,7 +540,7 @@ public static Radioactivity FromKilobecquerels(double value) /// /// Creates a from . /// - public static Radioactivity FromKilocuries(double value) + public static Radioactivity FromKilocuries(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Kilocurie); } @@ -566,7 +548,7 @@ public static Radioactivity FromKilocuries(double value) /// /// Creates a from . /// - public static Radioactivity FromKilorutherfords(double value) + public static Radioactivity FromKilorutherfords(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Kilorutherford); } @@ -574,7 +556,7 @@ public static Radioactivity FromKilorutherfords(double value) /// /// Creates a from . /// - public static Radioactivity FromMegabecquerels(double value) + public static Radioactivity FromMegabecquerels(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Megabecquerel); } @@ -582,7 +564,7 @@ public static Radioactivity FromMegabecquerels(double value) /// /// Creates a from . /// - public static Radioactivity FromMegacuries(double value) + public static Radioactivity FromMegacuries(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Megacurie); } @@ -590,7 +572,7 @@ public static Radioactivity FromMegacuries(double value) /// /// Creates a from . /// - public static Radioactivity FromMegarutherfords(double value) + public static Radioactivity FromMegarutherfords(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Megarutherford); } @@ -598,7 +580,7 @@ public static Radioactivity FromMegarutherfords(double value) /// /// Creates a from . /// - public static Radioactivity FromMicrobecquerels(double value) + public static Radioactivity FromMicrobecquerels(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Microbecquerel); } @@ -606,7 +588,7 @@ public static Radioactivity FromMicrobecquerels(double value) /// /// Creates a from . /// - public static Radioactivity FromMicrocuries(double value) + public static Radioactivity FromMicrocuries(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Microcurie); } @@ -614,7 +596,7 @@ public static Radioactivity FromMicrocuries(double value) /// /// Creates a from . /// - public static Radioactivity FromMicrorutherfords(double value) + public static Radioactivity FromMicrorutherfords(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Microrutherford); } @@ -622,7 +604,7 @@ public static Radioactivity FromMicrorutherfords(double value) /// /// Creates a from . /// - public static Radioactivity FromMillibecquerels(double value) + public static Radioactivity FromMillibecquerels(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Millibecquerel); } @@ -630,7 +612,7 @@ public static Radioactivity FromMillibecquerels(double value) /// /// Creates a from . /// - public static Radioactivity FromMillicuries(double value) + public static Radioactivity FromMillicuries(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Millicurie); } @@ -638,7 +620,7 @@ public static Radioactivity FromMillicuries(double value) /// /// Creates a from . /// - public static Radioactivity FromMillirutherfords(double value) + public static Radioactivity FromMillirutherfords(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Millirutherford); } @@ -646,7 +628,7 @@ public static Radioactivity FromMillirutherfords(double value) /// /// Creates a from . /// - public static Radioactivity FromNanobecquerels(double value) + public static Radioactivity FromNanobecquerels(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Nanobecquerel); } @@ -654,7 +636,7 @@ public static Radioactivity FromNanobecquerels(double value) /// /// Creates a from . /// - public static Radioactivity FromNanocuries(double value) + public static Radioactivity FromNanocuries(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Nanocurie); } @@ -662,7 +644,7 @@ public static Radioactivity FromNanocuries(double value) /// /// Creates a from . /// - public static Radioactivity FromNanorutherfords(double value) + public static Radioactivity FromNanorutherfords(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Nanorutherford); } @@ -670,7 +652,7 @@ public static Radioactivity FromNanorutherfords(double value) /// /// Creates a from . /// - public static Radioactivity FromPetabecquerels(double value) + public static Radioactivity FromPetabecquerels(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Petabecquerel); } @@ -678,7 +660,7 @@ public static Radioactivity FromPetabecquerels(double value) /// /// Creates a from . /// - public static Radioactivity FromPicobecquerels(double value) + public static Radioactivity FromPicobecquerels(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Picobecquerel); } @@ -686,7 +668,7 @@ public static Radioactivity FromPicobecquerels(double value) /// /// Creates a from . /// - public static Radioactivity FromPicocuries(double value) + public static Radioactivity FromPicocuries(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Picocurie); } @@ -694,7 +676,7 @@ public static Radioactivity FromPicocuries(double value) /// /// Creates a from . /// - public static Radioactivity FromPicorutherfords(double value) + public static Radioactivity FromPicorutherfords(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Picorutherford); } @@ -702,7 +684,7 @@ public static Radioactivity FromPicorutherfords(double value) /// /// Creates a from . /// - public static Radioactivity FromRutherfords(double value) + public static Radioactivity FromRutherfords(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Rutherford); } @@ -710,7 +692,7 @@ public static Radioactivity FromRutherfords(double value) /// /// Creates a from . /// - public static Radioactivity FromTerabecquerels(double value) + public static Radioactivity FromTerabecquerels(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Terabecquerel); } @@ -718,7 +700,7 @@ public static Radioactivity FromTerabecquerels(double value) /// /// Creates a from . /// - public static Radioactivity FromTeracuries(double value) + public static Radioactivity FromTeracuries(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Teracurie); } @@ -726,7 +708,7 @@ public static Radioactivity FromTeracuries(double value) /// /// Creates a from . /// - public static Radioactivity FromTerarutherfords(double value) + public static Radioactivity FromTerarutherfords(QuantityValue value) { return new Radioactivity(value, RadioactivityUnit.Terarutherford); } @@ -737,7 +719,7 @@ public static Radioactivity FromTerarutherfords(double value) /// Value to convert from. /// Unit to convert from. /// Radioactivity unit value. - public static Radioactivity From(double value, RadioactivityUnit fromUnit) + public static Radioactivity From(QuantityValue value, RadioactivityUnit fromUnit) { return new Radioactivity(value, fromUnit); } @@ -798,10 +780,7 @@ public static Radioactivity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Radioactivity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -829,11 +808,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Radioactivity re /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Radioactivity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -854,7 +829,7 @@ public static RadioactivityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -865,7 +840,7 @@ public static RadioactivityUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out RadioactivityUnit unit) { return TryParseUnit(str, null, out unit); @@ -880,7 +855,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out Radioactivit /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out RadioactivityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -899,35 +874,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Radioactivity operator +(Radioactivity left, Radioactivity right) { - return new Radioactivity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Radioactivity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Radioactivity operator -(Radioactivity left, Radioactivity right) { - return new Radioactivity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Radioactivity(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static Radioactivity operator *(double left, Radioactivity right) + public static Radioactivity operator *(QuantityValue left, Radioactivity right) { return new Radioactivity(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static Radioactivity operator *(Radioactivity left, double right) + public static Radioactivity operator *(Radioactivity left, QuantityValue right) { return new Radioactivity(left.Value * right, left.Unit); } /// Get from dividing by value. - public static Radioactivity operator /(Radioactivity left, double right) + public static Radioactivity operator /(Radioactivity left, QuantityValue right) { return new Radioactivity(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(Radioactivity left, Radioactivity right) + public static QuantityValue operator /(Radioactivity left, Radioactivity right) { return left.Becquerels / right.Becquerels; } @@ -939,97 +914,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Radioactivity left, Radioactivity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Radioactivity left, Radioactivity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Radioactivity left, Radioactivity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Radioactivity left, Radioactivity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Radioactivity other, Radioactivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Radioactivity left, Radioactivity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Radioactivity other, Radioactivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Radioactivity left, Radioactivity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Radioactivity other, Radioactivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Radioactivity otherQuantity)) + if (obj is not Radioactivity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Radioactivity other, Radioactivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Radioactivity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Radioactivity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Radioactivity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Radioactivity otherQuantity)) throw new ArgumentException("Expected type Radioactivity.", nameof(obj)); + if (obj is not Radioactivity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1041,202 +1001,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Radioactivity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RadioactivityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Radioactivity to another Radioactivity with the unit representation . - /// - /// The unit to convert to. - /// A Radioactivity with the specified unit. - public Radioactivity ToUnit(RadioactivityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Radioactivity with the specified unit. - public Radioactivity ToUnit(RadioactivityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Radioactivity), Unit, typeof(Radioactivity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Radioactivity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(RadioactivityUnit unit, [NotNullWhen(true)] out Radioactivity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Radioactivity? convertedOrNull = (Unit, unit) switch - { - // RadioactivityUnit -> BaseUnit - (RadioactivityUnit.Curie, RadioactivityUnit.Becquerel) => new Radioactivity(_value * 3.7e10, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Exabecquerel, RadioactivityUnit.Becquerel) => new Radioactivity((_value) * 1e18d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Gigabecquerel, RadioactivityUnit.Becquerel) => new Radioactivity((_value) * 1e9d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Gigacurie, RadioactivityUnit.Becquerel) => new Radioactivity((_value * 3.7e10) * 1e9d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Gigarutherford, RadioactivityUnit.Becquerel) => new Radioactivity((_value * 1e6) * 1e9d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Kilobecquerel, RadioactivityUnit.Becquerel) => new Radioactivity((_value) * 1e3d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Kilocurie, RadioactivityUnit.Becquerel) => new Radioactivity((_value * 3.7e10) * 1e3d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Kilorutherford, RadioactivityUnit.Becquerel) => new Radioactivity((_value * 1e6) * 1e3d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Megabecquerel, RadioactivityUnit.Becquerel) => new Radioactivity((_value) * 1e6d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Megacurie, RadioactivityUnit.Becquerel) => new Radioactivity((_value * 3.7e10) * 1e6d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Megarutherford, RadioactivityUnit.Becquerel) => new Radioactivity((_value * 1e6) * 1e6d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Microbecquerel, RadioactivityUnit.Becquerel) => new Radioactivity((_value) * 1e-6d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Microcurie, RadioactivityUnit.Becquerel) => new Radioactivity((_value * 3.7e10) * 1e-6d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Microrutherford, RadioactivityUnit.Becquerel) => new Radioactivity((_value * 1e6) * 1e-6d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Millibecquerel, RadioactivityUnit.Becquerel) => new Radioactivity((_value) * 1e-3d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Millicurie, RadioactivityUnit.Becquerel) => new Radioactivity((_value * 3.7e10) * 1e-3d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Millirutherford, RadioactivityUnit.Becquerel) => new Radioactivity((_value * 1e6) * 1e-3d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Nanobecquerel, RadioactivityUnit.Becquerel) => new Radioactivity((_value) * 1e-9d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Nanocurie, RadioactivityUnit.Becquerel) => new Radioactivity((_value * 3.7e10) * 1e-9d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Nanorutherford, RadioactivityUnit.Becquerel) => new Radioactivity((_value * 1e6) * 1e-9d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Petabecquerel, RadioactivityUnit.Becquerel) => new Radioactivity((_value) * 1e15d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Picobecquerel, RadioactivityUnit.Becquerel) => new Radioactivity((_value) * 1e-12d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Picocurie, RadioactivityUnit.Becquerel) => new Radioactivity((_value * 3.7e10) * 1e-12d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Picorutherford, RadioactivityUnit.Becquerel) => new Radioactivity((_value * 1e6) * 1e-12d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Rutherford, RadioactivityUnit.Becquerel) => new Radioactivity(_value * 1e6, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Terabecquerel, RadioactivityUnit.Becquerel) => new Radioactivity((_value) * 1e12d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Teracurie, RadioactivityUnit.Becquerel) => new Radioactivity((_value * 3.7e10) * 1e12d, RadioactivityUnit.Becquerel), - (RadioactivityUnit.Terarutherford, RadioactivityUnit.Becquerel) => new Radioactivity((_value * 1e6) * 1e12d, RadioactivityUnit.Becquerel), - - // BaseUnit -> RadioactivityUnit - (RadioactivityUnit.Becquerel, RadioactivityUnit.Curie) => new Radioactivity(_value / 3.7e10, RadioactivityUnit.Curie), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Exabecquerel) => new Radioactivity((_value) / 1e18d, RadioactivityUnit.Exabecquerel), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Gigabecquerel) => new Radioactivity((_value) / 1e9d, RadioactivityUnit.Gigabecquerel), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Gigacurie) => new Radioactivity((_value / 3.7e10) / 1e9d, RadioactivityUnit.Gigacurie), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Gigarutherford) => new Radioactivity((_value / 1e6) / 1e9d, RadioactivityUnit.Gigarutherford), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Kilobecquerel) => new Radioactivity((_value) / 1e3d, RadioactivityUnit.Kilobecquerel), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Kilocurie) => new Radioactivity((_value / 3.7e10) / 1e3d, RadioactivityUnit.Kilocurie), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Kilorutherford) => new Radioactivity((_value / 1e6) / 1e3d, RadioactivityUnit.Kilorutherford), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Megabecquerel) => new Radioactivity((_value) / 1e6d, RadioactivityUnit.Megabecquerel), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Megacurie) => new Radioactivity((_value / 3.7e10) / 1e6d, RadioactivityUnit.Megacurie), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Megarutherford) => new Radioactivity((_value / 1e6) / 1e6d, RadioactivityUnit.Megarutherford), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Microbecquerel) => new Radioactivity((_value) / 1e-6d, RadioactivityUnit.Microbecquerel), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Microcurie) => new Radioactivity((_value / 3.7e10) / 1e-6d, RadioactivityUnit.Microcurie), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Microrutherford) => new Radioactivity((_value / 1e6) / 1e-6d, RadioactivityUnit.Microrutherford), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Millibecquerel) => new Radioactivity((_value) / 1e-3d, RadioactivityUnit.Millibecquerel), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Millicurie) => new Radioactivity((_value / 3.7e10) / 1e-3d, RadioactivityUnit.Millicurie), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Millirutherford) => new Radioactivity((_value / 1e6) / 1e-3d, RadioactivityUnit.Millirutherford), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Nanobecquerel) => new Radioactivity((_value) / 1e-9d, RadioactivityUnit.Nanobecquerel), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Nanocurie) => new Radioactivity((_value / 3.7e10) / 1e-9d, RadioactivityUnit.Nanocurie), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Nanorutherford) => new Radioactivity((_value / 1e6) / 1e-9d, RadioactivityUnit.Nanorutherford), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Petabecquerel) => new Radioactivity((_value) / 1e15d, RadioactivityUnit.Petabecquerel), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Picobecquerel) => new Radioactivity((_value) / 1e-12d, RadioactivityUnit.Picobecquerel), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Picocurie) => new Radioactivity((_value / 3.7e10) / 1e-12d, RadioactivityUnit.Picocurie), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Picorutherford) => new Radioactivity((_value / 1e6) / 1e-12d, RadioactivityUnit.Picorutherford), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Rutherford) => new Radioactivity(_value / 1e6, RadioactivityUnit.Rutherford), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Terabecquerel) => new Radioactivity((_value) / 1e12d, RadioactivityUnit.Terabecquerel), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Teracurie) => new Radioactivity((_value / 3.7e10) / 1e12d, RadioactivityUnit.Teracurie), - (RadioactivityUnit.Becquerel, RadioactivityUnit.Terarutherford) => new Radioactivity((_value / 1e6) / 1e12d, RadioactivityUnit.Terarutherford), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Radioactivity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not RadioactivityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RadioactivityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is RadioactivityUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RadioactivityUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(RadioactivityUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(RadioactivityUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1251,7 +1033,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs b/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs index de18d006b5..34daf5a39f 100644 --- a/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Ratio.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Ratio : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly RatioUnit? _unit; /// @@ -117,19 +116,27 @@ public static RatioInfo CreateDefault(Func public static IEnumerable> GetDefaultMappings() { yield return new (RatioUnit.DecimalFraction, "DecimalFraction", "DecimalFractions", BaseUnits.Undefined); - yield return new (RatioUnit.PartPerBillion, "PartPerBillion", "PartsPerBillion", BaseUnits.Undefined); - yield return new (RatioUnit.PartPerMillion, "PartPerMillion", "PartsPerMillion", BaseUnits.Undefined); - yield return new (RatioUnit.PartPerThousand, "PartPerThousand", "PartsPerThousand", BaseUnits.Undefined); - yield return new (RatioUnit.PartPerTrillion, "PartPerTrillion", "PartsPerTrillion", BaseUnits.Undefined); - yield return new (RatioUnit.Percent, "Percent", "Percent", BaseUnits.Undefined); + yield return new (RatioUnit.PartPerBillion, "PartPerBillion", "PartsPerBillion", BaseUnits.Undefined, + 1000000000 + ); + yield return new (RatioUnit.PartPerMillion, "PartPerMillion", "PartsPerMillion", BaseUnits.Undefined, + 1000000 + ); + yield return new (RatioUnit.PartPerThousand, "PartPerThousand", "PartsPerThousand", BaseUnits.Undefined, + 1000 + ); + yield return new (RatioUnit.PartPerTrillion, "PartPerTrillion", "PartsPerTrillion", BaseUnits.Undefined, + 1000000000000 + ); + yield return new (RatioUnit.Percent, "Percent", "Percent", BaseUnits.Undefined, + 100 + ); } } static Ratio() { - Info = RatioInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(RatioInfo.CreateDefault); } /// @@ -137,7 +144,7 @@ static Ratio() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Ratio(double value, RatioUnit unit) + public Ratio(QuantityValue value, RatioUnit unit) { _value = value; _unit = unit; @@ -148,7 +155,8 @@ public Ratio(double value, RatioUnit unit) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -177,10 +185,8 @@ public Ratio(double value, RatioUnit unit) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public RatioUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -219,63 +225,39 @@ public Ratio(double value, RatioUnit unit) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecimalFractions => As(RatioUnit.DecimalFraction); + public QuantityValue DecimalFractions => this.As(RatioUnit.DecimalFraction); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PartsPerBillion => As(RatioUnit.PartPerBillion); + public QuantityValue PartsPerBillion => this.As(RatioUnit.PartPerBillion); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PartsPerMillion => As(RatioUnit.PartPerMillion); + public QuantityValue PartsPerMillion => this.As(RatioUnit.PartPerMillion); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PartsPerThousand => As(RatioUnit.PartPerThousand); + public QuantityValue PartsPerThousand => this.As(RatioUnit.PartPerThousand); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PartsPerTrillion => As(RatioUnit.PartPerTrillion); + public QuantityValue PartsPerTrillion => this.As(RatioUnit.PartPerTrillion); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Percent => As(RatioUnit.Percent); + public QuantityValue Percent => this.As(RatioUnit.Percent); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: RatioUnit -> BaseUnit - unitConverter.SetConversionFunction(RatioUnit.PartPerBillion, RatioUnit.DecimalFraction, quantity => quantity.ToUnit(RatioUnit.DecimalFraction)); - unitConverter.SetConversionFunction(RatioUnit.PartPerMillion, RatioUnit.DecimalFraction, quantity => quantity.ToUnit(RatioUnit.DecimalFraction)); - unitConverter.SetConversionFunction(RatioUnit.PartPerThousand, RatioUnit.DecimalFraction, quantity => quantity.ToUnit(RatioUnit.DecimalFraction)); - unitConverter.SetConversionFunction(RatioUnit.PartPerTrillion, RatioUnit.DecimalFraction, quantity => quantity.ToUnit(RatioUnit.DecimalFraction)); - unitConverter.SetConversionFunction(RatioUnit.Percent, RatioUnit.DecimalFraction, quantity => quantity.ToUnit(RatioUnit.DecimalFraction)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(RatioUnit.DecimalFraction, RatioUnit.DecimalFraction, quantity => quantity); - - // Register in unit converter: BaseUnit -> RatioUnit - unitConverter.SetConversionFunction(RatioUnit.DecimalFraction, RatioUnit.PartPerBillion, quantity => quantity.ToUnit(RatioUnit.PartPerBillion)); - unitConverter.SetConversionFunction(RatioUnit.DecimalFraction, RatioUnit.PartPerMillion, quantity => quantity.ToUnit(RatioUnit.PartPerMillion)); - unitConverter.SetConversionFunction(RatioUnit.DecimalFraction, RatioUnit.PartPerThousand, quantity => quantity.ToUnit(RatioUnit.PartPerThousand)); - unitConverter.SetConversionFunction(RatioUnit.DecimalFraction, RatioUnit.PartPerTrillion, quantity => quantity.ToUnit(RatioUnit.PartPerTrillion)); - unitConverter.SetConversionFunction(RatioUnit.DecimalFraction, RatioUnit.Percent, quantity => quantity.ToUnit(RatioUnit.Percent)); - } - /// /// Get unit abbreviation string. /// @@ -304,7 +286,7 @@ public static string GetAbbreviation(RatioUnit unit, IFormatProvider? provider) /// /// Creates a from . /// - public static Ratio FromDecimalFractions(double value) + public static Ratio FromDecimalFractions(QuantityValue value) { return new Ratio(value, RatioUnit.DecimalFraction); } @@ -312,7 +294,7 @@ public static Ratio FromDecimalFractions(double value) /// /// Creates a from . /// - public static Ratio FromPartsPerBillion(double value) + public static Ratio FromPartsPerBillion(QuantityValue value) { return new Ratio(value, RatioUnit.PartPerBillion); } @@ -320,7 +302,7 @@ public static Ratio FromPartsPerBillion(double value) /// /// Creates a from . /// - public static Ratio FromPartsPerMillion(double value) + public static Ratio FromPartsPerMillion(QuantityValue value) { return new Ratio(value, RatioUnit.PartPerMillion); } @@ -328,7 +310,7 @@ public static Ratio FromPartsPerMillion(double value) /// /// Creates a from . /// - public static Ratio FromPartsPerThousand(double value) + public static Ratio FromPartsPerThousand(QuantityValue value) { return new Ratio(value, RatioUnit.PartPerThousand); } @@ -336,7 +318,7 @@ public static Ratio FromPartsPerThousand(double value) /// /// Creates a from . /// - public static Ratio FromPartsPerTrillion(double value) + public static Ratio FromPartsPerTrillion(QuantityValue value) { return new Ratio(value, RatioUnit.PartPerTrillion); } @@ -344,7 +326,7 @@ public static Ratio FromPartsPerTrillion(double value) /// /// Creates a from . /// - public static Ratio FromPercent(double value) + public static Ratio FromPercent(QuantityValue value) { return new Ratio(value, RatioUnit.Percent); } @@ -355,7 +337,7 @@ public static Ratio FromPercent(double value) /// Value to convert from. /// Unit to convert from. /// Ratio unit value. - public static Ratio From(double value, RatioUnit fromUnit) + public static Ratio From(QuantityValue value, RatioUnit fromUnit) { return new Ratio(value, fromUnit); } @@ -416,10 +398,7 @@ public static Ratio Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Ratio Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -447,11 +426,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Ratio result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Ratio result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -472,7 +447,7 @@ public static RatioUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -483,7 +458,7 @@ public static RatioUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out RatioUnit unit) { return TryParseUnit(str, null, out unit); @@ -498,7 +473,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out RatioUnit un /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out RatioUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -517,35 +492,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Ratio operator +(Ratio left, Ratio right) { - return new Ratio(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Ratio(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Ratio operator -(Ratio left, Ratio right) { - return new Ratio(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Ratio(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -557,97 +532,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Ratio left, Ratio right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Ratio left, Ratio right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Ratio left, Ratio right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Ratio left, Ratio right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Ratio other, Ratio tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Ratio left, Ratio right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Ratio other, Ratio tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Ratio left, Ratio right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Ratio other, Ratio tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Ratio otherQuantity)) + if (obj is not Ratio otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Ratio other, Ratio tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Ratio other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Ratio. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Ratio), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Ratio otherQuantity)) throw new ArgumentException("Expected type Ratio.", nameof(obj)); + if (obj is not Ratio otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -659,156 +619,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Ratio other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RatioUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Ratio to another Ratio with the unit representation . - /// - /// The unit to convert to. - /// A Ratio with the specified unit. - public Ratio ToUnit(RatioUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Ratio with the specified unit. - public Ratio ToUnit(RatioUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Ratio), Unit, typeof(Ratio), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Ratio)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(RatioUnit unit, [NotNullWhen(true)] out Ratio? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Ratio? convertedOrNull = (Unit, unit) switch - { - // RatioUnit -> BaseUnit - (RatioUnit.PartPerBillion, RatioUnit.DecimalFraction) => new Ratio(_value / 1e9, RatioUnit.DecimalFraction), - (RatioUnit.PartPerMillion, RatioUnit.DecimalFraction) => new Ratio(_value / 1e6, RatioUnit.DecimalFraction), - (RatioUnit.PartPerThousand, RatioUnit.DecimalFraction) => new Ratio(_value / 1e3, RatioUnit.DecimalFraction), - (RatioUnit.PartPerTrillion, RatioUnit.DecimalFraction) => new Ratio(_value / 1e12, RatioUnit.DecimalFraction), - (RatioUnit.Percent, RatioUnit.DecimalFraction) => new Ratio(_value / 1e2, RatioUnit.DecimalFraction), - - // BaseUnit -> RatioUnit - (RatioUnit.DecimalFraction, RatioUnit.PartPerBillion) => new Ratio(_value * 1e9, RatioUnit.PartPerBillion), - (RatioUnit.DecimalFraction, RatioUnit.PartPerMillion) => new Ratio(_value * 1e6, RatioUnit.PartPerMillion), - (RatioUnit.DecimalFraction, RatioUnit.PartPerThousand) => new Ratio(_value * 1e3, RatioUnit.PartPerThousand), - (RatioUnit.DecimalFraction, RatioUnit.PartPerTrillion) => new Ratio(_value * 1e12, RatioUnit.PartPerTrillion), - (RatioUnit.DecimalFraction, RatioUnit.Percent) => new Ratio(_value * 1e2, RatioUnit.Percent), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Ratio ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not RatioUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(RatioUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(RatioUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -823,7 +651,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs index a8c1f5e4ce..b9df2a5a13 100644 --- a/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RatioChangeRate.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// The change in ratio per unit of time. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct RatioChangeRate : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly RatioChangeRateUnit? _unit; /// @@ -101,7 +100,7 @@ public static RatioChangeRateInfo CreateDefault(Func - /// The for is [T^-1]. + /// The for is T^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); @@ -117,15 +116,15 @@ public static RatioChangeRateInfo CreateDefault(Func> GetDefaultMappings() { yield return new (RatioChangeRateUnit.DecimalFractionPerSecond, "DecimalFractionPerSecond", "DecimalFractionsPerSecond", new BaseUnits(time: DurationUnit.Second)); - yield return new (RatioChangeRateUnit.PercentPerSecond, "PercentPerSecond", "PercentsPerSecond", BaseUnits.Undefined); + yield return new (RatioChangeRateUnit.PercentPerSecond, "PercentPerSecond", "PercentsPerSecond", BaseUnits.Undefined, + 100 + ); } } static RatioChangeRate() { - Info = RatioChangeRateInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(RatioChangeRateInfo.CreateDefault); } /// @@ -133,7 +132,7 @@ static RatioChangeRate() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public RatioChangeRate(double value, RatioChangeRateUnit unit) + public RatioChangeRate(QuantityValue value, RatioChangeRateUnit unit) { _value = value; _unit = unit; @@ -147,7 +146,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -158,7 +157,8 @@ public RatioChangeRate(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -187,10 +187,8 @@ public RatioChangeRate(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public RatioChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -229,35 +227,19 @@ public RatioChangeRate(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecimalFractionsPerSecond => As(RatioChangeRateUnit.DecimalFractionPerSecond); + public QuantityValue DecimalFractionsPerSecond => this.As(RatioChangeRateUnit.DecimalFractionPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PercentsPerSecond => As(RatioChangeRateUnit.PercentPerSecond); + public QuantityValue PercentsPerSecond => this.As(RatioChangeRateUnit.PercentPerSecond); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: RatioChangeRateUnit -> BaseUnit - unitConverter.SetConversionFunction(RatioChangeRateUnit.PercentPerSecond, RatioChangeRateUnit.DecimalFractionPerSecond, quantity => quantity.ToUnit(RatioChangeRateUnit.DecimalFractionPerSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(RatioChangeRateUnit.DecimalFractionPerSecond, RatioChangeRateUnit.DecimalFractionPerSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> RatioChangeRateUnit - unitConverter.SetConversionFunction(RatioChangeRateUnit.DecimalFractionPerSecond, RatioChangeRateUnit.PercentPerSecond, quantity => quantity.ToUnit(RatioChangeRateUnit.PercentPerSecond)); - } - /// /// Get unit abbreviation string. /// @@ -286,7 +268,7 @@ public static string GetAbbreviation(RatioChangeRateUnit unit, IFormatProvider? /// /// Creates a from . /// - public static RatioChangeRate FromDecimalFractionsPerSecond(double value) + public static RatioChangeRate FromDecimalFractionsPerSecond(QuantityValue value) { return new RatioChangeRate(value, RatioChangeRateUnit.DecimalFractionPerSecond); } @@ -294,7 +276,7 @@ public static RatioChangeRate FromDecimalFractionsPerSecond(double value) /// /// Creates a from . /// - public static RatioChangeRate FromPercentsPerSecond(double value) + public static RatioChangeRate FromPercentsPerSecond(QuantityValue value) { return new RatioChangeRate(value, RatioChangeRateUnit.PercentPerSecond); } @@ -305,7 +287,7 @@ public static RatioChangeRate FromPercentsPerSecond(double value) /// Value to convert from. /// Unit to convert from. /// RatioChangeRate unit value. - public static RatioChangeRate From(double value, RatioChangeRateUnit fromUnit) + public static RatioChangeRate From(QuantityValue value, RatioChangeRateUnit fromUnit) { return new RatioChangeRate(value, fromUnit); } @@ -366,10 +348,7 @@ public static RatioChangeRate Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static RatioChangeRate Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -397,11 +376,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out RatioChangeRate /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out RatioChangeRate result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -422,7 +397,7 @@ public static RatioChangeRateUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -433,7 +408,7 @@ public static RatioChangeRateUnit ParseUnit(string str, IFormatProvider? provide return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out RatioChangeRateUnit unit) { return TryParseUnit(str, null, out unit); @@ -448,7 +423,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out RatioChangeR /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out RatioChangeRateUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -467,35 +442,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static RatioChangeRate operator +(RatioChangeRate left, RatioChangeRate right) { - return new RatioChangeRate(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new RatioChangeRate(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static RatioChangeRate operator -(RatioChangeRate left, RatioChangeRate right) { - return new RatioChangeRate(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new RatioChangeRate(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -507,97 +482,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(RatioChangeRate left, RatioChangeRate right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(RatioChangeRate left, RatioChangeRate right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(RatioChangeRate left, RatioChangeRate right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(RatioChangeRate left, RatioChangeRate right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RatioChangeRate other, RatioChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(RatioChangeRate left, RatioChangeRate right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RatioChangeRate other, RatioChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(RatioChangeRate left, RatioChangeRate right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RatioChangeRate other, RatioChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is RatioChangeRate otherQuantity)) + if (obj is not RatioChangeRate otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RatioChangeRate other, RatioChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(RatioChangeRate other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current RatioChangeRate. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(RatioChangeRate), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is RatioChangeRate otherQuantity)) throw new ArgumentException("Expected type RatioChangeRate.", nameof(obj)); + if (obj is not RatioChangeRate otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -609,148 +569,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RatioChangeRate other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RatioChangeRateUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this RatioChangeRate to another RatioChangeRate with the unit representation . - /// - /// The unit to convert to. - /// A RatioChangeRate with the specified unit. - public RatioChangeRate ToUnit(RatioChangeRateUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A RatioChangeRate with the specified unit. - public RatioChangeRate ToUnit(RatioChangeRateUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(RatioChangeRate), Unit, typeof(RatioChangeRate), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (RatioChangeRate)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(RatioChangeRateUnit unit, [NotNullWhen(true)] out RatioChangeRate? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - RatioChangeRate? convertedOrNull = (Unit, unit) switch - { - // RatioChangeRateUnit -> BaseUnit - (RatioChangeRateUnit.PercentPerSecond, RatioChangeRateUnit.DecimalFractionPerSecond) => new RatioChangeRate(_value / 1e2, RatioChangeRateUnit.DecimalFractionPerSecond), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> RatioChangeRateUnit - (RatioChangeRateUnit.DecimalFractionPerSecond, RatioChangeRateUnit.PercentPerSecond) => new RatioChangeRate(_value * 1e2, RatioChangeRateUnit.PercentPerSecond), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public RatioChangeRate ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not RatioChangeRateUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioChangeRateUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is RatioChangeRateUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RatioChangeRateUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(RatioChangeRateUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(RatioChangeRateUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -765,7 +601,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs b/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs index 8141b31adf..fa388762b6 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReciprocalArea.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Inverse-square_law /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ReciprocalArea : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -60,13 +59,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ReciprocalAreaUnit? _unit; /// @@ -111,7 +110,7 @@ public static ReciprocalAreaInfo CreateDefault(Func - /// The for is [L^-2]. + /// The for is L^-2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 0, 0, 0, 0, 0, 0); @@ -126,25 +125,43 @@ public static ReciprocalAreaInfo CreateDefault(FuncAn of representing the default unit mappings for ReciprocalArea. public static IEnumerable> GetDefaultMappings() { - yield return new (ReciprocalAreaUnit.InverseSquareCentimeter, "InverseSquareCentimeter", "InverseSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter)); - yield return new (ReciprocalAreaUnit.InverseSquareDecimeter, "InverseSquareDecimeter", "InverseSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter)); - yield return new (ReciprocalAreaUnit.InverseSquareFoot, "InverseSquareFoot", "InverseSquareFeet", new BaseUnits(length: LengthUnit.Foot)); - yield return new (ReciprocalAreaUnit.InverseSquareInch, "InverseSquareInch", "InverseSquareInches", new BaseUnits(length: LengthUnit.Inch)); - yield return new (ReciprocalAreaUnit.InverseSquareKilometer, "InverseSquareKilometer", "InverseSquareKilometers", new BaseUnits(length: LengthUnit.Kilometer)); + yield return new (ReciprocalAreaUnit.InverseSquareCentimeter, "InverseSquareCentimeter", "InverseSquareCentimeters", new BaseUnits(length: LengthUnit.Centimeter), + new QuantityValue(1, 10000) + ); + yield return new (ReciprocalAreaUnit.InverseSquareDecimeter, "InverseSquareDecimeter", "InverseSquareDecimeters", new BaseUnits(length: LengthUnit.Decimeter), + new QuantityValue(1, 100) + ); + yield return new (ReciprocalAreaUnit.InverseSquareFoot, "InverseSquareFoot", "InverseSquareFeet", new BaseUnits(length: LengthUnit.Foot), + new QuantityValue(145161, 1562500) + ); + yield return new (ReciprocalAreaUnit.InverseSquareInch, "InverseSquareInch", "InverseSquareInches", new BaseUnits(length: LengthUnit.Inch), + new QuantityValue(16129, 25000000) + ); + yield return new (ReciprocalAreaUnit.InverseSquareKilometer, "InverseSquareKilometer", "InverseSquareKilometers", new BaseUnits(length: LengthUnit.Kilometer), + 1000000 + ); yield return new (ReciprocalAreaUnit.InverseSquareMeter, "InverseSquareMeter", "InverseSquareMeters", new BaseUnits(length: LengthUnit.Meter)); - yield return new (ReciprocalAreaUnit.InverseSquareMicrometer, "InverseSquareMicrometer", "InverseSquareMicrometers", new BaseUnits(length: LengthUnit.Micrometer)); - yield return new (ReciprocalAreaUnit.InverseSquareMile, "InverseSquareMile", "InverseSquareMiles", new BaseUnits(length: LengthUnit.Mile)); - yield return new (ReciprocalAreaUnit.InverseSquareMillimeter, "InverseSquareMillimeter", "InverseSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter)); - yield return new (ReciprocalAreaUnit.InverseSquareYard, "InverseSquareYard", "InverseSquareYards", new BaseUnits(length: LengthUnit.Yard)); - yield return new (ReciprocalAreaUnit.InverseUsSurveySquareFoot, "InverseUsSurveySquareFoot", "InverseUsSurveySquareFeet", new BaseUnits(length: LengthUnit.UsSurveyFoot)); + yield return new (ReciprocalAreaUnit.InverseSquareMicrometer, "InverseSquareMicrometer", "InverseSquareMicrometers", new BaseUnits(length: LengthUnit.Micrometer), + new QuantityValue(1, 1000000000000) + ); + yield return new (ReciprocalAreaUnit.InverseSquareMile, "InverseSquareMile", "InverseSquareMiles", new BaseUnits(length: LengthUnit.Mile), + new QuantityValue(40468564224, 15625) + ); + yield return new (ReciprocalAreaUnit.InverseSquareMillimeter, "InverseSquareMillimeter", "InverseSquareMillimeters", new BaseUnits(length: LengthUnit.Millimeter), + new QuantityValue(1, 1000000) + ); + yield return new (ReciprocalAreaUnit.InverseSquareYard, "InverseSquareYard", "InverseSquareYards", new BaseUnits(length: LengthUnit.Yard), + new QuantityValue(1306449, 1562500) + ); + yield return new (ReciprocalAreaUnit.InverseUsSurveySquareFoot, "InverseUsSurveySquareFoot", "InverseUsSurveySquareFeet", new BaseUnits(length: LengthUnit.UsSurveyFoot), + new QuantityValue(1440000, 15499969) + ); } } static ReciprocalArea() { - Info = ReciprocalAreaInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ReciprocalAreaInfo.CreateDefault); } /// @@ -152,7 +169,7 @@ static ReciprocalArea() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ReciprocalArea(double value, ReciprocalAreaUnit unit) + public ReciprocalArea(QuantityValue value, ReciprocalAreaUnit unit) { _value = value; _unit = unit; @@ -166,7 +183,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -177,7 +194,8 @@ public ReciprocalArea(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -206,10 +224,8 @@ public ReciprocalArea(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ReciprocalAreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -248,98 +264,64 @@ public ReciprocalArea(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseSquareCentimeters => As(ReciprocalAreaUnit.InverseSquareCentimeter); + public QuantityValue InverseSquareCentimeters => this.As(ReciprocalAreaUnit.InverseSquareCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseSquareDecimeters => As(ReciprocalAreaUnit.InverseSquareDecimeter); + public QuantityValue InverseSquareDecimeters => this.As(ReciprocalAreaUnit.InverseSquareDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseSquareFeet => As(ReciprocalAreaUnit.InverseSquareFoot); + public QuantityValue InverseSquareFeet => this.As(ReciprocalAreaUnit.InverseSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseSquareInches => As(ReciprocalAreaUnit.InverseSquareInch); + public QuantityValue InverseSquareInches => this.As(ReciprocalAreaUnit.InverseSquareInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseSquareKilometers => As(ReciprocalAreaUnit.InverseSquareKilometer); + public QuantityValue InverseSquareKilometers => this.As(ReciprocalAreaUnit.InverseSquareKilometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseSquareMeters => As(ReciprocalAreaUnit.InverseSquareMeter); + public QuantityValue InverseSquareMeters => this.As(ReciprocalAreaUnit.InverseSquareMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseSquareMicrometers => As(ReciprocalAreaUnit.InverseSquareMicrometer); + public QuantityValue InverseSquareMicrometers => this.As(ReciprocalAreaUnit.InverseSquareMicrometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseSquareMiles => As(ReciprocalAreaUnit.InverseSquareMile); + public QuantityValue InverseSquareMiles => this.As(ReciprocalAreaUnit.InverseSquareMile); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseSquareMillimeters => As(ReciprocalAreaUnit.InverseSquareMillimeter); + public QuantityValue InverseSquareMillimeters => this.As(ReciprocalAreaUnit.InverseSquareMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseSquareYards => As(ReciprocalAreaUnit.InverseSquareYard); + public QuantityValue InverseSquareYards => this.As(ReciprocalAreaUnit.InverseSquareYard); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseUsSurveySquareFeet => As(ReciprocalAreaUnit.InverseUsSurveySquareFoot); + public QuantityValue InverseUsSurveySquareFeet => this.As(ReciprocalAreaUnit.InverseUsSurveySquareFoot); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ReciprocalAreaUnit -> BaseUnit - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareCentimeter, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareDecimeter, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareFoot, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareInch, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareKilometer, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMicrometer, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMile, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMillimeter, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareYard, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseUsSurveySquareFoot, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> ReciprocalAreaUnit - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareCentimeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareCentimeter)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareDecimeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareDecimeter)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareFoot, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareFoot)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareInch, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareInch)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareKilometer, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareKilometer)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMicrometer, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMicrometer)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMile, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMile)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMillimeter, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareMillimeter)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareYard, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseSquareYard)); - unitConverter.SetConversionFunction(ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseUsSurveySquareFoot, quantity => quantity.ToUnit(ReciprocalAreaUnit.InverseUsSurveySquareFoot)); - } - /// /// Get unit abbreviation string. /// @@ -368,7 +350,7 @@ public static string GetAbbreviation(ReciprocalAreaUnit unit, IFormatProvider? p /// /// Creates a from . /// - public static ReciprocalArea FromInverseSquareCentimeters(double value) + public static ReciprocalArea FromInverseSquareCentimeters(QuantityValue value) { return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareCentimeter); } @@ -376,7 +358,7 @@ public static ReciprocalArea FromInverseSquareCentimeters(double value) /// /// Creates a from . /// - public static ReciprocalArea FromInverseSquareDecimeters(double value) + public static ReciprocalArea FromInverseSquareDecimeters(QuantityValue value) { return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareDecimeter); } @@ -384,7 +366,7 @@ public static ReciprocalArea FromInverseSquareDecimeters(double value) /// /// Creates a from . /// - public static ReciprocalArea FromInverseSquareFeet(double value) + public static ReciprocalArea FromInverseSquareFeet(QuantityValue value) { return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareFoot); } @@ -392,7 +374,7 @@ public static ReciprocalArea FromInverseSquareFeet(double value) /// /// Creates a from . /// - public static ReciprocalArea FromInverseSquareInches(double value) + public static ReciprocalArea FromInverseSquareInches(QuantityValue value) { return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareInch); } @@ -400,7 +382,7 @@ public static ReciprocalArea FromInverseSquareInches(double value) /// /// Creates a from . /// - public static ReciprocalArea FromInverseSquareKilometers(double value) + public static ReciprocalArea FromInverseSquareKilometers(QuantityValue value) { return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareKilometer); } @@ -408,7 +390,7 @@ public static ReciprocalArea FromInverseSquareKilometers(double value) /// /// Creates a from . /// - public static ReciprocalArea FromInverseSquareMeters(double value) + public static ReciprocalArea FromInverseSquareMeters(QuantityValue value) { return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareMeter); } @@ -416,7 +398,7 @@ public static ReciprocalArea FromInverseSquareMeters(double value) /// /// Creates a from . /// - public static ReciprocalArea FromInverseSquareMicrometers(double value) + public static ReciprocalArea FromInverseSquareMicrometers(QuantityValue value) { return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareMicrometer); } @@ -424,7 +406,7 @@ public static ReciprocalArea FromInverseSquareMicrometers(double value) /// /// Creates a from . /// - public static ReciprocalArea FromInverseSquareMiles(double value) + public static ReciprocalArea FromInverseSquareMiles(QuantityValue value) { return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareMile); } @@ -432,7 +414,7 @@ public static ReciprocalArea FromInverseSquareMiles(double value) /// /// Creates a from . /// - public static ReciprocalArea FromInverseSquareMillimeters(double value) + public static ReciprocalArea FromInverseSquareMillimeters(QuantityValue value) { return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareMillimeter); } @@ -440,7 +422,7 @@ public static ReciprocalArea FromInverseSquareMillimeters(double value) /// /// Creates a from . /// - public static ReciprocalArea FromInverseSquareYards(double value) + public static ReciprocalArea FromInverseSquareYards(QuantityValue value) { return new ReciprocalArea(value, ReciprocalAreaUnit.InverseSquareYard); } @@ -448,7 +430,7 @@ public static ReciprocalArea FromInverseSquareYards(double value) /// /// Creates a from . /// - public static ReciprocalArea FromInverseUsSurveySquareFeet(double value) + public static ReciprocalArea FromInverseUsSurveySquareFeet(QuantityValue value) { return new ReciprocalArea(value, ReciprocalAreaUnit.InverseUsSurveySquareFoot); } @@ -459,7 +441,7 @@ public static ReciprocalArea FromInverseUsSurveySquareFeet(double value) /// Value to convert from. /// Unit to convert from. /// ReciprocalArea unit value. - public static ReciprocalArea From(double value, ReciprocalAreaUnit fromUnit) + public static ReciprocalArea From(QuantityValue value, ReciprocalAreaUnit fromUnit) { return new ReciprocalArea(value, fromUnit); } @@ -520,10 +502,7 @@ public static ReciprocalArea Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ReciprocalArea Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -551,11 +530,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ReciprocalArea r /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ReciprocalArea result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -576,7 +551,7 @@ public static ReciprocalAreaUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -587,7 +562,7 @@ public static ReciprocalAreaUnit ParseUnit(string str, IFormatProvider? provider return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ReciprocalAreaUnit unit) { return TryParseUnit(str, null, out unit); @@ -602,7 +577,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ReciprocalAr /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ReciprocalAreaUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -621,35 +596,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ReciprocalArea operator +(ReciprocalArea left, ReciprocalArea right) { - return new ReciprocalArea(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ReciprocalArea(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ReciprocalArea operator -(ReciprocalArea left, ReciprocalArea right) { - return new ReciprocalArea(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ReciprocalArea(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -662,7 +637,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// The corresponding inverse quantity, . public Area Inverse() { - return Area.FromSquareMeters(1 / InverseSquareMeters); + return UnitConverter.Default.ConvertTo(Value, Unit, Area.Info); } /// Get from * . @@ -702,97 +677,82 @@ public Area Inverse() /// Returns true if less or equal to. public static bool operator <=(ReciprocalArea left, ReciprocalArea right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ReciprocalArea left, ReciprocalArea right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ReciprocalArea left, ReciprocalArea right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ReciprocalArea left, ReciprocalArea right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ReciprocalArea other, ReciprocalArea tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ReciprocalArea left, ReciprocalArea right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ReciprocalArea other, ReciprocalArea tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ReciprocalArea left, ReciprocalArea right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ReciprocalArea other, ReciprocalArea tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ReciprocalArea otherQuantity)) + if (obj is not ReciprocalArea otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ReciprocalArea other, ReciprocalArea tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ReciprocalArea other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ReciprocalArea. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ReciprocalArea), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ReciprocalArea otherQuantity)) throw new ArgumentException("Expected type ReciprocalArea.", nameof(obj)); + if (obj is not ReciprocalArea otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -804,166 +764,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ReciprocalArea other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ReciprocalAreaUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this ReciprocalArea to another ReciprocalArea with the unit representation . - /// - /// The unit to convert to. - /// A ReciprocalArea with the specified unit. - public ReciprocalArea ToUnit(ReciprocalAreaUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ReciprocalArea with the specified unit. - public ReciprocalArea ToUnit(ReciprocalAreaUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ReciprocalArea), Unit, typeof(ReciprocalArea), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ReciprocalArea)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ReciprocalAreaUnit unit, [NotNullWhen(true)] out ReciprocalArea? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ReciprocalArea? convertedOrNull = (Unit, unit) switch - { - // ReciprocalAreaUnit -> BaseUnit - (ReciprocalAreaUnit.InverseSquareCentimeter, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / 1e-4, ReciprocalAreaUnit.InverseSquareMeter), - (ReciprocalAreaUnit.InverseSquareDecimeter, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / 1e-2, ReciprocalAreaUnit.InverseSquareMeter), - (ReciprocalAreaUnit.InverseSquareFoot, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / 9.290304e-2, ReciprocalAreaUnit.InverseSquareMeter), - (ReciprocalAreaUnit.InverseSquareInch, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / 0.00064516, ReciprocalAreaUnit.InverseSquareMeter), - (ReciprocalAreaUnit.InverseSquareKilometer, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / 1e6, ReciprocalAreaUnit.InverseSquareMeter), - (ReciprocalAreaUnit.InverseSquareMicrometer, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / 1e-12, ReciprocalAreaUnit.InverseSquareMeter), - (ReciprocalAreaUnit.InverseSquareMile, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / (1609.344 * 1609.344), ReciprocalAreaUnit.InverseSquareMeter), - (ReciprocalAreaUnit.InverseSquareMillimeter, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / 1e-6, ReciprocalAreaUnit.InverseSquareMeter), - (ReciprocalAreaUnit.InverseSquareYard, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / (0.9144 * 0.9144), ReciprocalAreaUnit.InverseSquareMeter), - (ReciprocalAreaUnit.InverseUsSurveySquareFoot, ReciprocalAreaUnit.InverseSquareMeter) => new ReciprocalArea(_value / (1200.0 / 3937.0) / (1200.0 / 3937.0), ReciprocalAreaUnit.InverseSquareMeter), - - // BaseUnit -> ReciprocalAreaUnit - (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareCentimeter) => new ReciprocalArea(_value * 1e-4, ReciprocalAreaUnit.InverseSquareCentimeter), - (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareDecimeter) => new ReciprocalArea(_value * 1e-2, ReciprocalAreaUnit.InverseSquareDecimeter), - (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareFoot) => new ReciprocalArea(_value * 9.290304e-2, ReciprocalAreaUnit.InverseSquareFoot), - (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareInch) => new ReciprocalArea(_value * 0.00064516, ReciprocalAreaUnit.InverseSquareInch), - (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareKilometer) => new ReciprocalArea(_value * 1e6, ReciprocalAreaUnit.InverseSquareKilometer), - (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMicrometer) => new ReciprocalArea(_value * 1e-12, ReciprocalAreaUnit.InverseSquareMicrometer), - (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMile) => new ReciprocalArea(_value * (1609.344 * 1609.344), ReciprocalAreaUnit.InverseSquareMile), - (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareMillimeter) => new ReciprocalArea(_value * 1e-6, ReciprocalAreaUnit.InverseSquareMillimeter), - (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseSquareYard) => new ReciprocalArea(_value * (0.9144 * 0.9144), ReciprocalAreaUnit.InverseSquareYard), - (ReciprocalAreaUnit.InverseSquareMeter, ReciprocalAreaUnit.InverseUsSurveySquareFoot) => new ReciprocalArea(_value * (1200.0 / 3937.0) * (1200.0 / 3937.0), ReciprocalAreaUnit.InverseUsSurveySquareFoot), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ReciprocalArea ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ReciprocalAreaUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReciprocalAreaUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ReciprocalAreaUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ReciprocalAreaUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -978,7 +796,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs b/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs index 9dae1bcbe1..3161785efb 100644 --- a/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ReciprocalLength.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Reciprocal_length /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ReciprocalLength : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -62,13 +61,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ReciprocalLengthUnit? _unit; /// @@ -113,7 +112,7 @@ public static ReciprocalLengthInfo CreateDefault(Func - /// The for is [L^-1]. + /// The for is L^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 0, 0, 0, 0, 0, 0); @@ -128,24 +127,40 @@ public static ReciprocalLengthInfo CreateDefault(FuncAn of representing the default unit mappings for ReciprocalLength. public static IEnumerable> GetDefaultMappings() { - yield return new (ReciprocalLengthUnit.InverseCentimeter, "InverseCentimeter", "InverseCentimeters", new BaseUnits(length: LengthUnit.Centimeter)); - yield return new (ReciprocalLengthUnit.InverseFoot, "InverseFoot", "InverseFeet", new BaseUnits(length: LengthUnit.Foot)); - yield return new (ReciprocalLengthUnit.InverseInch, "InverseInch", "InverseInches", new BaseUnits(length: LengthUnit.Inch)); + yield return new (ReciprocalLengthUnit.InverseCentimeter, "InverseCentimeter", "InverseCentimeters", new BaseUnits(length: LengthUnit.Centimeter), + new QuantityValue(1, 100) + ); + yield return new (ReciprocalLengthUnit.InverseFoot, "InverseFoot", "InverseFeet", new BaseUnits(length: LengthUnit.Foot), + new QuantityValue(381, 1250) + ); + yield return new (ReciprocalLengthUnit.InverseInch, "InverseInch", "InverseInches", new BaseUnits(length: LengthUnit.Inch), + new QuantityValue(127, 5000) + ); yield return new (ReciprocalLengthUnit.InverseMeter, "InverseMeter", "InverseMeters", new BaseUnits(length: LengthUnit.Meter)); - yield return new (ReciprocalLengthUnit.InverseMicroinch, "InverseMicroinch", "InverseMicroinches", new BaseUnits(length: LengthUnit.Microinch)); - yield return new (ReciprocalLengthUnit.InverseMil, "InverseMil", "InverseMils", new BaseUnits(length: LengthUnit.Mil)); - yield return new (ReciprocalLengthUnit.InverseMile, "InverseMile", "InverseMiles", new BaseUnits(length: LengthUnit.Mile)); - yield return new (ReciprocalLengthUnit.InverseMillimeter, "InverseMillimeter", "InverseMillimeters", new BaseUnits(length: LengthUnit.Millimeter)); - yield return new (ReciprocalLengthUnit.InverseUsSurveyFoot, "InverseUsSurveyFoot", "InverseUsSurveyFeet", new BaseUnits(length: LengthUnit.UsSurveyFoot)); - yield return new (ReciprocalLengthUnit.InverseYard, "InverseYard", "InverseYards", new BaseUnits(length: LengthUnit.Yard)); + yield return new (ReciprocalLengthUnit.InverseMicroinch, "InverseMicroinch", "InverseMicroinches", new BaseUnits(length: LengthUnit.Microinch), + new QuantityValue(127, 5000000000) + ); + yield return new (ReciprocalLengthUnit.InverseMil, "InverseMil", "InverseMils", new BaseUnits(length: LengthUnit.Mil), + new QuantityValue(127, 5000000) + ); + yield return new (ReciprocalLengthUnit.InverseMile, "InverseMile", "InverseMiles", new BaseUnits(length: LengthUnit.Mile), + new QuantityValue(201168, 125) + ); + yield return new (ReciprocalLengthUnit.InverseMillimeter, "InverseMillimeter", "InverseMillimeters", new BaseUnits(length: LengthUnit.Millimeter), + new QuantityValue(1, 1000) + ); + yield return new (ReciprocalLengthUnit.InverseUsSurveyFoot, "InverseUsSurveyFoot", "InverseUsSurveyFeet", new BaseUnits(length: LengthUnit.UsSurveyFoot), + new QuantityValue(1200, 3937) + ); + yield return new (ReciprocalLengthUnit.InverseYard, "InverseYard", "InverseYards", new BaseUnits(length: LengthUnit.Yard), + new QuantityValue(1143, 1250) + ); } } static ReciprocalLength() { - Info = ReciprocalLengthInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ReciprocalLengthInfo.CreateDefault); } /// @@ -153,7 +168,7 @@ static ReciprocalLength() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ReciprocalLength(double value, ReciprocalLengthUnit unit) + public ReciprocalLength(QuantityValue value, ReciprocalLengthUnit unit) { _value = value; _unit = unit; @@ -167,7 +182,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -178,7 +193,8 @@ public ReciprocalLength(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -207,10 +223,8 @@ public ReciprocalLength(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ReciprocalLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -249,91 +263,59 @@ public ReciprocalLength(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseCentimeters => As(ReciprocalLengthUnit.InverseCentimeter); + public QuantityValue InverseCentimeters => this.As(ReciprocalLengthUnit.InverseCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseFeet => As(ReciprocalLengthUnit.InverseFoot); + public QuantityValue InverseFeet => this.As(ReciprocalLengthUnit.InverseFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseInches => As(ReciprocalLengthUnit.InverseInch); + public QuantityValue InverseInches => this.As(ReciprocalLengthUnit.InverseInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseMeters => As(ReciprocalLengthUnit.InverseMeter); + public QuantityValue InverseMeters => this.As(ReciprocalLengthUnit.InverseMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseMicroinches => As(ReciprocalLengthUnit.InverseMicroinch); + public QuantityValue InverseMicroinches => this.As(ReciprocalLengthUnit.InverseMicroinch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseMils => As(ReciprocalLengthUnit.InverseMil); + public QuantityValue InverseMils => this.As(ReciprocalLengthUnit.InverseMil); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseMiles => As(ReciprocalLengthUnit.InverseMile); + public QuantityValue InverseMiles => this.As(ReciprocalLengthUnit.InverseMile); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseMillimeters => As(ReciprocalLengthUnit.InverseMillimeter); + public QuantityValue InverseMillimeters => this.As(ReciprocalLengthUnit.InverseMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseUsSurveyFeet => As(ReciprocalLengthUnit.InverseUsSurveyFoot); + public QuantityValue InverseUsSurveyFeet => this.As(ReciprocalLengthUnit.InverseUsSurveyFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InverseYards => As(ReciprocalLengthUnit.InverseYard); + public QuantityValue InverseYards => this.As(ReciprocalLengthUnit.InverseYard); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ReciprocalLengthUnit -> BaseUnit - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseCentimeter, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseFoot, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseInch, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMicroinch, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMil, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMile, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMillimeter, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseUsSurveyFoot, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseYard, ReciprocalLengthUnit.InverseMeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> ReciprocalLengthUnit - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseCentimeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseCentimeter)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseFoot, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseFoot)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseInch, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseInch)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMicroinch, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMicroinch)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMil, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMil)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMile, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMile)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMillimeter, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseMillimeter)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseUsSurveyFoot, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseUsSurveyFoot)); - unitConverter.SetConversionFunction(ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseYard, quantity => quantity.ToUnit(ReciprocalLengthUnit.InverseYard)); - } - /// /// Get unit abbreviation string. /// @@ -362,7 +344,7 @@ public static string GetAbbreviation(ReciprocalLengthUnit unit, IFormatProvider? /// /// Creates a from . /// - public static ReciprocalLength FromInverseCentimeters(double value) + public static ReciprocalLength FromInverseCentimeters(QuantityValue value) { return new ReciprocalLength(value, ReciprocalLengthUnit.InverseCentimeter); } @@ -370,7 +352,7 @@ public static ReciprocalLength FromInverseCentimeters(double value) /// /// Creates a from . /// - public static ReciprocalLength FromInverseFeet(double value) + public static ReciprocalLength FromInverseFeet(QuantityValue value) { return new ReciprocalLength(value, ReciprocalLengthUnit.InverseFoot); } @@ -378,7 +360,7 @@ public static ReciprocalLength FromInverseFeet(double value) /// /// Creates a from . /// - public static ReciprocalLength FromInverseInches(double value) + public static ReciprocalLength FromInverseInches(QuantityValue value) { return new ReciprocalLength(value, ReciprocalLengthUnit.InverseInch); } @@ -386,7 +368,7 @@ public static ReciprocalLength FromInverseInches(double value) /// /// Creates a from . /// - public static ReciprocalLength FromInverseMeters(double value) + public static ReciprocalLength FromInverseMeters(QuantityValue value) { return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMeter); } @@ -394,7 +376,7 @@ public static ReciprocalLength FromInverseMeters(double value) /// /// Creates a from . /// - public static ReciprocalLength FromInverseMicroinches(double value) + public static ReciprocalLength FromInverseMicroinches(QuantityValue value) { return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMicroinch); } @@ -402,7 +384,7 @@ public static ReciprocalLength FromInverseMicroinches(double value) /// /// Creates a from . /// - public static ReciprocalLength FromInverseMils(double value) + public static ReciprocalLength FromInverseMils(QuantityValue value) { return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMil); } @@ -410,7 +392,7 @@ public static ReciprocalLength FromInverseMils(double value) /// /// Creates a from . /// - public static ReciprocalLength FromInverseMiles(double value) + public static ReciprocalLength FromInverseMiles(QuantityValue value) { return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMile); } @@ -418,7 +400,7 @@ public static ReciprocalLength FromInverseMiles(double value) /// /// Creates a from . /// - public static ReciprocalLength FromInverseMillimeters(double value) + public static ReciprocalLength FromInverseMillimeters(QuantityValue value) { return new ReciprocalLength(value, ReciprocalLengthUnit.InverseMillimeter); } @@ -426,7 +408,7 @@ public static ReciprocalLength FromInverseMillimeters(double value) /// /// Creates a from . /// - public static ReciprocalLength FromInverseUsSurveyFeet(double value) + public static ReciprocalLength FromInverseUsSurveyFeet(QuantityValue value) { return new ReciprocalLength(value, ReciprocalLengthUnit.InverseUsSurveyFoot); } @@ -434,7 +416,7 @@ public static ReciprocalLength FromInverseUsSurveyFeet(double value) /// /// Creates a from . /// - public static ReciprocalLength FromInverseYards(double value) + public static ReciprocalLength FromInverseYards(QuantityValue value) { return new ReciprocalLength(value, ReciprocalLengthUnit.InverseYard); } @@ -445,7 +427,7 @@ public static ReciprocalLength FromInverseYards(double value) /// Value to convert from. /// Unit to convert from. /// ReciprocalLength unit value. - public static ReciprocalLength From(double value, ReciprocalLengthUnit fromUnit) + public static ReciprocalLength From(QuantityValue value, ReciprocalLengthUnit fromUnit) { return new ReciprocalLength(value, fromUnit); } @@ -506,10 +488,7 @@ public static ReciprocalLength Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ReciprocalLength Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -537,11 +516,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ReciprocalLength /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ReciprocalLength result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -562,7 +537,7 @@ public static ReciprocalLengthUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -573,7 +548,7 @@ public static ReciprocalLengthUnit ParseUnit(string str, IFormatProvider? provid return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ReciprocalLengthUnit unit) { return TryParseUnit(str, null, out unit); @@ -588,7 +563,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ReciprocalLe /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ReciprocalLengthUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -607,35 +582,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ReciprocalLength operator +(ReciprocalLength left, ReciprocalLength right) { - return new ReciprocalLength(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ReciprocalLength(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ReciprocalLength operator -(ReciprocalLength left, ReciprocalLength right) { - return new ReciprocalLength(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ReciprocalLength(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -648,7 +623,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// The corresponding inverse quantity, . public Length Inverse() { - return Length.FromMeters(1 / InverseMeters); + return UnitConverter.Default.ConvertTo(Value, Unit, Length.Info); } /// Get from * . @@ -700,97 +675,82 @@ public Length Inverse() /// Returns true if less or equal to. public static bool operator <=(ReciprocalLength left, ReciprocalLength right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ReciprocalLength left, ReciprocalLength right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ReciprocalLength left, ReciprocalLength right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ReciprocalLength left, ReciprocalLength right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ReciprocalLength other, ReciprocalLength tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ReciprocalLength left, ReciprocalLength right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ReciprocalLength other, ReciprocalLength tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ReciprocalLength left, ReciprocalLength right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ReciprocalLength other, ReciprocalLength tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ReciprocalLength otherQuantity)) + if (obj is not ReciprocalLength otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ReciprocalLength other, ReciprocalLength tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ReciprocalLength other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ReciprocalLength. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ReciprocalLength), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ReciprocalLength otherQuantity)) throw new ArgumentException("Expected type ReciprocalLength.", nameof(obj)); + if (obj is not ReciprocalLength otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -802,164 +762,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ReciprocalLength other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ReciprocalLengthUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this ReciprocalLength to another ReciprocalLength with the unit representation . - /// - /// The unit to convert to. - /// A ReciprocalLength with the specified unit. - public ReciprocalLength ToUnit(ReciprocalLengthUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ReciprocalLength with the specified unit. - public ReciprocalLength ToUnit(ReciprocalLengthUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ReciprocalLength), Unit, typeof(ReciprocalLength), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ReciprocalLength)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ReciprocalLengthUnit unit, [NotNullWhen(true)] out ReciprocalLength? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ReciprocalLength? convertedOrNull = (Unit, unit) switch - { - // ReciprocalLengthUnit -> BaseUnit - (ReciprocalLengthUnit.InverseCentimeter, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value * 1e2, ReciprocalLengthUnit.InverseMeter), - (ReciprocalLengthUnit.InverseFoot, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value / 0.3048, ReciprocalLengthUnit.InverseMeter), - (ReciprocalLengthUnit.InverseInch, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value / 2.54e-2, ReciprocalLengthUnit.InverseMeter), - (ReciprocalLengthUnit.InverseMicroinch, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value / 2.54e-8, ReciprocalLengthUnit.InverseMeter), - (ReciprocalLengthUnit.InverseMil, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value / 2.54e-5, ReciprocalLengthUnit.InverseMeter), - (ReciprocalLengthUnit.InverseMile, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value / 1609.344, ReciprocalLengthUnit.InverseMeter), - (ReciprocalLengthUnit.InverseMillimeter, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value * 1e3, ReciprocalLengthUnit.InverseMeter), - (ReciprocalLengthUnit.InverseUsSurveyFoot, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value * 3937 / 1200, ReciprocalLengthUnit.InverseMeter), - (ReciprocalLengthUnit.InverseYard, ReciprocalLengthUnit.InverseMeter) => new ReciprocalLength(_value / 0.9144, ReciprocalLengthUnit.InverseMeter), - - // BaseUnit -> ReciprocalLengthUnit - (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseCentimeter) => new ReciprocalLength(_value / 1e2, ReciprocalLengthUnit.InverseCentimeter), - (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseFoot) => new ReciprocalLength(_value * 0.3048, ReciprocalLengthUnit.InverseFoot), - (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseInch) => new ReciprocalLength(_value * 2.54e-2, ReciprocalLengthUnit.InverseInch), - (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMicroinch) => new ReciprocalLength(_value * 2.54e-8, ReciprocalLengthUnit.InverseMicroinch), - (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMil) => new ReciprocalLength(_value * 2.54e-5, ReciprocalLengthUnit.InverseMil), - (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMile) => new ReciprocalLength(_value * 1609.344, ReciprocalLengthUnit.InverseMile), - (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseMillimeter) => new ReciprocalLength(_value / 1e3, ReciprocalLengthUnit.InverseMillimeter), - (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseUsSurveyFoot) => new ReciprocalLength(_value * 1200 / 3937, ReciprocalLengthUnit.InverseUsSurveyFoot), - (ReciprocalLengthUnit.InverseMeter, ReciprocalLengthUnit.InverseYard) => new ReciprocalLength(_value * 0.9144, ReciprocalLengthUnit.InverseYard), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ReciprocalLength ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ReciprocalLengthUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ReciprocalLengthUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ReciprocalLengthUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ReciprocalLengthUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -974,7 +794,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs b/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs index 48f4a44b03..c5522bd201 100644 --- a/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RelativeHumidity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct RelativeHumidity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly RelativeHumidityUnit? _unit; /// @@ -122,9 +121,7 @@ public static IEnumerable> GetDefaultMappin static RelativeHumidity() { - Info = RelativeHumidityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(RelativeHumidityInfo.CreateDefault); } /// @@ -132,7 +129,7 @@ static RelativeHumidity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public RelativeHumidity(double value, RelativeHumidityUnit unit) + public RelativeHumidity(QuantityValue value, RelativeHumidityUnit unit) { _value = value; _unit = unit; @@ -143,7 +140,8 @@ public RelativeHumidity(double value, RelativeHumidityUnit unit) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -172,10 +170,8 @@ public RelativeHumidity(double value, RelativeHumidityUnit unit) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public RelativeHumidityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -214,28 +210,14 @@ public RelativeHumidity(double value, RelativeHumidityUnit unit) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Percent => As(RelativeHumidityUnit.Percent); + public QuantityValue Percent => this.As(RelativeHumidityUnit.Percent); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: RelativeHumidityUnit -> BaseUnit - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(RelativeHumidityUnit.Percent, RelativeHumidityUnit.Percent, quantity => quantity); - - // Register in unit converter: BaseUnit -> RelativeHumidityUnit - } - /// /// Get unit abbreviation string. /// @@ -264,7 +246,7 @@ public static string GetAbbreviation(RelativeHumidityUnit unit, IFormatProvider? /// /// Creates a from . /// - public static RelativeHumidity FromPercent(double value) + public static RelativeHumidity FromPercent(QuantityValue value) { return new RelativeHumidity(value, RelativeHumidityUnit.Percent); } @@ -275,7 +257,7 @@ public static RelativeHumidity FromPercent(double value) /// Value to convert from. /// Unit to convert from. /// RelativeHumidity unit value. - public static RelativeHumidity From(double value, RelativeHumidityUnit fromUnit) + public static RelativeHumidity From(QuantityValue value, RelativeHumidityUnit fromUnit) { return new RelativeHumidity(value, fromUnit); } @@ -336,10 +318,7 @@ public static RelativeHumidity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static RelativeHumidity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -367,11 +346,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out RelativeHumidity /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out RelativeHumidity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -392,7 +367,7 @@ public static RelativeHumidityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -403,7 +378,7 @@ public static RelativeHumidityUnit ParseUnit(string str, IFormatProvider? provid return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out RelativeHumidityUnit unit) { return TryParseUnit(str, null, out unit); @@ -418,7 +393,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out RelativeHumi /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out RelativeHumidityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -437,35 +412,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static RelativeHumidity operator +(RelativeHumidity left, RelativeHumidity right) { - return new RelativeHumidity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new RelativeHumidity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static RelativeHumidity operator -(RelativeHumidity left, RelativeHumidity right) { - return new RelativeHumidity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new RelativeHumidity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -477,97 +452,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(RelativeHumidity left, RelativeHumidity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(RelativeHumidity left, RelativeHumidity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(RelativeHumidity left, RelativeHumidity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(RelativeHumidity left, RelativeHumidity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RelativeHumidity other, RelativeHumidity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(RelativeHumidity left, RelativeHumidity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RelativeHumidity other, RelativeHumidity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(RelativeHumidity left, RelativeHumidity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RelativeHumidity other, RelativeHumidity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is RelativeHumidity otherQuantity)) + if (obj is not RelativeHumidity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RelativeHumidity other, RelativeHumidity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(RelativeHumidity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current RelativeHumidity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(RelativeHumidity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is RelativeHumidity otherQuantity)) throw new ArgumentException("Expected type RelativeHumidity.", nameof(obj)); + if (obj is not RelativeHumidity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -579,146 +539,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RelativeHumidity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RelativeHumidityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this RelativeHumidity to another RelativeHumidity with the unit representation . - /// - /// The unit to convert to. - /// A RelativeHumidity with the specified unit. - public RelativeHumidity ToUnit(RelativeHumidityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A RelativeHumidity with the specified unit. - public RelativeHumidity ToUnit(RelativeHumidityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(RelativeHumidity), Unit, typeof(RelativeHumidity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (RelativeHumidity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(RelativeHumidityUnit unit, [NotNullWhen(true)] out RelativeHumidity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - RelativeHumidity? convertedOrNull = (Unit, unit) switch - { - // RelativeHumidityUnit -> BaseUnit + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> RelativeHumidityUnit - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public RelativeHumidity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not RelativeHumidityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RelativeHumidityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is RelativeHumidityUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RelativeHumidityUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(RelativeHumidityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(RelativeHumidityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -733,7 +571,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs index 766ccebbf7..78c54f3595 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalAcceleration.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// Angular acceleration is the rate of change of rotational speed. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct RotationalAcceleration : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly RotationalAccelerationUnit? _unit; /// @@ -101,7 +100,7 @@ public static RotationalAccelerationInfo CreateDefault(Func - /// The for is [T^-2]. + /// The for is T^-2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -2, 0, 0, 0, 0); @@ -116,18 +115,22 @@ public static RotationalAccelerationInfo CreateDefault(FuncAn of representing the default unit mappings for RotationalAcceleration. public static IEnumerable> GetDefaultMappings() { - yield return new (RotationalAccelerationUnit.DegreePerSecondSquared, "DegreePerSecondSquared", "DegreesPerSecondSquared", BaseUnits.Undefined); + yield return new (RotationalAccelerationUnit.DegreePerSecondSquared, "DegreePerSecondSquared", "DegreesPerSecondSquared", BaseUnits.Undefined, + new QuantityValue(180000000000000000, 3141592653589793) + ); yield return new (RotationalAccelerationUnit.RadianPerSecondSquared, "RadianPerSecondSquared", "RadiansPerSecondSquared", new BaseUnits(time: DurationUnit.Second)); - yield return new (RotationalAccelerationUnit.RevolutionPerMinutePerSecond, "RevolutionPerMinutePerSecond", "RevolutionsPerMinutePerSecond", BaseUnits.Undefined); - yield return new (RotationalAccelerationUnit.RevolutionPerSecondSquared, "RevolutionPerSecondSquared", "RevolutionsPerSecondSquared", BaseUnits.Undefined); + yield return new (RotationalAccelerationUnit.RevolutionPerMinutePerSecond, "RevolutionPerMinutePerSecond", "RevolutionsPerMinutePerSecond", BaseUnits.Undefined, + new QuantityValue(30000000000000000, 3141592653589793) + ); + yield return new (RotationalAccelerationUnit.RevolutionPerSecondSquared, "RevolutionPerSecondSquared", "RevolutionsPerSecondSquared", BaseUnits.Undefined, + new QuantityValue(500000000000000, 3141592653589793) + ); } } static RotationalAcceleration() { - Info = RotationalAccelerationInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(RotationalAccelerationInfo.CreateDefault); } /// @@ -135,7 +138,7 @@ static RotationalAcceleration() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public RotationalAcceleration(double value, RotationalAccelerationUnit unit) + public RotationalAcceleration(QuantityValue value, RotationalAccelerationUnit unit) { _value = value; _unit = unit; @@ -149,7 +152,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -160,7 +163,8 @@ public RotationalAcceleration(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -189,10 +193,8 @@ public RotationalAcceleration(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public RotationalAccelerationUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -231,49 +233,29 @@ public RotationalAcceleration(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesPerSecondSquared => As(RotationalAccelerationUnit.DegreePerSecondSquared); + public QuantityValue DegreesPerSecondSquared => this.As(RotationalAccelerationUnit.DegreePerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double RadiansPerSecondSquared => As(RotationalAccelerationUnit.RadianPerSecondSquared); + public QuantityValue RadiansPerSecondSquared => this.As(RotationalAccelerationUnit.RadianPerSecondSquared); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double RevolutionsPerMinutePerSecond => As(RotationalAccelerationUnit.RevolutionPerMinutePerSecond); + public QuantityValue RevolutionsPerMinutePerSecond => this.As(RotationalAccelerationUnit.RevolutionPerMinutePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double RevolutionsPerSecondSquared => As(RotationalAccelerationUnit.RevolutionPerSecondSquared); + public QuantityValue RevolutionsPerSecondSquared => this.As(RotationalAccelerationUnit.RevolutionPerSecondSquared); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: RotationalAccelerationUnit -> BaseUnit - unitConverter.SetConversionFunction(RotationalAccelerationUnit.DegreePerSecondSquared, RotationalAccelerationUnit.RadianPerSecondSquared, quantity => quantity.ToUnit(RotationalAccelerationUnit.RadianPerSecondSquared)); - unitConverter.SetConversionFunction(RotationalAccelerationUnit.RevolutionPerMinutePerSecond, RotationalAccelerationUnit.RadianPerSecondSquared, quantity => quantity.ToUnit(RotationalAccelerationUnit.RadianPerSecondSquared)); - unitConverter.SetConversionFunction(RotationalAccelerationUnit.RevolutionPerSecondSquared, RotationalAccelerationUnit.RadianPerSecondSquared, quantity => quantity.ToUnit(RotationalAccelerationUnit.RadianPerSecondSquared)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.RadianPerSecondSquared, quantity => quantity); - - // Register in unit converter: BaseUnit -> RotationalAccelerationUnit - unitConverter.SetConversionFunction(RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.DegreePerSecondSquared, quantity => quantity.ToUnit(RotationalAccelerationUnit.DegreePerSecondSquared)); - unitConverter.SetConversionFunction(RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.RevolutionPerMinutePerSecond, quantity => quantity.ToUnit(RotationalAccelerationUnit.RevolutionPerMinutePerSecond)); - unitConverter.SetConversionFunction(RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.RevolutionPerSecondSquared, quantity => quantity.ToUnit(RotationalAccelerationUnit.RevolutionPerSecondSquared)); - } - /// /// Get unit abbreviation string. /// @@ -302,7 +284,7 @@ public static string GetAbbreviation(RotationalAccelerationUnit unit, IFormatPro /// /// Creates a from . /// - public static RotationalAcceleration FromDegreesPerSecondSquared(double value) + public static RotationalAcceleration FromDegreesPerSecondSquared(QuantityValue value) { return new RotationalAcceleration(value, RotationalAccelerationUnit.DegreePerSecondSquared); } @@ -310,7 +292,7 @@ public static RotationalAcceleration FromDegreesPerSecondSquared(double value) /// /// Creates a from . /// - public static RotationalAcceleration FromRadiansPerSecondSquared(double value) + public static RotationalAcceleration FromRadiansPerSecondSquared(QuantityValue value) { return new RotationalAcceleration(value, RotationalAccelerationUnit.RadianPerSecondSquared); } @@ -318,7 +300,7 @@ public static RotationalAcceleration FromRadiansPerSecondSquared(double value) /// /// Creates a from . /// - public static RotationalAcceleration FromRevolutionsPerMinutePerSecond(double value) + public static RotationalAcceleration FromRevolutionsPerMinutePerSecond(QuantityValue value) { return new RotationalAcceleration(value, RotationalAccelerationUnit.RevolutionPerMinutePerSecond); } @@ -326,7 +308,7 @@ public static RotationalAcceleration FromRevolutionsPerMinutePerSecond(double va /// /// Creates a from . /// - public static RotationalAcceleration FromRevolutionsPerSecondSquared(double value) + public static RotationalAcceleration FromRevolutionsPerSecondSquared(QuantityValue value) { return new RotationalAcceleration(value, RotationalAccelerationUnit.RevolutionPerSecondSquared); } @@ -337,7 +319,7 @@ public static RotationalAcceleration FromRevolutionsPerSecondSquared(double valu /// Value to convert from. /// Unit to convert from. /// RotationalAcceleration unit value. - public static RotationalAcceleration From(double value, RotationalAccelerationUnit fromUnit) + public static RotationalAcceleration From(QuantityValue value, RotationalAccelerationUnit fromUnit) { return new RotationalAcceleration(value, fromUnit); } @@ -398,10 +380,7 @@ public static RotationalAcceleration Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static RotationalAcceleration Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -429,11 +408,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out RotationalAccele /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out RotationalAcceleration result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -454,7 +429,7 @@ public static RotationalAccelerationUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -465,7 +440,7 @@ public static RotationalAccelerationUnit ParseUnit(string str, IFormatProvider? return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out RotationalAccelerationUnit unit) { return TryParseUnit(str, null, out unit); @@ -480,7 +455,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out RotationalAc /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out RotationalAccelerationUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -499,35 +474,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static RotationalAcceleration operator +(RotationalAcceleration left, RotationalAcceleration right) { - return new RotationalAcceleration(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new RotationalAcceleration(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static RotationalAcceleration operator -(RotationalAcceleration left, RotationalAcceleration right) { - return new RotationalAcceleration(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new RotationalAcceleration(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -539,97 +514,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(RotationalAcceleration left, RotationalAcceleration right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(RotationalAcceleration left, RotationalAcceleration right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(RotationalAcceleration left, RotationalAcceleration right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(RotationalAcceleration left, RotationalAcceleration right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RotationalAcceleration other, RotationalAcceleration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(RotationalAcceleration left, RotationalAcceleration right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RotationalAcceleration other, RotationalAcceleration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(RotationalAcceleration left, RotationalAcceleration right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RotationalAcceleration other, RotationalAcceleration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is RotationalAcceleration otherQuantity)) + if (obj is not RotationalAcceleration otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RotationalAcceleration other, RotationalAcceleration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(RotationalAcceleration other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current RotationalAcceleration. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(RotationalAcceleration), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is RotationalAcceleration otherQuantity)) throw new ArgumentException("Expected type RotationalAcceleration.", nameof(obj)); + if (obj is not RotationalAcceleration otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -641,152 +601,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RotationalAcceleration other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalAccelerationUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this RotationalAcceleration to another RotationalAcceleration with the unit representation . - /// - /// The unit to convert to. - /// A RotationalAcceleration with the specified unit. - public RotationalAcceleration ToUnit(RotationalAccelerationUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A RotationalAcceleration with the specified unit. - public RotationalAcceleration ToUnit(RotationalAccelerationUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(RotationalAcceleration), Unit, typeof(RotationalAcceleration), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (RotationalAcceleration)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(RotationalAccelerationUnit unit, [NotNullWhen(true)] out RotationalAcceleration? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - RotationalAcceleration? convertedOrNull = (Unit, unit) switch - { - // RotationalAccelerationUnit -> BaseUnit - (RotationalAccelerationUnit.DegreePerSecondSquared, RotationalAccelerationUnit.RadianPerSecondSquared) => new RotationalAcceleration((Math.PI / 180) * _value, RotationalAccelerationUnit.RadianPerSecondSquared), - (RotationalAccelerationUnit.RevolutionPerMinutePerSecond, RotationalAccelerationUnit.RadianPerSecondSquared) => new RotationalAcceleration(((2 * Math.PI) / 60) * _value, RotationalAccelerationUnit.RadianPerSecondSquared), - (RotationalAccelerationUnit.RevolutionPerSecondSquared, RotationalAccelerationUnit.RadianPerSecondSquared) => new RotationalAcceleration((2 * Math.PI) * _value, RotationalAccelerationUnit.RadianPerSecondSquared), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> RotationalAccelerationUnit - (RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.DegreePerSecondSquared) => new RotationalAcceleration((180 / Math.PI) * _value, RotationalAccelerationUnit.DegreePerSecondSquared), - (RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.RevolutionPerMinutePerSecond) => new RotationalAcceleration((60 / (2 * Math.PI)) * _value, RotationalAccelerationUnit.RevolutionPerMinutePerSecond), - (RotationalAccelerationUnit.RadianPerSecondSquared, RotationalAccelerationUnit.RevolutionPerSecondSquared) => new RotationalAcceleration((1 / (2 * Math.PI)) * _value, RotationalAccelerationUnit.RevolutionPerSecondSquared), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public RotationalAcceleration ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not RotationalAccelerationUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalAccelerationUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is RotationalAccelerationUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalAccelerationUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(RotationalAccelerationUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(RotationalAccelerationUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -801,7 +633,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs index e236d4a261..fdda54ae17 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalSpeed.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct RotationalSpeed : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -54,13 +53,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly RotationalSpeedUnit? _unit; /// @@ -105,7 +104,7 @@ public static RotationalSpeedInfo CreateDefault(Func - /// The for is [T^-1]. + /// The for is T^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -1, 0, 0, 0, 0); @@ -120,27 +119,49 @@ public static RotationalSpeedInfo CreateDefault(FuncAn of representing the default unit mappings for RotationalSpeed. public static IEnumerable> GetDefaultMappings() { - yield return new (RotationalSpeedUnit.CentiradianPerSecond, "CentiradianPerSecond", "CentiradiansPerSecond", BaseUnits.Undefined); - yield return new (RotationalSpeedUnit.DeciradianPerSecond, "DeciradianPerSecond", "DeciradiansPerSecond", BaseUnits.Undefined); - yield return new (RotationalSpeedUnit.DegreePerMinute, "DegreePerMinute", "DegreesPerMinute", BaseUnits.Undefined); - yield return new (RotationalSpeedUnit.DegreePerSecond, "DegreePerSecond", "DegreesPerSecond", BaseUnits.Undefined); - yield return new (RotationalSpeedUnit.MicrodegreePerSecond, "MicrodegreePerSecond", "MicrodegreesPerSecond", BaseUnits.Undefined); - yield return new (RotationalSpeedUnit.MicroradianPerSecond, "MicroradianPerSecond", "MicroradiansPerSecond", BaseUnits.Undefined); - yield return new (RotationalSpeedUnit.MillidegreePerSecond, "MillidegreePerSecond", "MillidegreesPerSecond", BaseUnits.Undefined); - yield return new (RotationalSpeedUnit.MilliradianPerSecond, "MilliradianPerSecond", "MilliradiansPerSecond", BaseUnits.Undefined); - yield return new (RotationalSpeedUnit.NanodegreePerSecond, "NanodegreePerSecond", "NanodegreesPerSecond", BaseUnits.Undefined); - yield return new (RotationalSpeedUnit.NanoradianPerSecond, "NanoradianPerSecond", "NanoradiansPerSecond", BaseUnits.Undefined); + yield return new (RotationalSpeedUnit.CentiradianPerSecond, "CentiradianPerSecond", "CentiradiansPerSecond", BaseUnits.Undefined, + 100 + ); + yield return new (RotationalSpeedUnit.DeciradianPerSecond, "DeciradianPerSecond", "DeciradiansPerSecond", BaseUnits.Undefined, + 10 + ); + yield return new (RotationalSpeedUnit.DegreePerMinute, "DegreePerMinute", "DegreesPerMinute", BaseUnits.Undefined, + new QuantityValue(new BigInteger(108) * QuantityValue.PowerOfTen(17), 3141592653589793) + ); + yield return new (RotationalSpeedUnit.DegreePerSecond, "DegreePerSecond", "DegreesPerSecond", BaseUnits.Undefined, + new QuantityValue(180000000000000000, 3141592653589793) + ); + yield return new (RotationalSpeedUnit.MicrodegreePerSecond, "MicrodegreePerSecond", "MicrodegreesPerSecond", BaseUnits.Undefined, + new QuantityValue(new BigInteger(18) * QuantityValue.PowerOfTen(22), 3141592653589793) + ); + yield return new (RotationalSpeedUnit.MicroradianPerSecond, "MicroradianPerSecond", "MicroradiansPerSecond", BaseUnits.Undefined, + 1000000 + ); + yield return new (RotationalSpeedUnit.MillidegreePerSecond, "MillidegreePerSecond", "MillidegreesPerSecond", BaseUnits.Undefined, + new QuantityValue(new BigInteger(18) * QuantityValue.PowerOfTen(19), 3141592653589793) + ); + yield return new (RotationalSpeedUnit.MilliradianPerSecond, "MilliradianPerSecond", "MilliradiansPerSecond", BaseUnits.Undefined, + 1000 + ); + yield return new (RotationalSpeedUnit.NanodegreePerSecond, "NanodegreePerSecond", "NanodegreesPerSecond", BaseUnits.Undefined, + new QuantityValue(new BigInteger(18) * QuantityValue.PowerOfTen(25), 3141592653589793) + ); + yield return new (RotationalSpeedUnit.NanoradianPerSecond, "NanoradianPerSecond", "NanoradiansPerSecond", BaseUnits.Undefined, + 1000000000 + ); yield return new (RotationalSpeedUnit.RadianPerSecond, "RadianPerSecond", "RadiansPerSecond", new BaseUnits(time: DurationUnit.Second)); - yield return new (RotationalSpeedUnit.RevolutionPerMinute, "RevolutionPerMinute", "RevolutionsPerMinute", BaseUnits.Undefined); - yield return new (RotationalSpeedUnit.RevolutionPerSecond, "RevolutionPerSecond", "RevolutionsPerSecond", BaseUnits.Undefined); + yield return new (RotationalSpeedUnit.RevolutionPerMinute, "RevolutionPerMinute", "RevolutionsPerMinute", BaseUnits.Undefined, + new QuantityValue(30000000000000000, 3141592653589793) + ); + yield return new (RotationalSpeedUnit.RevolutionPerSecond, "RevolutionPerSecond", "RevolutionsPerSecond", BaseUnits.Undefined, + new QuantityValue(500000000000000, 3141592653589793) + ); } } static RotationalSpeed() { - Info = RotationalSpeedInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(RotationalSpeedInfo.CreateDefault); } /// @@ -148,7 +169,7 @@ static RotationalSpeed() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public RotationalSpeed(double value, RotationalSpeedUnit unit) + public RotationalSpeed(QuantityValue value, RotationalSpeedUnit unit) { _value = value; _unit = unit; @@ -162,7 +183,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -173,7 +194,8 @@ public RotationalSpeed(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -202,10 +224,8 @@ public RotationalSpeed(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public RotationalSpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -244,112 +264,74 @@ public RotationalSpeed(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentiradiansPerSecond => As(RotationalSpeedUnit.CentiradianPerSecond); + public QuantityValue CentiradiansPerSecond => this.As(RotationalSpeedUnit.CentiradianPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DeciradiansPerSecond => As(RotationalSpeedUnit.DeciradianPerSecond); + public QuantityValue DeciradiansPerSecond => this.As(RotationalSpeedUnit.DeciradianPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesPerMinute => As(RotationalSpeedUnit.DegreePerMinute); + public QuantityValue DegreesPerMinute => this.As(RotationalSpeedUnit.DegreePerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesPerSecond => As(RotationalSpeedUnit.DegreePerSecond); + public QuantityValue DegreesPerSecond => this.As(RotationalSpeedUnit.DegreePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrodegreesPerSecond => As(RotationalSpeedUnit.MicrodegreePerSecond); + public QuantityValue MicrodegreesPerSecond => this.As(RotationalSpeedUnit.MicrodegreePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicroradiansPerSecond => As(RotationalSpeedUnit.MicroradianPerSecond); + public QuantityValue MicroradiansPerSecond => this.As(RotationalSpeedUnit.MicroradianPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillidegreesPerSecond => As(RotationalSpeedUnit.MillidegreePerSecond); + public QuantityValue MillidegreesPerSecond => this.As(RotationalSpeedUnit.MillidegreePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilliradiansPerSecond => As(RotationalSpeedUnit.MilliradianPerSecond); + public QuantityValue MilliradiansPerSecond => this.As(RotationalSpeedUnit.MilliradianPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanodegreesPerSecond => As(RotationalSpeedUnit.NanodegreePerSecond); + public QuantityValue NanodegreesPerSecond => this.As(RotationalSpeedUnit.NanodegreePerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanoradiansPerSecond => As(RotationalSpeedUnit.NanoradianPerSecond); + public QuantityValue NanoradiansPerSecond => this.As(RotationalSpeedUnit.NanoradianPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double RadiansPerSecond => As(RotationalSpeedUnit.RadianPerSecond); + public QuantityValue RadiansPerSecond => this.As(RotationalSpeedUnit.RadianPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double RevolutionsPerMinute => As(RotationalSpeedUnit.RevolutionPerMinute); + public QuantityValue RevolutionsPerMinute => this.As(RotationalSpeedUnit.RevolutionPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double RevolutionsPerSecond => As(RotationalSpeedUnit.RevolutionPerSecond); + public QuantityValue RevolutionsPerSecond => this.As(RotationalSpeedUnit.RevolutionPerSecond); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: RotationalSpeedUnit -> BaseUnit - unitConverter.SetConversionFunction(RotationalSpeedUnit.CentiradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.DeciradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.DegreePerMinute, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.DegreePerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.MicrodegreePerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.MicroradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.MillidegreePerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.MilliradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.NanodegreePerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.NanoradianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RevolutionPerMinute, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RevolutionPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RadianPerSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.RadianPerSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> RotationalSpeedUnit - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.CentiradianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.CentiradianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DeciradianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.DeciradianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DegreePerMinute, quantity => quantity.ToUnit(RotationalSpeedUnit.DegreePerMinute)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DegreePerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.DegreePerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MicrodegreePerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.MicrodegreePerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MicroradianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.MicroradianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MillidegreePerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.MillidegreePerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MilliradianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.MilliradianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.NanodegreePerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.NanodegreePerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.NanoradianPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.NanoradianPerSecond)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.RevolutionPerMinute, quantity => quantity.ToUnit(RotationalSpeedUnit.RevolutionPerMinute)); - unitConverter.SetConversionFunction(RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.RevolutionPerSecond, quantity => quantity.ToUnit(RotationalSpeedUnit.RevolutionPerSecond)); - } - /// /// Get unit abbreviation string. /// @@ -378,7 +360,7 @@ public static string GetAbbreviation(RotationalSpeedUnit unit, IFormatProvider? /// /// Creates a from . /// - public static RotationalSpeed FromCentiradiansPerSecond(double value) + public static RotationalSpeed FromCentiradiansPerSecond(QuantityValue value) { return new RotationalSpeed(value, RotationalSpeedUnit.CentiradianPerSecond); } @@ -386,7 +368,7 @@ public static RotationalSpeed FromCentiradiansPerSecond(double value) /// /// Creates a from . /// - public static RotationalSpeed FromDeciradiansPerSecond(double value) + public static RotationalSpeed FromDeciradiansPerSecond(QuantityValue value) { return new RotationalSpeed(value, RotationalSpeedUnit.DeciradianPerSecond); } @@ -394,7 +376,7 @@ public static RotationalSpeed FromDeciradiansPerSecond(double value) /// /// Creates a from . /// - public static RotationalSpeed FromDegreesPerMinute(double value) + public static RotationalSpeed FromDegreesPerMinute(QuantityValue value) { return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerMinute); } @@ -402,7 +384,7 @@ public static RotationalSpeed FromDegreesPerMinute(double value) /// /// Creates a from . /// - public static RotationalSpeed FromDegreesPerSecond(double value) + public static RotationalSpeed FromDegreesPerSecond(QuantityValue value) { return new RotationalSpeed(value, RotationalSpeedUnit.DegreePerSecond); } @@ -410,7 +392,7 @@ public static RotationalSpeed FromDegreesPerSecond(double value) /// /// Creates a from . /// - public static RotationalSpeed FromMicrodegreesPerSecond(double value) + public static RotationalSpeed FromMicrodegreesPerSecond(QuantityValue value) { return new RotationalSpeed(value, RotationalSpeedUnit.MicrodegreePerSecond); } @@ -418,7 +400,7 @@ public static RotationalSpeed FromMicrodegreesPerSecond(double value) /// /// Creates a from . /// - public static RotationalSpeed FromMicroradiansPerSecond(double value) + public static RotationalSpeed FromMicroradiansPerSecond(QuantityValue value) { return new RotationalSpeed(value, RotationalSpeedUnit.MicroradianPerSecond); } @@ -426,7 +408,7 @@ public static RotationalSpeed FromMicroradiansPerSecond(double value) /// /// Creates a from . /// - public static RotationalSpeed FromMillidegreesPerSecond(double value) + public static RotationalSpeed FromMillidegreesPerSecond(QuantityValue value) { return new RotationalSpeed(value, RotationalSpeedUnit.MillidegreePerSecond); } @@ -434,7 +416,7 @@ public static RotationalSpeed FromMillidegreesPerSecond(double value) /// /// Creates a from . /// - public static RotationalSpeed FromMilliradiansPerSecond(double value) + public static RotationalSpeed FromMilliradiansPerSecond(QuantityValue value) { return new RotationalSpeed(value, RotationalSpeedUnit.MilliradianPerSecond); } @@ -442,7 +424,7 @@ public static RotationalSpeed FromMilliradiansPerSecond(double value) /// /// Creates a from . /// - public static RotationalSpeed FromNanodegreesPerSecond(double value) + public static RotationalSpeed FromNanodegreesPerSecond(QuantityValue value) { return new RotationalSpeed(value, RotationalSpeedUnit.NanodegreePerSecond); } @@ -450,7 +432,7 @@ public static RotationalSpeed FromNanodegreesPerSecond(double value) /// /// Creates a from . /// - public static RotationalSpeed FromNanoradiansPerSecond(double value) + public static RotationalSpeed FromNanoradiansPerSecond(QuantityValue value) { return new RotationalSpeed(value, RotationalSpeedUnit.NanoradianPerSecond); } @@ -458,7 +440,7 @@ public static RotationalSpeed FromNanoradiansPerSecond(double value) /// /// Creates a from . /// - public static RotationalSpeed FromRadiansPerSecond(double value) + public static RotationalSpeed FromRadiansPerSecond(QuantityValue value) { return new RotationalSpeed(value, RotationalSpeedUnit.RadianPerSecond); } @@ -466,7 +448,7 @@ public static RotationalSpeed FromRadiansPerSecond(double value) /// /// Creates a from . /// - public static RotationalSpeed FromRevolutionsPerMinute(double value) + public static RotationalSpeed FromRevolutionsPerMinute(QuantityValue value) { return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerMinute); } @@ -474,7 +456,7 @@ public static RotationalSpeed FromRevolutionsPerMinute(double value) /// /// Creates a from . /// - public static RotationalSpeed FromRevolutionsPerSecond(double value) + public static RotationalSpeed FromRevolutionsPerSecond(QuantityValue value) { return new RotationalSpeed(value, RotationalSpeedUnit.RevolutionPerSecond); } @@ -485,7 +467,7 @@ public static RotationalSpeed FromRevolutionsPerSecond(double value) /// Value to convert from. /// Unit to convert from. /// RotationalSpeed unit value. - public static RotationalSpeed From(double value, RotationalSpeedUnit fromUnit) + public static RotationalSpeed From(QuantityValue value, RotationalSpeedUnit fromUnit) { return new RotationalSpeed(value, fromUnit); } @@ -546,10 +528,7 @@ public static RotationalSpeed Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static RotationalSpeed Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -577,11 +556,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out RotationalSpeed /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out RotationalSpeed result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -602,7 +577,7 @@ public static RotationalSpeedUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -613,7 +588,7 @@ public static RotationalSpeedUnit ParseUnit(string str, IFormatProvider? provide return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out RotationalSpeedUnit unit) { return TryParseUnit(str, null, out unit); @@ -628,7 +603,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out RotationalSp /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out RotationalSpeedUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -647,35 +622,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static RotationalSpeed operator +(RotationalSpeed left, RotationalSpeed right) { - return new RotationalSpeed(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new RotationalSpeed(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static RotationalSpeed operator -(RotationalSpeed left, RotationalSpeed right) { - return new RotationalSpeed(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new RotationalSpeed(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -703,97 +678,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(RotationalSpeed left, RotationalSpeed right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(RotationalSpeed left, RotationalSpeed right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(RotationalSpeed left, RotationalSpeed right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(RotationalSpeed left, RotationalSpeed right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RotationalSpeed other, RotationalSpeed tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(RotationalSpeed left, RotationalSpeed right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RotationalSpeed other, RotationalSpeed tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(RotationalSpeed left, RotationalSpeed right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RotationalSpeed other, RotationalSpeed tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is RotationalSpeed otherQuantity)) + if (obj is not RotationalSpeed otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RotationalSpeed other, RotationalSpeed tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(RotationalSpeed other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current RotationalSpeed. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(RotationalSpeed), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is RotationalSpeed otherQuantity)) throw new ArgumentException("Expected type RotationalSpeed.", nameof(obj)); + if (obj is not RotationalSpeed otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -805,170 +765,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RotationalSpeed other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalSpeedUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this RotationalSpeed to another RotationalSpeed with the unit representation . - /// - /// The unit to convert to. - /// A RotationalSpeed with the specified unit. - public RotationalSpeed ToUnit(RotationalSpeedUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A RotationalSpeed with the specified unit. - public RotationalSpeed ToUnit(RotationalSpeedUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(RotationalSpeed), Unit, typeof(RotationalSpeed), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (RotationalSpeed)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(RotationalSpeedUnit unit, [NotNullWhen(true)] out RotationalSpeed? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - RotationalSpeed? convertedOrNull = (Unit, unit) switch - { - // RotationalSpeedUnit -> BaseUnit - (RotationalSpeedUnit.CentiradianPerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed((_value) * 1e-2d, RotationalSpeedUnit.RadianPerSecond), - (RotationalSpeedUnit.DeciradianPerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed((_value) * 1e-1d, RotationalSpeedUnit.RadianPerSecond), - (RotationalSpeedUnit.DegreePerMinute, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed((Math.PI / (180 * 60)) * _value, RotationalSpeedUnit.RadianPerSecond), - (RotationalSpeedUnit.DegreePerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed((Math.PI / 180) * _value, RotationalSpeedUnit.RadianPerSecond), - (RotationalSpeedUnit.MicrodegreePerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed(((Math.PI / 180) * _value) * 1e-6d, RotationalSpeedUnit.RadianPerSecond), - (RotationalSpeedUnit.MicroradianPerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed((_value) * 1e-6d, RotationalSpeedUnit.RadianPerSecond), - (RotationalSpeedUnit.MillidegreePerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed(((Math.PI / 180) * _value) * 1e-3d, RotationalSpeedUnit.RadianPerSecond), - (RotationalSpeedUnit.MilliradianPerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed((_value) * 1e-3d, RotationalSpeedUnit.RadianPerSecond), - (RotationalSpeedUnit.NanodegreePerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed(((Math.PI / 180) * _value) * 1e-9d, RotationalSpeedUnit.RadianPerSecond), - (RotationalSpeedUnit.NanoradianPerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed((_value) * 1e-9d, RotationalSpeedUnit.RadianPerSecond), - (RotationalSpeedUnit.RevolutionPerMinute, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed((_value * 2 * Math.PI) / 60, RotationalSpeedUnit.RadianPerSecond), - (RotationalSpeedUnit.RevolutionPerSecond, RotationalSpeedUnit.RadianPerSecond) => new RotationalSpeed(_value * 2 * Math.PI, RotationalSpeedUnit.RadianPerSecond), - - // BaseUnit -> RotationalSpeedUnit - (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.CentiradianPerSecond) => new RotationalSpeed((_value) / 1e-2d, RotationalSpeedUnit.CentiradianPerSecond), - (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DeciradianPerSecond) => new RotationalSpeed((_value) / 1e-1d, RotationalSpeedUnit.DeciradianPerSecond), - (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DegreePerMinute) => new RotationalSpeed((180 * 60 / Math.PI) * _value, RotationalSpeedUnit.DegreePerMinute), - (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.DegreePerSecond) => new RotationalSpeed((180 / Math.PI) * _value, RotationalSpeedUnit.DegreePerSecond), - (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MicrodegreePerSecond) => new RotationalSpeed(((180 / Math.PI) * _value) / 1e-6d, RotationalSpeedUnit.MicrodegreePerSecond), - (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MicroradianPerSecond) => new RotationalSpeed((_value) / 1e-6d, RotationalSpeedUnit.MicroradianPerSecond), - (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MillidegreePerSecond) => new RotationalSpeed(((180 / Math.PI) * _value) / 1e-3d, RotationalSpeedUnit.MillidegreePerSecond), - (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.MilliradianPerSecond) => new RotationalSpeed((_value) / 1e-3d, RotationalSpeedUnit.MilliradianPerSecond), - (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.NanodegreePerSecond) => new RotationalSpeed(((180 / Math.PI) * _value) / 1e-9d, RotationalSpeedUnit.NanodegreePerSecond), - (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.NanoradianPerSecond) => new RotationalSpeed((_value) / 1e-9d, RotationalSpeedUnit.NanoradianPerSecond), - (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.RevolutionPerMinute) => new RotationalSpeed((_value / (2 * Math.PI)) * 60, RotationalSpeedUnit.RevolutionPerMinute), - (RotationalSpeedUnit.RadianPerSecond, RotationalSpeedUnit.RevolutionPerSecond) => new RotationalSpeed(_value / (2 * Math.PI), RotationalSpeedUnit.RevolutionPerSecond), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public RotationalSpeed ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not RotationalSpeedUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalSpeedUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(RotationalSpeedUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(RotationalSpeedUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -983,7 +797,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs index c6d1e7d459..66c5046a07 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalStiffness.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct RotationalStiffness : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -55,13 +54,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly RotationalStiffnessUnit? _unit; /// @@ -106,7 +105,7 @@ public static RotationalStiffnessInfo CreateDefault(Func - /// The for is [T^-2][L^2][M]. + /// The for is T^-2L^2M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); @@ -121,47 +120,109 @@ public static RotationalStiffnessInfo CreateDefault(FuncAn of representing the default unit mappings for RotationalStiffness. public static IEnumerable> GetDefaultMappings() { - yield return new (RotationalStiffnessUnit.CentinewtonMeterPerDegree, "CentinewtonMeterPerDegree", "CentinewtonMetersPerDegree", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, "CentinewtonMillimeterPerDegree", "CentinewtonMillimetersPerDegree", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, "CentinewtonMillimeterPerRadian", "CentinewtonMillimetersPerRadian", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.DecanewtonMeterPerDegree, "DecanewtonMeterPerDegree", "DecanewtonMetersPerDegree", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, "DecanewtonMillimeterPerDegree", "DecanewtonMillimetersPerDegree", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, "DecanewtonMillimeterPerRadian", "DecanewtonMillimetersPerRadian", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.DecinewtonMeterPerDegree, "DecinewtonMeterPerDegree", "DecinewtonMetersPerDegree", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, "DecinewtonMillimeterPerDegree", "DecinewtonMillimetersPerDegree", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, "DecinewtonMillimeterPerRadian", "DecinewtonMillimetersPerRadian", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.KilonewtonMeterPerDegree, "KilonewtonMeterPerDegree", "KilonewtonMetersPerDegree", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.KilonewtonMeterPerRadian, "KilonewtonMeterPerRadian", "KilonewtonMetersPerRadian", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, "KilonewtonMillimeterPerDegree", "KilonewtonMillimetersPerDegree", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, "KilonewtonMillimeterPerRadian", "KilonewtonMillimetersPerRadian", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.KilopoundForceFootPerDegrees, "KilopoundForceFootPerDegrees", "KilopoundForceFeetPerDegrees", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.MeganewtonMeterPerDegree, "MeganewtonMeterPerDegree", "MeganewtonMetersPerDegree", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.MeganewtonMeterPerRadian, "MeganewtonMeterPerRadian", "MeganewtonMetersPerRadian", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, "MeganewtonMillimeterPerDegree", "MeganewtonMillimetersPerDegree", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, "MeganewtonMillimeterPerRadian", "MeganewtonMillimetersPerRadian", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.MicronewtonMeterPerDegree, "MicronewtonMeterPerDegree", "MicronewtonMetersPerDegree", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, "MicronewtonMillimeterPerDegree", "MicronewtonMillimetersPerDegree", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, "MicronewtonMillimeterPerRadian", "MicronewtonMillimetersPerRadian", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.MillinewtonMeterPerDegree, "MillinewtonMeterPerDegree", "MillinewtonMetersPerDegree", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, "MillinewtonMillimeterPerDegree", "MillinewtonMillimetersPerDegree", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, "MillinewtonMillimeterPerRadian", "MillinewtonMillimetersPerRadian", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.NanonewtonMeterPerDegree, "NanonewtonMeterPerDegree", "NanonewtonMetersPerDegree", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, "NanonewtonMillimeterPerDegree", "NanonewtonMillimetersPerDegree", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, "NanonewtonMillimeterPerRadian", "NanonewtonMillimetersPerRadian", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.NewtonMeterPerDegree, "NewtonMeterPerDegree", "NewtonMetersPerDegree", BaseUnits.Undefined); + yield return new (RotationalStiffnessUnit.CentinewtonMeterPerDegree, "CentinewtonMeterPerDegree", "CentinewtonMetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 1800000000000000) + ); + yield return new (RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, "CentinewtonMillimeterPerDegree", "CentinewtonMillimetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 1800000000000) + ); + yield return new (RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, "CentinewtonMillimeterPerRadian", "CentinewtonMillimetersPerRadian", BaseUnits.Undefined, + 100000 + ); + yield return new (RotationalStiffnessUnit.DecanewtonMeterPerDegree, "DecanewtonMeterPerDegree", "DecanewtonMetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 1800000000000000000) + ); + yield return new (RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, "DecanewtonMillimeterPerDegree", "DecanewtonMillimetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 1800000000000000) + ); + yield return new (RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, "DecanewtonMillimeterPerRadian", "DecanewtonMillimetersPerRadian", BaseUnits.Undefined, + 100 + ); + yield return new (RotationalStiffnessUnit.DecinewtonMeterPerDegree, "DecinewtonMeterPerDegree", "DecinewtonMetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 18000000000000000) + ); + yield return new (RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, "DecinewtonMillimeterPerDegree", "DecinewtonMillimetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 18000000000000) + ); + yield return new (RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, "DecinewtonMillimeterPerRadian", "DecinewtonMillimetersPerRadian", BaseUnits.Undefined, + 10000 + ); + yield return new (RotationalStiffnessUnit.KilonewtonMeterPerDegree, "KilonewtonMeterPerDegree", "KilonewtonMetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, new BigInteger(18) * QuantityValue.PowerOfTen(19)) + ); + yield return new (RotationalStiffnessUnit.KilonewtonMeterPerRadian, "KilonewtonMeterPerRadian", "KilonewtonMetersPerRadian", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, "KilonewtonMillimeterPerDegree", "KilonewtonMillimetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 180000000000000000) + ); + yield return new (RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, "KilonewtonMillimeterPerRadian", "KilonewtonMillimetersPerRadian", BaseUnits.Undefined, + 1 + ); + yield return new (RotationalStiffnessUnit.KilopoundForceFootPerDegrees, "KilopoundForceFootPerDegrees", "KilopoundForceFeetPerDegrees", BaseUnits.Undefined, + new QuantityValue(3141592653589793, QuantityValue.PowerOfTen(3) * new BigInteger(244047230699652072)) + ); + yield return new (RotationalStiffnessUnit.MeganewtonMeterPerDegree, "MeganewtonMeterPerDegree", "MeganewtonMetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, new BigInteger(18) * QuantityValue.PowerOfTen(22)) + ); + yield return new (RotationalStiffnessUnit.MeganewtonMeterPerRadian, "MeganewtonMeterPerRadian", "MeganewtonMetersPerRadian", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, "MeganewtonMillimeterPerDegree", "MeganewtonMillimetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, new BigInteger(18) * QuantityValue.PowerOfTen(19)) + ); + yield return new (RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, "MeganewtonMillimeterPerRadian", "MeganewtonMillimetersPerRadian", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (RotationalStiffnessUnit.MicronewtonMeterPerDegree, "MicronewtonMeterPerDegree", "MicronewtonMetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 180000000000) + ); + yield return new (RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, "MicronewtonMillimeterPerDegree", "MicronewtonMillimetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 180000000) + ); + yield return new (RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, "MicronewtonMillimeterPerRadian", "MicronewtonMillimetersPerRadian", BaseUnits.Undefined, + 1000000000 + ); + yield return new (RotationalStiffnessUnit.MillinewtonMeterPerDegree, "MillinewtonMeterPerDegree", "MillinewtonMetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 180000000000000) + ); + yield return new (RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, "MillinewtonMillimeterPerDegree", "MillinewtonMillimetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 180000000000) + ); + yield return new (RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, "MillinewtonMillimeterPerRadian", "MillinewtonMillimetersPerRadian", BaseUnits.Undefined, + 1000000 + ); + yield return new (RotationalStiffnessUnit.NanonewtonMeterPerDegree, "NanonewtonMeterPerDegree", "NanonewtonMetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 180000000) + ); + yield return new (RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, "NanonewtonMillimeterPerDegree", "NanonewtonMillimetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 180000) + ); + yield return new (RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, "NanonewtonMillimeterPerRadian", "NanonewtonMillimetersPerRadian", BaseUnits.Undefined, + 1000000000000 + ); + yield return new (RotationalStiffnessUnit.NewtonMeterPerDegree, "NewtonMeterPerDegree", "NewtonMetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 180000000000000000) + ); yield return new (RotationalStiffnessUnit.NewtonMeterPerRadian, "NewtonMeterPerRadian", "NewtonMetersPerRadian", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (RotationalStiffnessUnit.NewtonMillimeterPerDegree, "NewtonMillimeterPerDegree", "NewtonMillimetersPerDegree", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.NewtonMillimeterPerRadian, "NewtonMillimeterPerRadian", "NewtonMillimetersPerRadian", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.PoundForceFeetPerRadian, "PoundForceFeetPerRadian", "PoundForceFeetPerRadian", BaseUnits.Undefined); - yield return new (RotationalStiffnessUnit.PoundForceFootPerDegrees, "PoundForceFootPerDegrees", "PoundForceFeetPerDegrees", BaseUnits.Undefined); + yield return new (RotationalStiffnessUnit.NewtonMillimeterPerDegree, "NewtonMillimeterPerDegree", "NewtonMillimetersPerDegree", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 180000000000000) + ); + yield return new (RotationalStiffnessUnit.NewtonMillimeterPerRadian, "NewtonMillimeterPerRadian", "NewtonMillimetersPerRadian", BaseUnits.Undefined, + 1000 + ); + yield return new (RotationalStiffnessUnit.PoundForceFeetPerRadian, "PoundForceFeetPerRadian", "PoundForceFeetPerRadian", BaseUnits.Undefined, + new QuantityValue(2500000000000000, 3389544870828501) + ); + yield return new (RotationalStiffnessUnit.PoundForceFootPerDegrees, "PoundForceFootPerDegrees", "PoundForceFeetPerDegrees", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 244047230699652072) + ); } } static RotationalStiffness() { - Info = RotationalStiffnessInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(RotationalStiffnessInfo.CreateDefault); } /// @@ -169,7 +230,7 @@ static RotationalStiffness() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public RotationalStiffness(double value, RotationalStiffnessUnit unit) + public RotationalStiffness(QuantityValue value, RotationalStiffnessUnit unit) { _value = value; _unit = unit; @@ -183,7 +244,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -194,7 +255,8 @@ public RotationalStiffness(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -223,10 +285,8 @@ public RotationalStiffness(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public RotationalStiffnessUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -265,252 +325,174 @@ public RotationalStiffness(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentinewtonMetersPerDegree => As(RotationalStiffnessUnit.CentinewtonMeterPerDegree); + public QuantityValue CentinewtonMetersPerDegree => this.As(RotationalStiffnessUnit.CentinewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentinewtonMillimetersPerDegree => As(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree); + public QuantityValue CentinewtonMillimetersPerDegree => this.As(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentinewtonMillimetersPerRadian => As(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian); + public QuantityValue CentinewtonMillimetersPerRadian => this.As(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecanewtonMetersPerDegree => As(RotationalStiffnessUnit.DecanewtonMeterPerDegree); + public QuantityValue DecanewtonMetersPerDegree => this.As(RotationalStiffnessUnit.DecanewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecanewtonMillimetersPerDegree => As(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree); + public QuantityValue DecanewtonMillimetersPerDegree => this.As(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecanewtonMillimetersPerRadian => As(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian); + public QuantityValue DecanewtonMillimetersPerRadian => this.As(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecinewtonMetersPerDegree => As(RotationalStiffnessUnit.DecinewtonMeterPerDegree); + public QuantityValue DecinewtonMetersPerDegree => this.As(RotationalStiffnessUnit.DecinewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecinewtonMillimetersPerDegree => As(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree); + public QuantityValue DecinewtonMillimetersPerDegree => this.As(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecinewtonMillimetersPerRadian => As(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian); + public QuantityValue DecinewtonMillimetersPerRadian => this.As(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonMetersPerDegree => As(RotationalStiffnessUnit.KilonewtonMeterPerDegree); + public QuantityValue KilonewtonMetersPerDegree => this.As(RotationalStiffnessUnit.KilonewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonMetersPerRadian => As(RotationalStiffnessUnit.KilonewtonMeterPerRadian); + public QuantityValue KilonewtonMetersPerRadian => this.As(RotationalStiffnessUnit.KilonewtonMeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonMillimetersPerDegree => As(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree); + public QuantityValue KilonewtonMillimetersPerDegree => this.As(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonMillimetersPerRadian => As(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian); + public QuantityValue KilonewtonMillimetersPerRadian => this.As(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundForceFeetPerDegrees => As(RotationalStiffnessUnit.KilopoundForceFootPerDegrees); + public QuantityValue KilopoundForceFeetPerDegrees => this.As(RotationalStiffnessUnit.KilopoundForceFootPerDegrees); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MeganewtonMetersPerDegree => As(RotationalStiffnessUnit.MeganewtonMeterPerDegree); + public QuantityValue MeganewtonMetersPerDegree => this.As(RotationalStiffnessUnit.MeganewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MeganewtonMetersPerRadian => As(RotationalStiffnessUnit.MeganewtonMeterPerRadian); + public QuantityValue MeganewtonMetersPerRadian => this.As(RotationalStiffnessUnit.MeganewtonMeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MeganewtonMillimetersPerDegree => As(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree); + public QuantityValue MeganewtonMillimetersPerDegree => this.As(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MeganewtonMillimetersPerRadian => As(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian); + public QuantityValue MeganewtonMillimetersPerRadian => this.As(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicronewtonMetersPerDegree => As(RotationalStiffnessUnit.MicronewtonMeterPerDegree); + public QuantityValue MicronewtonMetersPerDegree => this.As(RotationalStiffnessUnit.MicronewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicronewtonMillimetersPerDegree => As(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree); + public QuantityValue MicronewtonMillimetersPerDegree => this.As(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicronewtonMillimetersPerRadian => As(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian); + public QuantityValue MicronewtonMillimetersPerRadian => this.As(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillinewtonMetersPerDegree => As(RotationalStiffnessUnit.MillinewtonMeterPerDegree); + public QuantityValue MillinewtonMetersPerDegree => this.As(RotationalStiffnessUnit.MillinewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillinewtonMillimetersPerDegree => As(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree); + public QuantityValue MillinewtonMillimetersPerDegree => this.As(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillinewtonMillimetersPerRadian => As(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian); + public QuantityValue MillinewtonMillimetersPerRadian => this.As(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanonewtonMetersPerDegree => As(RotationalStiffnessUnit.NanonewtonMeterPerDegree); + public QuantityValue NanonewtonMetersPerDegree => this.As(RotationalStiffnessUnit.NanonewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanonewtonMillimetersPerDegree => As(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree); + public QuantityValue NanonewtonMillimetersPerDegree => this.As(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanonewtonMillimetersPerRadian => As(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian); + public QuantityValue NanonewtonMillimetersPerRadian => this.As(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonMetersPerDegree => As(RotationalStiffnessUnit.NewtonMeterPerDegree); + public QuantityValue NewtonMetersPerDegree => this.As(RotationalStiffnessUnit.NewtonMeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonMetersPerRadian => As(RotationalStiffnessUnit.NewtonMeterPerRadian); + public QuantityValue NewtonMetersPerRadian => this.As(RotationalStiffnessUnit.NewtonMeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonMillimetersPerDegree => As(RotationalStiffnessUnit.NewtonMillimeterPerDegree); + public QuantityValue NewtonMillimetersPerDegree => this.As(RotationalStiffnessUnit.NewtonMillimeterPerDegree); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonMillimetersPerRadian => As(RotationalStiffnessUnit.NewtonMillimeterPerRadian); + public QuantityValue NewtonMillimetersPerRadian => this.As(RotationalStiffnessUnit.NewtonMillimeterPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundForceFeetPerRadian => As(RotationalStiffnessUnit.PoundForceFeetPerRadian); + public QuantityValue PoundForceFeetPerRadian => this.As(RotationalStiffnessUnit.PoundForceFeetPerRadian); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundForceFeetPerDegrees => As(RotationalStiffnessUnit.PoundForceFootPerDegrees); + public QuantityValue PoundForceFeetPerDegrees => this.As(RotationalStiffnessUnit.PoundForceFootPerDegrees); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: RotationalStiffnessUnit -> BaseUnit - unitConverter.SetConversionFunction(RotationalStiffnessUnit.CentinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecanewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.KilonewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.KilonewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.KilopoundForceFootPerDegrees, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MeganewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MeganewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MicronewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MillinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NanonewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.PoundForceFeetPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.PoundForceFootPerDegrees, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerRadian)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian, quantity => quantity); - - // Register in unit converter: BaseUnit -> RotationalStiffnessUnit - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.CentinewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.CentinewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.CentinewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecanewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecanewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecanewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecinewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecinewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.DecinewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.KilonewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.KilonewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.KilonewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.KilonewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilopoundForceFootPerDegrees, quantity => quantity.ToUnit(RotationalStiffnessUnit.KilopoundForceFootPerDegrees)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MeganewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.MeganewtonMeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MeganewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.MeganewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MicronewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MicronewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.MicronewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MillinewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.MillinewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.MillinewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.NanonewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.NanonewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NanonewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMillimeterPerDegree, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMillimeterPerDegree)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMillimeterPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.NewtonMillimeterPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.PoundForceFeetPerRadian, quantity => quantity.ToUnit(RotationalStiffnessUnit.PoundForceFeetPerRadian)); - unitConverter.SetConversionFunction(RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.PoundForceFootPerDegrees, quantity => quantity.ToUnit(RotationalStiffnessUnit.PoundForceFootPerDegrees)); - } - /// /// Get unit abbreviation string. /// @@ -539,7 +521,7 @@ public static string GetAbbreviation(RotationalStiffnessUnit unit, IFormatProvid /// /// Creates a from . /// - public static RotationalStiffness FromCentinewtonMetersPerDegree(double value) + public static RotationalStiffness FromCentinewtonMetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.CentinewtonMeterPerDegree); } @@ -547,7 +529,7 @@ public static RotationalStiffness FromCentinewtonMetersPerDegree(double value) /// /// Creates a from . /// - public static RotationalStiffness FromCentinewtonMillimetersPerDegree(double value) + public static RotationalStiffness FromCentinewtonMillimetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.CentinewtonMillimeterPerDegree); } @@ -555,7 +537,7 @@ public static RotationalStiffness FromCentinewtonMillimetersPerDegree(double val /// /// Creates a from . /// - public static RotationalStiffness FromCentinewtonMillimetersPerRadian(double value) + public static RotationalStiffness FromCentinewtonMillimetersPerRadian(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.CentinewtonMillimeterPerRadian); } @@ -563,7 +545,7 @@ public static RotationalStiffness FromCentinewtonMillimetersPerRadian(double val /// /// Creates a from . /// - public static RotationalStiffness FromDecanewtonMetersPerDegree(double value) + public static RotationalStiffness FromDecanewtonMetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.DecanewtonMeterPerDegree); } @@ -571,7 +553,7 @@ public static RotationalStiffness FromDecanewtonMetersPerDegree(double value) /// /// Creates a from . /// - public static RotationalStiffness FromDecanewtonMillimetersPerDegree(double value) + public static RotationalStiffness FromDecanewtonMillimetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.DecanewtonMillimeterPerDegree); } @@ -579,7 +561,7 @@ public static RotationalStiffness FromDecanewtonMillimetersPerDegree(double valu /// /// Creates a from . /// - public static RotationalStiffness FromDecanewtonMillimetersPerRadian(double value) + public static RotationalStiffness FromDecanewtonMillimetersPerRadian(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.DecanewtonMillimeterPerRadian); } @@ -587,7 +569,7 @@ public static RotationalStiffness FromDecanewtonMillimetersPerRadian(double valu /// /// Creates a from . /// - public static RotationalStiffness FromDecinewtonMetersPerDegree(double value) + public static RotationalStiffness FromDecinewtonMetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.DecinewtonMeterPerDegree); } @@ -595,7 +577,7 @@ public static RotationalStiffness FromDecinewtonMetersPerDegree(double value) /// /// Creates a from . /// - public static RotationalStiffness FromDecinewtonMillimetersPerDegree(double value) + public static RotationalStiffness FromDecinewtonMillimetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.DecinewtonMillimeterPerDegree); } @@ -603,7 +585,7 @@ public static RotationalStiffness FromDecinewtonMillimetersPerDegree(double valu /// /// Creates a from . /// - public static RotationalStiffness FromDecinewtonMillimetersPerRadian(double value) + public static RotationalStiffness FromDecinewtonMillimetersPerRadian(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.DecinewtonMillimeterPerRadian); } @@ -611,7 +593,7 @@ public static RotationalStiffness FromDecinewtonMillimetersPerRadian(double valu /// /// Creates a from . /// - public static RotationalStiffness FromKilonewtonMetersPerDegree(double value) + public static RotationalStiffness FromKilonewtonMetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMeterPerDegree); } @@ -619,7 +601,7 @@ public static RotationalStiffness FromKilonewtonMetersPerDegree(double value) /// /// Creates a from . /// - public static RotationalStiffness FromKilonewtonMetersPerRadian(double value) + public static RotationalStiffness FromKilonewtonMetersPerRadian(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMeterPerRadian); } @@ -627,7 +609,7 @@ public static RotationalStiffness FromKilonewtonMetersPerRadian(double value) /// /// Creates a from . /// - public static RotationalStiffness FromKilonewtonMillimetersPerDegree(double value) + public static RotationalStiffness FromKilonewtonMillimetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMillimeterPerDegree); } @@ -635,7 +617,7 @@ public static RotationalStiffness FromKilonewtonMillimetersPerDegree(double valu /// /// Creates a from . /// - public static RotationalStiffness FromKilonewtonMillimetersPerRadian(double value) + public static RotationalStiffness FromKilonewtonMillimetersPerRadian(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.KilonewtonMillimeterPerRadian); } @@ -643,7 +625,7 @@ public static RotationalStiffness FromKilonewtonMillimetersPerRadian(double valu /// /// Creates a from . /// - public static RotationalStiffness FromKilopoundForceFeetPerDegrees(double value) + public static RotationalStiffness FromKilopoundForceFeetPerDegrees(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.KilopoundForceFootPerDegrees); } @@ -651,7 +633,7 @@ public static RotationalStiffness FromKilopoundForceFeetPerDegrees(double value) /// /// Creates a from . /// - public static RotationalStiffness FromMeganewtonMetersPerDegree(double value) + public static RotationalStiffness FromMeganewtonMetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMeterPerDegree); } @@ -659,7 +641,7 @@ public static RotationalStiffness FromMeganewtonMetersPerDegree(double value) /// /// Creates a from . /// - public static RotationalStiffness FromMeganewtonMetersPerRadian(double value) + public static RotationalStiffness FromMeganewtonMetersPerRadian(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMeterPerRadian); } @@ -667,7 +649,7 @@ public static RotationalStiffness FromMeganewtonMetersPerRadian(double value) /// /// Creates a from . /// - public static RotationalStiffness FromMeganewtonMillimetersPerDegree(double value) + public static RotationalStiffness FromMeganewtonMillimetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMillimeterPerDegree); } @@ -675,7 +657,7 @@ public static RotationalStiffness FromMeganewtonMillimetersPerDegree(double valu /// /// Creates a from . /// - public static RotationalStiffness FromMeganewtonMillimetersPerRadian(double value) + public static RotationalStiffness FromMeganewtonMillimetersPerRadian(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.MeganewtonMillimeterPerRadian); } @@ -683,7 +665,7 @@ public static RotationalStiffness FromMeganewtonMillimetersPerRadian(double valu /// /// Creates a from . /// - public static RotationalStiffness FromMicronewtonMetersPerDegree(double value) + public static RotationalStiffness FromMicronewtonMetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.MicronewtonMeterPerDegree); } @@ -691,7 +673,7 @@ public static RotationalStiffness FromMicronewtonMetersPerDegree(double value) /// /// Creates a from . /// - public static RotationalStiffness FromMicronewtonMillimetersPerDegree(double value) + public static RotationalStiffness FromMicronewtonMillimetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.MicronewtonMillimeterPerDegree); } @@ -699,7 +681,7 @@ public static RotationalStiffness FromMicronewtonMillimetersPerDegree(double val /// /// Creates a from . /// - public static RotationalStiffness FromMicronewtonMillimetersPerRadian(double value) + public static RotationalStiffness FromMicronewtonMillimetersPerRadian(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.MicronewtonMillimeterPerRadian); } @@ -707,7 +689,7 @@ public static RotationalStiffness FromMicronewtonMillimetersPerRadian(double val /// /// Creates a from . /// - public static RotationalStiffness FromMillinewtonMetersPerDegree(double value) + public static RotationalStiffness FromMillinewtonMetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.MillinewtonMeterPerDegree); } @@ -715,7 +697,7 @@ public static RotationalStiffness FromMillinewtonMetersPerDegree(double value) /// /// Creates a from . /// - public static RotationalStiffness FromMillinewtonMillimetersPerDegree(double value) + public static RotationalStiffness FromMillinewtonMillimetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.MillinewtonMillimeterPerDegree); } @@ -723,7 +705,7 @@ public static RotationalStiffness FromMillinewtonMillimetersPerDegree(double val /// /// Creates a from . /// - public static RotationalStiffness FromMillinewtonMillimetersPerRadian(double value) + public static RotationalStiffness FromMillinewtonMillimetersPerRadian(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.MillinewtonMillimeterPerRadian); } @@ -731,7 +713,7 @@ public static RotationalStiffness FromMillinewtonMillimetersPerRadian(double val /// /// Creates a from . /// - public static RotationalStiffness FromNanonewtonMetersPerDegree(double value) + public static RotationalStiffness FromNanonewtonMetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.NanonewtonMeterPerDegree); } @@ -739,7 +721,7 @@ public static RotationalStiffness FromNanonewtonMetersPerDegree(double value) /// /// Creates a from . /// - public static RotationalStiffness FromNanonewtonMillimetersPerDegree(double value) + public static RotationalStiffness FromNanonewtonMillimetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.NanonewtonMillimeterPerDegree); } @@ -747,7 +729,7 @@ public static RotationalStiffness FromNanonewtonMillimetersPerDegree(double valu /// /// Creates a from . /// - public static RotationalStiffness FromNanonewtonMillimetersPerRadian(double value) + public static RotationalStiffness FromNanonewtonMillimetersPerRadian(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.NanonewtonMillimeterPerRadian); } @@ -755,7 +737,7 @@ public static RotationalStiffness FromNanonewtonMillimetersPerRadian(double valu /// /// Creates a from . /// - public static RotationalStiffness FromNewtonMetersPerDegree(double value) + public static RotationalStiffness FromNewtonMetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMeterPerDegree); } @@ -763,7 +745,7 @@ public static RotationalStiffness FromNewtonMetersPerDegree(double value) /// /// Creates a from . /// - public static RotationalStiffness FromNewtonMetersPerRadian(double value) + public static RotationalStiffness FromNewtonMetersPerRadian(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMeterPerRadian); } @@ -771,7 +753,7 @@ public static RotationalStiffness FromNewtonMetersPerRadian(double value) /// /// Creates a from . /// - public static RotationalStiffness FromNewtonMillimetersPerDegree(double value) + public static RotationalStiffness FromNewtonMillimetersPerDegree(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMillimeterPerDegree); } @@ -779,7 +761,7 @@ public static RotationalStiffness FromNewtonMillimetersPerDegree(double value) /// /// Creates a from . /// - public static RotationalStiffness FromNewtonMillimetersPerRadian(double value) + public static RotationalStiffness FromNewtonMillimetersPerRadian(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.NewtonMillimeterPerRadian); } @@ -787,7 +769,7 @@ public static RotationalStiffness FromNewtonMillimetersPerRadian(double value) /// /// Creates a from . /// - public static RotationalStiffness FromPoundForceFeetPerRadian(double value) + public static RotationalStiffness FromPoundForceFeetPerRadian(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.PoundForceFeetPerRadian); } @@ -795,7 +777,7 @@ public static RotationalStiffness FromPoundForceFeetPerRadian(double value) /// /// Creates a from . /// - public static RotationalStiffness FromPoundForceFeetPerDegrees(double value) + public static RotationalStiffness FromPoundForceFeetPerDegrees(QuantityValue value) { return new RotationalStiffness(value, RotationalStiffnessUnit.PoundForceFootPerDegrees); } @@ -806,7 +788,7 @@ public static RotationalStiffness FromPoundForceFeetPerDegrees(double value) /// Value to convert from. /// Unit to convert from. /// RotationalStiffness unit value. - public static RotationalStiffness From(double value, RotationalStiffnessUnit fromUnit) + public static RotationalStiffness From(QuantityValue value, RotationalStiffnessUnit fromUnit) { return new RotationalStiffness(value, fromUnit); } @@ -867,10 +849,7 @@ public static RotationalStiffness Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static RotationalStiffness Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -898,11 +877,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out RotationalStiffn /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out RotationalStiffness result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -923,7 +898,7 @@ public static RotationalStiffnessUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -934,7 +909,7 @@ public static RotationalStiffnessUnit ParseUnit(string str, IFormatProvider? pro return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out RotationalStiffnessUnit unit) { return TryParseUnit(str, null, out unit); @@ -949,7 +924,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out RotationalSt /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out RotationalStiffnessUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -968,35 +943,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static RotationalStiffness operator +(RotationalStiffness left, RotationalStiffness right) { - return new RotationalStiffness(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new RotationalStiffness(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static RotationalStiffness operator -(RotationalStiffness left, RotationalStiffness right) { - return new RotationalStiffness(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new RotationalStiffness(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -1030,97 +1005,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(RotationalStiffness left, RotationalStiffness right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(RotationalStiffness left, RotationalStiffness right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(RotationalStiffness left, RotationalStiffness right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(RotationalStiffness left, RotationalStiffness right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RotationalStiffness other, RotationalStiffness tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(RotationalStiffness left, RotationalStiffness right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RotationalStiffness other, RotationalStiffness tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(RotationalStiffness left, RotationalStiffness right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RotationalStiffness other, RotationalStiffness tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is RotationalStiffness otherQuantity)) + if (obj is not RotationalStiffness otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RotationalStiffness other, RotationalStiffness tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(RotationalStiffness other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current RotationalStiffness. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(RotationalStiffness), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is RotationalStiffness otherQuantity)) throw new ArgumentException("Expected type RotationalStiffness.", nameof(obj)); + if (obj is not RotationalStiffness otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1132,210 +1092,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RotationalStiffness other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalStiffnessUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this RotationalStiffness to another RotationalStiffness with the unit representation . - /// - /// The unit to convert to. - /// A RotationalStiffness with the specified unit. - public RotationalStiffness ToUnit(RotationalStiffnessUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A RotationalStiffness with the specified unit. - public RotationalStiffness ToUnit(RotationalStiffnessUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(RotationalStiffness), Unit, typeof(RotationalStiffness), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (RotationalStiffness)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(RotationalStiffnessUnit unit, [NotNullWhen(true)] out RotationalStiffness? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - RotationalStiffness? convertedOrNull = (Unit, unit) switch - { - // RotationalStiffnessUnit -> BaseUnit - (RotationalStiffnessUnit.CentinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * (180 / Math.PI)) * 1e-2d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.CentinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 180 / Math.PI * 0.001) * 1e-2d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.CentinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 0.001) * 1e-2d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.DecanewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * (180 / Math.PI)) * 1e1d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.DecanewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 180 / Math.PI * 0.001) * 1e1d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.DecanewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 0.001) * 1e1d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.DecinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * (180 / Math.PI)) * 1e-1d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.DecinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 180 / Math.PI * 0.001) * 1e-1d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.DecinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 0.001) * 1e-1d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.KilonewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * (180 / Math.PI)) * 1e3d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.KilonewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value) * 1e3d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.KilonewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 180 / Math.PI * 0.001) * 1e3d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.KilonewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 0.001) * 1e3d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.KilopoundForceFootPerDegrees, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness(_value * (4.4482216152605e3 * 0.3048 * 180 / Math.PI), RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.MeganewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * (180 / Math.PI)) * 1e6d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.MeganewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value) * 1e6d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.MeganewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 180 / Math.PI * 0.001) * 1e6d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.MeganewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 0.001) * 1e6d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.MicronewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * (180 / Math.PI)) * 1e-6d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.MicronewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 180 / Math.PI * 0.001) * 1e-6d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.MicronewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 0.001) * 1e-6d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.MillinewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * (180 / Math.PI)) * 1e-3d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.MillinewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 180 / Math.PI * 0.001) * 1e-3d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.MillinewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 0.001) * 1e-3d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.NanonewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * (180 / Math.PI)) * 1e-9d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.NanonewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 180 / Math.PI * 0.001) * 1e-9d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.NanonewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness((_value * 0.001) * 1e-9d, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.NewtonMeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness(_value * (180 / Math.PI), RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.NewtonMillimeterPerDegree, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness(_value * 180 / Math.PI * 0.001, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.NewtonMillimeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness(_value * 0.001, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.PoundForceFeetPerRadian, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness(_value * 4.4482216152605 * 0.3048, RotationalStiffnessUnit.NewtonMeterPerRadian), - (RotationalStiffnessUnit.PoundForceFootPerDegrees, RotationalStiffnessUnit.NewtonMeterPerRadian) => new RotationalStiffness(_value * (4.4482216152605 * 0.3048 * 180 / Math.PI), RotationalStiffnessUnit.NewtonMeterPerRadian), - - // BaseUnit -> RotationalStiffnessUnit - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMeterPerDegree) => new RotationalStiffness((_value / (180 / Math.PI)) / 1e-2d, RotationalStiffnessUnit.CentinewtonMeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMillimeterPerDegree) => new RotationalStiffness((_value / 180 * Math.PI * 1000) / 1e-2d, RotationalStiffnessUnit.CentinewtonMillimeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.CentinewtonMillimeterPerRadian) => new RotationalStiffness((_value * 1000) / 1e-2d, RotationalStiffnessUnit.CentinewtonMillimeterPerRadian), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMeterPerDegree) => new RotationalStiffness((_value / (180 / Math.PI)) / 1e1d, RotationalStiffnessUnit.DecanewtonMeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMillimeterPerDegree) => new RotationalStiffness((_value / 180 * Math.PI * 1000) / 1e1d, RotationalStiffnessUnit.DecanewtonMillimeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecanewtonMillimeterPerRadian) => new RotationalStiffness((_value * 1000) / 1e1d, RotationalStiffnessUnit.DecanewtonMillimeterPerRadian), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMeterPerDegree) => new RotationalStiffness((_value / (180 / Math.PI)) / 1e-1d, RotationalStiffnessUnit.DecinewtonMeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMillimeterPerDegree) => new RotationalStiffness((_value / 180 * Math.PI * 1000) / 1e-1d, RotationalStiffnessUnit.DecinewtonMillimeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.DecinewtonMillimeterPerRadian) => new RotationalStiffness((_value * 1000) / 1e-1d, RotationalStiffnessUnit.DecinewtonMillimeterPerRadian), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMeterPerDegree) => new RotationalStiffness((_value / (180 / Math.PI)) / 1e3d, RotationalStiffnessUnit.KilonewtonMeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMeterPerRadian) => new RotationalStiffness((_value) / 1e3d, RotationalStiffnessUnit.KilonewtonMeterPerRadian), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMillimeterPerDegree) => new RotationalStiffness((_value / 180 * Math.PI * 1000) / 1e3d, RotationalStiffnessUnit.KilonewtonMillimeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilonewtonMillimeterPerRadian) => new RotationalStiffness((_value * 1000) / 1e3d, RotationalStiffnessUnit.KilonewtonMillimeterPerRadian), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.KilopoundForceFootPerDegrees) => new RotationalStiffness(_value / (4.4482216152605e3 * 0.3048 * 180 / Math.PI), RotationalStiffnessUnit.KilopoundForceFootPerDegrees), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMeterPerDegree) => new RotationalStiffness((_value / (180 / Math.PI)) / 1e6d, RotationalStiffnessUnit.MeganewtonMeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMeterPerRadian) => new RotationalStiffness((_value) / 1e6d, RotationalStiffnessUnit.MeganewtonMeterPerRadian), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMillimeterPerDegree) => new RotationalStiffness((_value / 180 * Math.PI * 1000) / 1e6d, RotationalStiffnessUnit.MeganewtonMillimeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MeganewtonMillimeterPerRadian) => new RotationalStiffness((_value * 1000) / 1e6d, RotationalStiffnessUnit.MeganewtonMillimeterPerRadian), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMeterPerDegree) => new RotationalStiffness((_value / (180 / Math.PI)) / 1e-6d, RotationalStiffnessUnit.MicronewtonMeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMillimeterPerDegree) => new RotationalStiffness((_value / 180 * Math.PI * 1000) / 1e-6d, RotationalStiffnessUnit.MicronewtonMillimeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MicronewtonMillimeterPerRadian) => new RotationalStiffness((_value * 1000) / 1e-6d, RotationalStiffnessUnit.MicronewtonMillimeterPerRadian), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMeterPerDegree) => new RotationalStiffness((_value / (180 / Math.PI)) / 1e-3d, RotationalStiffnessUnit.MillinewtonMeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMillimeterPerDegree) => new RotationalStiffness((_value / 180 * Math.PI * 1000) / 1e-3d, RotationalStiffnessUnit.MillinewtonMillimeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.MillinewtonMillimeterPerRadian) => new RotationalStiffness((_value * 1000) / 1e-3d, RotationalStiffnessUnit.MillinewtonMillimeterPerRadian), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMeterPerDegree) => new RotationalStiffness((_value / (180 / Math.PI)) / 1e-9d, RotationalStiffnessUnit.NanonewtonMeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMillimeterPerDegree) => new RotationalStiffness((_value / 180 * Math.PI * 1000) / 1e-9d, RotationalStiffnessUnit.NanonewtonMillimeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NanonewtonMillimeterPerRadian) => new RotationalStiffness((_value * 1000) / 1e-9d, RotationalStiffnessUnit.NanonewtonMillimeterPerRadian), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMeterPerDegree) => new RotationalStiffness(_value / (180 / Math.PI), RotationalStiffnessUnit.NewtonMeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMillimeterPerDegree) => new RotationalStiffness(_value / 180 * Math.PI * 1000, RotationalStiffnessUnit.NewtonMillimeterPerDegree), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.NewtonMillimeterPerRadian) => new RotationalStiffness(_value * 1000, RotationalStiffnessUnit.NewtonMillimeterPerRadian), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.PoundForceFeetPerRadian) => new RotationalStiffness(_value / (4.4482216152605 * 0.3048), RotationalStiffnessUnit.PoundForceFeetPerRadian), - (RotationalStiffnessUnit.NewtonMeterPerRadian, RotationalStiffnessUnit.PoundForceFootPerDegrees) => new RotationalStiffness(_value / (4.4482216152605 * 0.3048 * 180 / Math.PI), RotationalStiffnessUnit.PoundForceFootPerDegrees), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public RotationalStiffness ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not RotationalStiffnessUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalStiffnessUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(RotationalStiffnessUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(RotationalStiffnessUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1350,7 +1124,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs index 36615225ff..1f2f1cefa7 100644 --- a/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/RotationalStiffnessPerLength.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Stiffness#Rotational_stiffness /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct RotationalStiffnessPerLength : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly RotationalStiffnessPerLengthUnit? _unit; /// @@ -104,7 +103,7 @@ public static RotationalStiffnessPerLengthInfo CreateDefault(Func - /// The for is [T^-2][L][M]. + /// The for is T^-2LM. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 1, -2, 0, 0, 0, 0); @@ -119,19 +118,25 @@ public static RotationalStiffnessPerLengthInfo CreateDefault(FuncAn of representing the default unit mappings for RotationalStiffnessPerLength. public static IEnumerable> GetDefaultMappings() { - yield return new (RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, "KilonewtonMeterPerRadianPerMeter", "KilonewtonMetersPerRadianPerMeter", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, "KilopoundForceFootPerDegreesPerFoot", "KilopoundForceFeetPerDegreesPerFeet", BaseUnits.Undefined); - yield return new (RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, "MeganewtonMeterPerRadianPerMeter", "MeganewtonMetersPerRadianPerMeter", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); + yield return new (RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, "KilonewtonMeterPerRadianPerMeter", "KilonewtonMetersPerRadianPerMeter", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000) + ); + yield return new (RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, "KilopoundForceFootPerDegreesPerFoot", "KilopoundForceFeetPerDegreesPerFeet", BaseUnits.Undefined, + new QuantityValue(3141592653589793, QuantityValue.PowerOfTen(7) * new BigInteger(80067989074689)) + ); + yield return new (RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, "MeganewtonMeterPerRadianPerMeter", "MeganewtonMetersPerRadianPerMeter", new BaseUnits(length: LengthUnit.Megameter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); yield return new (RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, "NewtonMeterPerRadianPerMeter", "NewtonMetersPerRadianPerMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, "PoundForceFootPerDegreesPerFoot", "PoundForceFeetPerDegreesPerFeet", BaseUnits.Undefined); + yield return new (RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, "PoundForceFootPerDegreesPerFoot", "PoundForceFeetPerDegreesPerFeet", BaseUnits.Undefined, + new QuantityValue(3141592653589793, 800679890746890000) + ); } } static RotationalStiffnessPerLength() { - Info = RotationalStiffnessPerLengthInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(RotationalStiffnessPerLengthInfo.CreateDefault); } /// @@ -139,7 +144,7 @@ static RotationalStiffnessPerLength() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public RotationalStiffnessPerLength(double value, RotationalStiffnessPerLengthUnit unit) + public RotationalStiffnessPerLength(QuantityValue value, RotationalStiffnessPerLengthUnit unit) { _value = value; _unit = unit; @@ -153,7 +158,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -164,7 +169,8 @@ public RotationalStiffnessPerLength(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -193,10 +199,8 @@ public RotationalStiffnessPerLength(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public RotationalStiffnessPerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -235,56 +239,34 @@ public RotationalStiffnessPerLength(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); + public QuantityValue KilonewtonMetersPerRadianPerMeter => this.As(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundForceFeetPerDegreesPerFeet => As(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot); + public QuantityValue KilopoundForceFeetPerDegreesPerFeet => this.As(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MeganewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); + public QuantityValue MeganewtonMetersPerRadianPerMeter => this.As(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonMetersPerRadianPerMeter => As(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); + public QuantityValue NewtonMetersPerRadianPerMeter => this.As(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundForceFeetPerDegreesPerFeet => As(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot); + public QuantityValue PoundForceFeetPerDegreesPerFeet => this.As(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: RotationalStiffnessPerLengthUnit -> BaseUnit - unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter)); - unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter)); - unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter)); - unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> RotationalStiffnessPerLengthUnit - unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter)); - unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot)); - unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter)); - unitConverter.SetConversionFunction(RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, quantity => quantity.ToUnit(RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot)); - } - /// /// Get unit abbreviation string. /// @@ -313,7 +295,7 @@ public static string GetAbbreviation(RotationalStiffnessPerLengthUnit unit, IFor /// /// Creates a from . /// - public static RotationalStiffnessPerLength FromKilonewtonMetersPerRadianPerMeter(double value) + public static RotationalStiffnessPerLength FromKilonewtonMetersPerRadianPerMeter(QuantityValue value) { return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter); } @@ -321,7 +303,7 @@ public static RotationalStiffnessPerLength FromKilonewtonMetersPerRadianPerMeter /// /// Creates a from . /// - public static RotationalStiffnessPerLength FromKilopoundForceFeetPerDegreesPerFeet(double value) + public static RotationalStiffnessPerLength FromKilopoundForceFeetPerDegreesPerFeet(QuantityValue value) { return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot); } @@ -329,7 +311,7 @@ public static RotationalStiffnessPerLength FromKilopoundForceFeetPerDegreesPerFe /// /// Creates a from . /// - public static RotationalStiffnessPerLength FromMeganewtonMetersPerRadianPerMeter(double value) + public static RotationalStiffnessPerLength FromMeganewtonMetersPerRadianPerMeter(QuantityValue value) { return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter); } @@ -337,7 +319,7 @@ public static RotationalStiffnessPerLength FromMeganewtonMetersPerRadianPerMeter /// /// Creates a from . /// - public static RotationalStiffnessPerLength FromNewtonMetersPerRadianPerMeter(double value) + public static RotationalStiffnessPerLength FromNewtonMetersPerRadianPerMeter(QuantityValue value) { return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter); } @@ -345,7 +327,7 @@ public static RotationalStiffnessPerLength FromNewtonMetersPerRadianPerMeter(dou /// /// Creates a from . /// - public static RotationalStiffnessPerLength FromPoundForceFeetPerDegreesPerFeet(double value) + public static RotationalStiffnessPerLength FromPoundForceFeetPerDegreesPerFeet(QuantityValue value) { return new RotationalStiffnessPerLength(value, RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot); } @@ -356,7 +338,7 @@ public static RotationalStiffnessPerLength FromPoundForceFeetPerDegreesPerFeet(d /// Value to convert from. /// Unit to convert from. /// RotationalStiffnessPerLength unit value. - public static RotationalStiffnessPerLength From(double value, RotationalStiffnessPerLengthUnit fromUnit) + public static RotationalStiffnessPerLength From(QuantityValue value, RotationalStiffnessPerLengthUnit fromUnit) { return new RotationalStiffnessPerLength(value, fromUnit); } @@ -417,10 +399,7 @@ public static RotationalStiffnessPerLength Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static RotationalStiffnessPerLength Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -448,11 +427,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out RotationalStiffn /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out RotationalStiffnessPerLength result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -473,7 +448,7 @@ public static RotationalStiffnessPerLengthUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -484,7 +459,7 @@ public static RotationalStiffnessPerLengthUnit ParseUnit(string str, IFormatProv return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out RotationalStiffnessPerLengthUnit unit) { return TryParseUnit(str, null, out unit); @@ -499,7 +474,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out RotationalSt /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out RotationalStiffnessPerLengthUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -518,35 +493,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static RotationalStiffnessPerLength operator +(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) { - return new RotationalStiffnessPerLength(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new RotationalStiffnessPerLength(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static RotationalStiffnessPerLength operator -(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) { - return new RotationalStiffnessPerLength(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new RotationalStiffnessPerLength(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -568,97 +543,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RotationalStiffnessPerLength other, RotationalStiffnessPerLength tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(RotationalStiffnessPerLength other, RotationalStiffnessPerLength tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(RotationalStiffnessPerLength left, RotationalStiffnessPerLength right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RotationalStiffnessPerLength other, RotationalStiffnessPerLength tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is RotationalStiffnessPerLength otherQuantity)) + if (obj is not RotationalStiffnessPerLength otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(RotationalStiffnessPerLength other, RotationalStiffnessPerLength tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(RotationalStiffnessPerLength other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current RotationalStiffnessPerLength. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(RotationalStiffnessPerLength), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is RotationalStiffnessPerLength otherQuantity)) throw new ArgumentException("Expected type RotationalStiffnessPerLength.", nameof(obj)); + if (obj is not RotationalStiffnessPerLength otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -670,154 +630,24 @@ public int CompareTo(object? obj) /// public int CompareTo(RotationalStiffnessPerLength other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(RotationalStiffnessPerLengthUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this RotationalStiffnessPerLength to another RotationalStiffnessPerLength with the unit representation . - /// - /// The unit to convert to. - /// A RotationalStiffnessPerLength with the specified unit. - public RotationalStiffnessPerLength ToUnit(RotationalStiffnessPerLengthUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A RotationalStiffnessPerLength with the specified unit. - public RotationalStiffnessPerLength ToUnit(RotationalStiffnessPerLengthUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(RotationalStiffnessPerLength), Unit, typeof(RotationalStiffnessPerLength), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (RotationalStiffnessPerLength)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(RotationalStiffnessPerLengthUnit unit, [NotNullWhen(true)] out RotationalStiffnessPerLength? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - RotationalStiffnessPerLength? convertedOrNull = (Unit, unit) switch - { - // RotationalStiffnessPerLengthUnit -> BaseUnit - (RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter) => new RotationalStiffnessPerLength((_value) * 1e3d, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter), - (RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter) => new RotationalStiffnessPerLength(_value * (4.4482216152605e3 * 180 / Math.PI), RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter), - (RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter) => new RotationalStiffnessPerLength((_value) * 1e6d, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter), - (RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot, RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter) => new RotationalStiffnessPerLength(_value * (4.4482216152605 * 180 / Math.PI), RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter), - - // BaseUnit -> RotationalStiffnessPerLengthUnit - (RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter) => new RotationalStiffnessPerLength((_value) / 1e3d, RotationalStiffnessPerLengthUnit.KilonewtonMeterPerRadianPerMeter), - (RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot) => new RotationalStiffnessPerLength(_value / (4.4482216152605e3 * 180 / Math.PI), RotationalStiffnessPerLengthUnit.KilopoundForceFootPerDegreesPerFoot), - (RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter) => new RotationalStiffnessPerLength((_value) / 1e6d, RotationalStiffnessPerLengthUnit.MeganewtonMeterPerRadianPerMeter), - (RotationalStiffnessPerLengthUnit.NewtonMeterPerRadianPerMeter, RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot) => new RotationalStiffnessPerLength(_value / (4.4482216152605 * 180 / Math.PI), RotationalStiffnessPerLengthUnit.PoundForceFootPerDegreesPerFoot), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public RotationalStiffnessPerLength ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not RotationalStiffnessPerLengthUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(RotationalStiffnessPerLengthUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(RotationalStiffnessPerLengthUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(RotationalStiffnessPerLengthUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -832,7 +662,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs b/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs index d6eb7d764c..3c51bf9787 100644 --- a/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Scalar.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// A way of representing a number of items. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Scalar : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ScalarUnit? _unit; /// @@ -122,9 +121,7 @@ public static IEnumerable> GetDefaultMappings() static Scalar() { - Info = ScalarInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ScalarInfo.CreateDefault); } /// @@ -132,7 +129,7 @@ static Scalar() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Scalar(double value, ScalarUnit unit) + public Scalar(QuantityValue value, ScalarUnit unit) { _value = value; _unit = unit; @@ -143,7 +140,8 @@ public Scalar(double value, ScalarUnit unit) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -172,10 +170,8 @@ public Scalar(double value, ScalarUnit unit) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ScalarUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -214,28 +210,14 @@ public Scalar(double value, ScalarUnit unit) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Amount => As(ScalarUnit.Amount); + public QuantityValue Amount => this.As(ScalarUnit.Amount); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ScalarUnit -> BaseUnit - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ScalarUnit.Amount, ScalarUnit.Amount, quantity => quantity); - - // Register in unit converter: BaseUnit -> ScalarUnit - } - /// /// Get unit abbreviation string. /// @@ -264,7 +246,7 @@ public static string GetAbbreviation(ScalarUnit unit, IFormatProvider? provider) /// /// Creates a from . /// - public static Scalar FromAmount(double value) + public static Scalar FromAmount(QuantityValue value) { return new Scalar(value, ScalarUnit.Amount); } @@ -275,7 +257,7 @@ public static Scalar FromAmount(double value) /// Value to convert from. /// Unit to convert from. /// Scalar unit value. - public static Scalar From(double value, ScalarUnit fromUnit) + public static Scalar From(QuantityValue value, ScalarUnit fromUnit) { return new Scalar(value, fromUnit); } @@ -336,10 +318,7 @@ public static Scalar Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Scalar Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -367,11 +346,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Scalar result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Scalar result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -392,7 +367,7 @@ public static ScalarUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -403,7 +378,7 @@ public static ScalarUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ScalarUnit unit) { return TryParseUnit(str, null, out unit); @@ -418,7 +393,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ScalarUnit u /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ScalarUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -437,35 +412,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Scalar operator +(Scalar left, Scalar right) { - return new Scalar(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Scalar(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Scalar operator -(Scalar left, Scalar right) { - return new Scalar(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Scalar(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -477,97 +452,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Scalar left, Scalar right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Scalar left, Scalar right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Scalar left, Scalar right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Scalar left, Scalar right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Scalar other, Scalar tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Scalar left, Scalar right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Scalar other, Scalar tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Scalar left, Scalar right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Scalar other, Scalar tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Scalar otherQuantity)) + if (obj is not Scalar otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Scalar other, Scalar tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Scalar other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Scalar. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Scalar), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Scalar otherQuantity)) throw new ArgumentException("Expected type Scalar.", nameof(obj)); + if (obj is not Scalar otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -579,146 +539,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Scalar other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ScalarUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this Scalar to another Scalar with the unit representation . - /// - /// The unit to convert to. - /// A Scalar with the specified unit. - public Scalar ToUnit(ScalarUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Scalar with the specified unit. - public Scalar ToUnit(ScalarUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Scalar), Unit, typeof(Scalar), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Scalar)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ScalarUnit unit, [NotNullWhen(true)] out Scalar? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Scalar? convertedOrNull = (Unit, unit) switch - { - // ScalarUnit -> BaseUnit + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> ScalarUnit - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Scalar ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ScalarUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ScalarUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ScalarUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ScalarUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ScalarUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(ScalarUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -733,7 +571,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs b/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs index 64edbe9778..c3fe5a1328 100644 --- a/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SolidAngle.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Solid_angle /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct SolidAngle : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly SolidAngleUnit? _unit; /// @@ -125,9 +124,7 @@ public static IEnumerable> GetDefaultMappings() static SolidAngle() { - Info = SolidAngleInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(SolidAngleInfo.CreateDefault); } /// @@ -135,7 +132,7 @@ static SolidAngle() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public SolidAngle(double value, SolidAngleUnit unit) + public SolidAngle(QuantityValue value, SolidAngleUnit unit) { _value = value; _unit = unit; @@ -146,7 +143,8 @@ public SolidAngle(double value, SolidAngleUnit unit) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -175,10 +173,8 @@ public SolidAngle(double value, SolidAngleUnit unit) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public SolidAngleUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -217,28 +213,14 @@ public SolidAngle(double value, SolidAngleUnit unit) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Steradians => As(SolidAngleUnit.Steradian); + public QuantityValue Steradians => this.As(SolidAngleUnit.Steradian); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: SolidAngleUnit -> BaseUnit - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(SolidAngleUnit.Steradian, SolidAngleUnit.Steradian, quantity => quantity); - - // Register in unit converter: BaseUnit -> SolidAngleUnit - } - /// /// Get unit abbreviation string. /// @@ -267,7 +249,7 @@ public static string GetAbbreviation(SolidAngleUnit unit, IFormatProvider? provi /// /// Creates a from . /// - public static SolidAngle FromSteradians(double value) + public static SolidAngle FromSteradians(QuantityValue value) { return new SolidAngle(value, SolidAngleUnit.Steradian); } @@ -278,7 +260,7 @@ public static SolidAngle FromSteradians(double value) /// Value to convert from. /// Unit to convert from. /// SolidAngle unit value. - public static SolidAngle From(double value, SolidAngleUnit fromUnit) + public static SolidAngle From(QuantityValue value, SolidAngleUnit fromUnit) { return new SolidAngle(value, fromUnit); } @@ -339,10 +321,7 @@ public static SolidAngle Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static SolidAngle Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -370,11 +349,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out SolidAngle resul /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out SolidAngle result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -395,7 +370,7 @@ public static SolidAngleUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -406,7 +381,7 @@ public static SolidAngleUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out SolidAngleUnit unit) { return TryParseUnit(str, null, out unit); @@ -421,7 +396,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out SolidAngleUn /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out SolidAngleUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -440,35 +415,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static SolidAngle operator +(SolidAngle left, SolidAngle right) { - return new SolidAngle(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new SolidAngle(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static SolidAngle operator -(SolidAngle left, SolidAngle right) { - return new SolidAngle(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new SolidAngle(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -480,97 +455,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(SolidAngle left, SolidAngle right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(SolidAngle left, SolidAngle right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(SolidAngle left, SolidAngle right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(SolidAngle left, SolidAngle right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(SolidAngle other, SolidAngle tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(SolidAngle left, SolidAngle right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(SolidAngle other, SolidAngle tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(SolidAngle left, SolidAngle right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(SolidAngle other, SolidAngle tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is SolidAngle otherQuantity)) + if (obj is not SolidAngle otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(SolidAngle other, SolidAngle tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(SolidAngle other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current SolidAngle. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(SolidAngle), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is SolidAngle otherQuantity)) throw new ArgumentException("Expected type SolidAngle.", nameof(obj)); + if (obj is not SolidAngle otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -582,146 +542,24 @@ public int CompareTo(object? obj) /// public int CompareTo(SolidAngle other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SolidAngleUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this SolidAngle to another SolidAngle with the unit representation . - /// - /// The unit to convert to. - /// A SolidAngle with the specified unit. - public SolidAngle ToUnit(SolidAngleUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A SolidAngle with the specified unit. - public SolidAngle ToUnit(SolidAngleUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(SolidAngle), Unit, typeof(SolidAngle), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (SolidAngle)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(SolidAngleUnit unit, [NotNullWhen(true)] out SolidAngle? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - SolidAngle? convertedOrNull = (Unit, unit) switch - { - // SolidAngleUnit -> BaseUnit + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> SolidAngleUnit - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public SolidAngle ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not SolidAngleUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SolidAngleUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is SolidAngleUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SolidAngleUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(SolidAngleUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(SolidAngleUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -736,7 +574,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs index 92f2fea62f..fbf7666197 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEnergy.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Specific_energy /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct SpecificEnergy : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -47,7 +46,7 @@ namespace UnitsNet IDivisionOperators, IDivisionOperators, IDivisionOperators, - IMultiplyOperators, + IMultiplyOperators, #endif #if NET7_0_OR_GREATER IComparisonOperators, @@ -61,13 +60,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly SpecificEnergyUnit? _unit; /// @@ -112,7 +111,7 @@ public static SpecificEnergyInfo CreateDefault(Func - /// The for is [T^-2][L^2]. + /// The for is T^-2L^2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, -2, 0, 0, 0, 0); @@ -127,44 +126,100 @@ public static SpecificEnergyInfo CreateDefault(FuncAn of representing the default unit mappings for SpecificEnergy. public static IEnumerable> GetDefaultMappings() { - yield return new (SpecificEnergyUnit.BtuPerPound, "BtuPerPound", "BtuPerPound", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.CaloriePerGram, "CaloriePerGram", "CaloriesPerGram", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.GigawattDayPerKilogram, "GigawattDayPerKilogram", "GigawattDaysPerKilogram", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.GigawattDayPerShortTon, "GigawattDayPerShortTon", "GigawattDaysPerShortTon", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.GigawattDayPerTonne, "GigawattDayPerTonne", "GigawattDaysPerTonne", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.GigawattHourPerKilogram, "GigawattHourPerKilogram", "GigawattHoursPerKilogram", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.GigawattHourPerPound, "GigawattHourPerPound", "GigawattHoursPerPound", BaseUnits.Undefined); + yield return new (SpecificEnergyUnit.BtuPerPound, "BtuPerPound", "BtuPerPound", BaseUnits.Undefined, + new QuantityValue(1, 2326) + ); + yield return new (SpecificEnergyUnit.CaloriePerGram, "CaloriePerGram", "CaloriesPerGram", BaseUnits.Undefined, + new QuantityValue(1, 4184) + ); + yield return new (SpecificEnergyUnit.GigawattDayPerKilogram, "GigawattDayPerKilogram", "GigawattDaysPerKilogram", BaseUnits.Undefined, + new QuantityValue(1, 86400000000000) + ); + yield return new (SpecificEnergyUnit.GigawattDayPerShortTon, "GigawattDayPerShortTon", "GigawattDaysPerShortTon", BaseUnits.Undefined, + new QuantityValue(45359237, 4320000000000000000) + ); + yield return new (SpecificEnergyUnit.GigawattDayPerTonne, "GigawattDayPerTonne", "GigawattDaysPerTonne", BaseUnits.Undefined, + new QuantityValue(1, 86400000000) + ); + yield return new (SpecificEnergyUnit.GigawattHourPerKilogram, "GigawattHourPerKilogram", "GigawattHoursPerKilogram", BaseUnits.Undefined, + new QuantityValue(1, 3600000000000) + ); + yield return new (SpecificEnergyUnit.GigawattHourPerPound, "GigawattHourPerPound", "GigawattHoursPerPound", BaseUnits.Undefined, + new QuantityValue(1, 7936640000000) + ); yield return new (SpecificEnergyUnit.JoulePerKilogram, "JoulePerKilogram", "JoulesPerKilogram", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)); - yield return new (SpecificEnergyUnit.KilocaloriePerGram, "KilocaloriePerGram", "KilocaloriesPerGram", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.KilojoulePerKilogram, "KilojoulePerKilogram", "KilojoulesPerKilogram", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.KilowattDayPerKilogram, "KilowattDayPerKilogram", "KilowattDaysPerKilogram", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.KilowattDayPerShortTon, "KilowattDayPerShortTon", "KilowattDaysPerShortTon", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.KilowattDayPerTonne, "KilowattDayPerTonne", "KilowattDaysPerTonne", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.KilowattHourPerKilogram, "KilowattHourPerKilogram", "KilowattHoursPerKilogram", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.KilowattHourPerPound, "KilowattHourPerPound", "KilowattHoursPerPound", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.MegajoulePerKilogram, "MegajoulePerKilogram", "MegajoulesPerKilogram", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second)); - yield return new (SpecificEnergyUnit.MegaJoulePerTonne, "MegaJoulePerTonne", "MegaJoulesPerTonne", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.MegawattDayPerKilogram, "MegawattDayPerKilogram", "MegawattDaysPerKilogram", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.MegawattDayPerShortTon, "MegawattDayPerShortTon", "MegawattDaysPerShortTon", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.MegawattDayPerTonne, "MegawattDayPerTonne", "MegawattDaysPerTonne", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.MegawattHourPerKilogram, "MegawattHourPerKilogram", "MegawattHoursPerKilogram", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.MegawattHourPerPound, "MegawattHourPerPound", "MegawattHoursPerPound", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.TerawattDayPerKilogram, "TerawattDayPerKilogram", "TerawattDaysPerKilogram", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.TerawattDayPerShortTon, "TerawattDayPerShortTon", "TerawattDaysPerShortTon", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.TerawattDayPerTonne, "TerawattDayPerTonne", "TerawattDaysPerTonne", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.WattDayPerKilogram, "WattDayPerKilogram", "WattDaysPerKilogram", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.WattDayPerShortTon, "WattDayPerShortTon", "WattDaysPerShortTon", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.WattDayPerTonne, "WattDayPerTonne", "WattDaysPerTonne", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.WattHourPerKilogram, "WattHourPerKilogram", "WattHoursPerKilogram", BaseUnits.Undefined); - yield return new (SpecificEnergyUnit.WattHourPerPound, "WattHourPerPound", "WattHoursPerPound", BaseUnits.Undefined); + yield return new (SpecificEnergyUnit.KilocaloriePerGram, "KilocaloriePerGram", "KilocaloriesPerGram", BaseUnits.Undefined, + new QuantityValue(1, 4184000) + ); + yield return new (SpecificEnergyUnit.KilojoulePerKilogram, "KilojoulePerKilogram", "KilojoulesPerKilogram", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (SpecificEnergyUnit.KilowattDayPerKilogram, "KilowattDayPerKilogram", "KilowattDaysPerKilogram", BaseUnits.Undefined, + new QuantityValue(1, 86400000) + ); + yield return new (SpecificEnergyUnit.KilowattDayPerShortTon, "KilowattDayPerShortTon", "KilowattDaysPerShortTon", BaseUnits.Undefined, + new QuantityValue(45359237, 4320000000000) + ); + yield return new (SpecificEnergyUnit.KilowattDayPerTonne, "KilowattDayPerTonne", "KilowattDaysPerTonne", BaseUnits.Undefined, + new QuantityValue(1, 86400) + ); + yield return new (SpecificEnergyUnit.KilowattHourPerKilogram, "KilowattHourPerKilogram", "KilowattHoursPerKilogram", BaseUnits.Undefined, + new QuantityValue(1, 3600000) + ); + yield return new (SpecificEnergyUnit.KilowattHourPerPound, "KilowattHourPerPound", "KilowattHoursPerPound", BaseUnits.Undefined, + new QuantityValue(1, 7936640) + ); + yield return new (SpecificEnergyUnit.MegajoulePerKilogram, "MegajoulePerKilogram", "MegajoulesPerKilogram", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (SpecificEnergyUnit.MegaJoulePerTonne, "MegaJoulePerTonne", "MegaJoulesPerTonne", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (SpecificEnergyUnit.MegawattDayPerKilogram, "MegawattDayPerKilogram", "MegawattDaysPerKilogram", BaseUnits.Undefined, + new QuantityValue(1, 86400000000) + ); + yield return new (SpecificEnergyUnit.MegawattDayPerShortTon, "MegawattDayPerShortTon", "MegawattDaysPerShortTon", BaseUnits.Undefined, + new QuantityValue(45359237, 4320000000000000) + ); + yield return new (SpecificEnergyUnit.MegawattDayPerTonne, "MegawattDayPerTonne", "MegawattDaysPerTonne", BaseUnits.Undefined, + new QuantityValue(1, 86400000) + ); + yield return new (SpecificEnergyUnit.MegawattHourPerKilogram, "MegawattHourPerKilogram", "MegawattHoursPerKilogram", BaseUnits.Undefined, + new QuantityValue(1, 3600000000) + ); + yield return new (SpecificEnergyUnit.MegawattHourPerPound, "MegawattHourPerPound", "MegawattHoursPerPound", BaseUnits.Undefined, + new QuantityValue(1, 7936640000) + ); + yield return new (SpecificEnergyUnit.TerawattDayPerKilogram, "TerawattDayPerKilogram", "TerawattDaysPerKilogram", BaseUnits.Undefined, + new QuantityValue(1, 86400000000000000) + ); + yield return new (SpecificEnergyUnit.TerawattDayPerShortTon, "TerawattDayPerShortTon", "TerawattDaysPerShortTon", BaseUnits.Undefined, + new QuantityValue(45359237, new BigInteger(432) * QuantityValue.PowerOfTen(19)) + ); + yield return new (SpecificEnergyUnit.TerawattDayPerTonne, "TerawattDayPerTonne", "TerawattDaysPerTonne", BaseUnits.Undefined, + new QuantityValue(1, 86400000000000) + ); + yield return new (SpecificEnergyUnit.WattDayPerKilogram, "WattDayPerKilogram", "WattDaysPerKilogram", BaseUnits.Undefined, + new QuantityValue(1, 86400) + ); + yield return new (SpecificEnergyUnit.WattDayPerShortTon, "WattDayPerShortTon", "WattDaysPerShortTon", BaseUnits.Undefined, + new QuantityValue(45359237, 4320000000) + ); + yield return new (SpecificEnergyUnit.WattDayPerTonne, "WattDayPerTonne", "WattDaysPerTonne", BaseUnits.Undefined, + new QuantityValue(5, 432) + ); + yield return new (SpecificEnergyUnit.WattHourPerKilogram, "WattHourPerKilogram", "WattHoursPerKilogram", BaseUnits.Undefined, + new QuantityValue(1, 3600) + ); + yield return new (SpecificEnergyUnit.WattHourPerPound, "WattHourPerPound", "WattHoursPerPound", BaseUnits.Undefined, + new QuantityValue(25, 198416) + ); } } static SpecificEnergy() { - Info = SpecificEnergyInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(SpecificEnergyInfo.CreateDefault); } /// @@ -172,7 +227,7 @@ static SpecificEnergy() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public SpecificEnergy(double value, SpecificEnergyUnit unit) + public SpecificEnergy(QuantityValue value, SpecificEnergyUnit unit) { _value = value; _unit = unit; @@ -186,7 +241,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -197,7 +252,8 @@ public SpecificEnergy(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -226,10 +282,8 @@ public SpecificEnergy(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public SpecificEnergyUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -268,231 +322,159 @@ public SpecificEnergy(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BtuPerPound => As(SpecificEnergyUnit.BtuPerPound); + public QuantityValue BtuPerPound => this.As(SpecificEnergyUnit.BtuPerPound); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CaloriesPerGram => As(SpecificEnergyUnit.CaloriePerGram); + public QuantityValue CaloriesPerGram => this.As(SpecificEnergyUnit.CaloriePerGram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigawattDaysPerKilogram => As(SpecificEnergyUnit.GigawattDayPerKilogram); + public QuantityValue GigawattDaysPerKilogram => this.As(SpecificEnergyUnit.GigawattDayPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigawattDaysPerShortTon => As(SpecificEnergyUnit.GigawattDayPerShortTon); + public QuantityValue GigawattDaysPerShortTon => this.As(SpecificEnergyUnit.GigawattDayPerShortTon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigawattDaysPerTonne => As(SpecificEnergyUnit.GigawattDayPerTonne); + public QuantityValue GigawattDaysPerTonne => this.As(SpecificEnergyUnit.GigawattDayPerTonne); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigawattHoursPerKilogram => As(SpecificEnergyUnit.GigawattHourPerKilogram); + public QuantityValue GigawattHoursPerKilogram => this.As(SpecificEnergyUnit.GigawattHourPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GigawattHoursPerPound => As(SpecificEnergyUnit.GigawattHourPerPound); + public QuantityValue GigawattHoursPerPound => this.As(SpecificEnergyUnit.GigawattHourPerPound); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double JoulesPerKilogram => As(SpecificEnergyUnit.JoulePerKilogram); + public QuantityValue JoulesPerKilogram => this.As(SpecificEnergyUnit.JoulePerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilocaloriesPerGram => As(SpecificEnergyUnit.KilocaloriePerGram); + public QuantityValue KilocaloriesPerGram => this.As(SpecificEnergyUnit.KilocaloriePerGram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilojoulesPerKilogram => As(SpecificEnergyUnit.KilojoulePerKilogram); + public QuantityValue KilojoulesPerKilogram => this.As(SpecificEnergyUnit.KilojoulePerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattDaysPerKilogram => As(SpecificEnergyUnit.KilowattDayPerKilogram); + public QuantityValue KilowattDaysPerKilogram => this.As(SpecificEnergyUnit.KilowattDayPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattDaysPerShortTon => As(SpecificEnergyUnit.KilowattDayPerShortTon); + public QuantityValue KilowattDaysPerShortTon => this.As(SpecificEnergyUnit.KilowattDayPerShortTon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattDaysPerTonne => As(SpecificEnergyUnit.KilowattDayPerTonne); + public QuantityValue KilowattDaysPerTonne => this.As(SpecificEnergyUnit.KilowattDayPerTonne); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattHoursPerKilogram => As(SpecificEnergyUnit.KilowattHourPerKilogram); + public QuantityValue KilowattHoursPerKilogram => this.As(SpecificEnergyUnit.KilowattHourPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilowattHoursPerPound => As(SpecificEnergyUnit.KilowattHourPerPound); + public QuantityValue KilowattHoursPerPound => this.As(SpecificEnergyUnit.KilowattHourPerPound); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegajoulesPerKilogram => As(SpecificEnergyUnit.MegajoulePerKilogram); + public QuantityValue MegajoulesPerKilogram => this.As(SpecificEnergyUnit.MegajoulePerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegaJoulesPerTonne => As(SpecificEnergyUnit.MegaJoulePerTonne); + public QuantityValue MegaJoulesPerTonne => this.As(SpecificEnergyUnit.MegaJoulePerTonne); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattDaysPerKilogram => As(SpecificEnergyUnit.MegawattDayPerKilogram); + public QuantityValue MegawattDaysPerKilogram => this.As(SpecificEnergyUnit.MegawattDayPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattDaysPerShortTon => As(SpecificEnergyUnit.MegawattDayPerShortTon); + public QuantityValue MegawattDaysPerShortTon => this.As(SpecificEnergyUnit.MegawattDayPerShortTon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattDaysPerTonne => As(SpecificEnergyUnit.MegawattDayPerTonne); + public QuantityValue MegawattDaysPerTonne => this.As(SpecificEnergyUnit.MegawattDayPerTonne); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattHoursPerKilogram => As(SpecificEnergyUnit.MegawattHourPerKilogram); + public QuantityValue MegawattHoursPerKilogram => this.As(SpecificEnergyUnit.MegawattHourPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegawattHoursPerPound => As(SpecificEnergyUnit.MegawattHourPerPound); + public QuantityValue MegawattHoursPerPound => this.As(SpecificEnergyUnit.MegawattHourPerPound); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TerawattDaysPerKilogram => As(SpecificEnergyUnit.TerawattDayPerKilogram); + public QuantityValue TerawattDaysPerKilogram => this.As(SpecificEnergyUnit.TerawattDayPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TerawattDaysPerShortTon => As(SpecificEnergyUnit.TerawattDayPerShortTon); + public QuantityValue TerawattDaysPerShortTon => this.As(SpecificEnergyUnit.TerawattDayPerShortTon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TerawattDaysPerTonne => As(SpecificEnergyUnit.TerawattDayPerTonne); + public QuantityValue TerawattDaysPerTonne => this.As(SpecificEnergyUnit.TerawattDayPerTonne); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattDaysPerKilogram => As(SpecificEnergyUnit.WattDayPerKilogram); + public QuantityValue WattDaysPerKilogram => this.As(SpecificEnergyUnit.WattDayPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattDaysPerShortTon => As(SpecificEnergyUnit.WattDayPerShortTon); + public QuantityValue WattDaysPerShortTon => this.As(SpecificEnergyUnit.WattDayPerShortTon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattDaysPerTonne => As(SpecificEnergyUnit.WattDayPerTonne); + public QuantityValue WattDaysPerTonne => this.As(SpecificEnergyUnit.WattDayPerTonne); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattHoursPerKilogram => As(SpecificEnergyUnit.WattHourPerKilogram); + public QuantityValue WattHoursPerKilogram => this.As(SpecificEnergyUnit.WattHourPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattHoursPerPound => As(SpecificEnergyUnit.WattHourPerPound); + public QuantityValue WattHoursPerPound => this.As(SpecificEnergyUnit.WattHourPerPound); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: SpecificEnergyUnit -> BaseUnit - unitConverter.SetConversionFunction(SpecificEnergyUnit.BtuPerPound, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.CaloriePerGram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.GigawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.GigawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.GigawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.GigawattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.GigawattHourPerPound, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.KilocaloriePerGram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.KilojoulePerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.KilowattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.KilowattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.KilowattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.KilowattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.KilowattHourPerPound, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.MegajoulePerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.MegaJoulePerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.MegawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.MegawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.MegawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.MegawattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.MegawattHourPerPound, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.TerawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.TerawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.TerawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.WattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.WattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.WattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.WattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.WattHourPerPound, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.JoulePerKilogram)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.JoulePerKilogram, quantity => quantity); - - // Register in unit converter: BaseUnit -> SpecificEnergyUnit - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.BtuPerPound, quantity => quantity.ToUnit(SpecificEnergyUnit.BtuPerPound)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.CaloriePerGram, quantity => quantity.ToUnit(SpecificEnergyUnit.CaloriePerGram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.GigawattDayPerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerShortTon, quantity => quantity.ToUnit(SpecificEnergyUnit.GigawattDayPerShortTon)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerTonne, quantity => quantity.ToUnit(SpecificEnergyUnit.GigawattDayPerTonne)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattHourPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.GigawattHourPerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattHourPerPound, quantity => quantity.ToUnit(SpecificEnergyUnit.GigawattHourPerPound)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilocaloriePerGram, quantity => quantity.ToUnit(SpecificEnergyUnit.KilocaloriePerGram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilojoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.KilojoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.KilowattDayPerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerShortTon, quantity => quantity.ToUnit(SpecificEnergyUnit.KilowattDayPerShortTon)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerTonne, quantity => quantity.ToUnit(SpecificEnergyUnit.KilowattDayPerTonne)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattHourPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.KilowattHourPerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattHourPerPound, quantity => quantity.ToUnit(SpecificEnergyUnit.KilowattHourPerPound)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegajoulePerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.MegajoulePerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegaJoulePerTonne, quantity => quantity.ToUnit(SpecificEnergyUnit.MegaJoulePerTonne)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.MegawattDayPerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerShortTon, quantity => quantity.ToUnit(SpecificEnergyUnit.MegawattDayPerShortTon)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerTonne, quantity => quantity.ToUnit(SpecificEnergyUnit.MegawattDayPerTonne)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattHourPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.MegawattHourPerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattHourPerPound, quantity => quantity.ToUnit(SpecificEnergyUnit.MegawattHourPerPound)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.TerawattDayPerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerShortTon, quantity => quantity.ToUnit(SpecificEnergyUnit.TerawattDayPerShortTon)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerTonne, quantity => quantity.ToUnit(SpecificEnergyUnit.TerawattDayPerTonne)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.WattDayPerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerShortTon, quantity => quantity.ToUnit(SpecificEnergyUnit.WattDayPerShortTon)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerTonne, quantity => quantity.ToUnit(SpecificEnergyUnit.WattDayPerTonne)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattHourPerKilogram, quantity => quantity.ToUnit(SpecificEnergyUnit.WattHourPerKilogram)); - unitConverter.SetConversionFunction(SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattHourPerPound, quantity => quantity.ToUnit(SpecificEnergyUnit.WattHourPerPound)); - } - /// /// Get unit abbreviation string. /// @@ -521,7 +503,7 @@ public static string GetAbbreviation(SpecificEnergyUnit unit, IFormatProvider? p /// /// Creates a from . /// - public static SpecificEnergy FromBtuPerPound(double value) + public static SpecificEnergy FromBtuPerPound(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.BtuPerPound); } @@ -529,7 +511,7 @@ public static SpecificEnergy FromBtuPerPound(double value) /// /// Creates a from . /// - public static SpecificEnergy FromCaloriesPerGram(double value) + public static SpecificEnergy FromCaloriesPerGram(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.CaloriePerGram); } @@ -537,7 +519,7 @@ public static SpecificEnergy FromCaloriesPerGram(double value) /// /// Creates a from . /// - public static SpecificEnergy FromGigawattDaysPerKilogram(double value) + public static SpecificEnergy FromGigawattDaysPerKilogram(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.GigawattDayPerKilogram); } @@ -545,7 +527,7 @@ public static SpecificEnergy FromGigawattDaysPerKilogram(double value) /// /// Creates a from . /// - public static SpecificEnergy FromGigawattDaysPerShortTon(double value) + public static SpecificEnergy FromGigawattDaysPerShortTon(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.GigawattDayPerShortTon); } @@ -553,7 +535,7 @@ public static SpecificEnergy FromGigawattDaysPerShortTon(double value) /// /// Creates a from . /// - public static SpecificEnergy FromGigawattDaysPerTonne(double value) + public static SpecificEnergy FromGigawattDaysPerTonne(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.GigawattDayPerTonne); } @@ -561,7 +543,7 @@ public static SpecificEnergy FromGigawattDaysPerTonne(double value) /// /// Creates a from . /// - public static SpecificEnergy FromGigawattHoursPerKilogram(double value) + public static SpecificEnergy FromGigawattHoursPerKilogram(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.GigawattHourPerKilogram); } @@ -569,7 +551,7 @@ public static SpecificEnergy FromGigawattHoursPerKilogram(double value) /// /// Creates a from . /// - public static SpecificEnergy FromGigawattHoursPerPound(double value) + public static SpecificEnergy FromGigawattHoursPerPound(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.GigawattHourPerPound); } @@ -577,7 +559,7 @@ public static SpecificEnergy FromGigawattHoursPerPound(double value) /// /// Creates a from . /// - public static SpecificEnergy FromJoulesPerKilogram(double value) + public static SpecificEnergy FromJoulesPerKilogram(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.JoulePerKilogram); } @@ -585,7 +567,7 @@ public static SpecificEnergy FromJoulesPerKilogram(double value) /// /// Creates a from . /// - public static SpecificEnergy FromKilocaloriesPerGram(double value) + public static SpecificEnergy FromKilocaloriesPerGram(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.KilocaloriePerGram); } @@ -593,7 +575,7 @@ public static SpecificEnergy FromKilocaloriesPerGram(double value) /// /// Creates a from . /// - public static SpecificEnergy FromKilojoulesPerKilogram(double value) + public static SpecificEnergy FromKilojoulesPerKilogram(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.KilojoulePerKilogram); } @@ -601,7 +583,7 @@ public static SpecificEnergy FromKilojoulesPerKilogram(double value) /// /// Creates a from . /// - public static SpecificEnergy FromKilowattDaysPerKilogram(double value) + public static SpecificEnergy FromKilowattDaysPerKilogram(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.KilowattDayPerKilogram); } @@ -609,7 +591,7 @@ public static SpecificEnergy FromKilowattDaysPerKilogram(double value) /// /// Creates a from . /// - public static SpecificEnergy FromKilowattDaysPerShortTon(double value) + public static SpecificEnergy FromKilowattDaysPerShortTon(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.KilowattDayPerShortTon); } @@ -617,7 +599,7 @@ public static SpecificEnergy FromKilowattDaysPerShortTon(double value) /// /// Creates a from . /// - public static SpecificEnergy FromKilowattDaysPerTonne(double value) + public static SpecificEnergy FromKilowattDaysPerTonne(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.KilowattDayPerTonne); } @@ -625,7 +607,7 @@ public static SpecificEnergy FromKilowattDaysPerTonne(double value) /// /// Creates a from . /// - public static SpecificEnergy FromKilowattHoursPerKilogram(double value) + public static SpecificEnergy FromKilowattHoursPerKilogram(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.KilowattHourPerKilogram); } @@ -633,7 +615,7 @@ public static SpecificEnergy FromKilowattHoursPerKilogram(double value) /// /// Creates a from . /// - public static SpecificEnergy FromKilowattHoursPerPound(double value) + public static SpecificEnergy FromKilowattHoursPerPound(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.KilowattHourPerPound); } @@ -641,7 +623,7 @@ public static SpecificEnergy FromKilowattHoursPerPound(double value) /// /// Creates a from . /// - public static SpecificEnergy FromMegajoulesPerKilogram(double value) + public static SpecificEnergy FromMegajoulesPerKilogram(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.MegajoulePerKilogram); } @@ -649,7 +631,7 @@ public static SpecificEnergy FromMegajoulesPerKilogram(double value) /// /// Creates a from . /// - public static SpecificEnergy FromMegaJoulesPerTonne(double value) + public static SpecificEnergy FromMegaJoulesPerTonne(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.MegaJoulePerTonne); } @@ -657,7 +639,7 @@ public static SpecificEnergy FromMegaJoulesPerTonne(double value) /// /// Creates a from . /// - public static SpecificEnergy FromMegawattDaysPerKilogram(double value) + public static SpecificEnergy FromMegawattDaysPerKilogram(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.MegawattDayPerKilogram); } @@ -665,7 +647,7 @@ public static SpecificEnergy FromMegawattDaysPerKilogram(double value) /// /// Creates a from . /// - public static SpecificEnergy FromMegawattDaysPerShortTon(double value) + public static SpecificEnergy FromMegawattDaysPerShortTon(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.MegawattDayPerShortTon); } @@ -673,7 +655,7 @@ public static SpecificEnergy FromMegawattDaysPerShortTon(double value) /// /// Creates a from . /// - public static SpecificEnergy FromMegawattDaysPerTonne(double value) + public static SpecificEnergy FromMegawattDaysPerTonne(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.MegawattDayPerTonne); } @@ -681,7 +663,7 @@ public static SpecificEnergy FromMegawattDaysPerTonne(double value) /// /// Creates a from . /// - public static SpecificEnergy FromMegawattHoursPerKilogram(double value) + public static SpecificEnergy FromMegawattHoursPerKilogram(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.MegawattHourPerKilogram); } @@ -689,7 +671,7 @@ public static SpecificEnergy FromMegawattHoursPerKilogram(double value) /// /// Creates a from . /// - public static SpecificEnergy FromMegawattHoursPerPound(double value) + public static SpecificEnergy FromMegawattHoursPerPound(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.MegawattHourPerPound); } @@ -697,7 +679,7 @@ public static SpecificEnergy FromMegawattHoursPerPound(double value) /// /// Creates a from . /// - public static SpecificEnergy FromTerawattDaysPerKilogram(double value) + public static SpecificEnergy FromTerawattDaysPerKilogram(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.TerawattDayPerKilogram); } @@ -705,7 +687,7 @@ public static SpecificEnergy FromTerawattDaysPerKilogram(double value) /// /// Creates a from . /// - public static SpecificEnergy FromTerawattDaysPerShortTon(double value) + public static SpecificEnergy FromTerawattDaysPerShortTon(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.TerawattDayPerShortTon); } @@ -713,7 +695,7 @@ public static SpecificEnergy FromTerawattDaysPerShortTon(double value) /// /// Creates a from . /// - public static SpecificEnergy FromTerawattDaysPerTonne(double value) + public static SpecificEnergy FromTerawattDaysPerTonne(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.TerawattDayPerTonne); } @@ -721,7 +703,7 @@ public static SpecificEnergy FromTerawattDaysPerTonne(double value) /// /// Creates a from . /// - public static SpecificEnergy FromWattDaysPerKilogram(double value) + public static SpecificEnergy FromWattDaysPerKilogram(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.WattDayPerKilogram); } @@ -729,7 +711,7 @@ public static SpecificEnergy FromWattDaysPerKilogram(double value) /// /// Creates a from . /// - public static SpecificEnergy FromWattDaysPerShortTon(double value) + public static SpecificEnergy FromWattDaysPerShortTon(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.WattDayPerShortTon); } @@ -737,7 +719,7 @@ public static SpecificEnergy FromWattDaysPerShortTon(double value) /// /// Creates a from . /// - public static SpecificEnergy FromWattDaysPerTonne(double value) + public static SpecificEnergy FromWattDaysPerTonne(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.WattDayPerTonne); } @@ -745,7 +727,7 @@ public static SpecificEnergy FromWattDaysPerTonne(double value) /// /// Creates a from . /// - public static SpecificEnergy FromWattHoursPerKilogram(double value) + public static SpecificEnergy FromWattHoursPerKilogram(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.WattHourPerKilogram); } @@ -753,7 +735,7 @@ public static SpecificEnergy FromWattHoursPerKilogram(double value) /// /// Creates a from . /// - public static SpecificEnergy FromWattHoursPerPound(double value) + public static SpecificEnergy FromWattHoursPerPound(QuantityValue value) { return new SpecificEnergy(value, SpecificEnergyUnit.WattHourPerPound); } @@ -764,7 +746,7 @@ public static SpecificEnergy FromWattHoursPerPound(double value) /// Value to convert from. /// Unit to convert from. /// SpecificEnergy unit value. - public static SpecificEnergy From(double value, SpecificEnergyUnit fromUnit) + public static SpecificEnergy From(QuantityValue value, SpecificEnergyUnit fromUnit) { return new SpecificEnergy(value, fromUnit); } @@ -825,10 +807,7 @@ public static SpecificEnergy Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static SpecificEnergy Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -856,11 +835,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out SpecificEnergy r /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out SpecificEnergy result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -881,7 +856,7 @@ public static SpecificEnergyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -892,7 +867,7 @@ public static SpecificEnergyUnit ParseUnit(string str, IFormatProvider? provider return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out SpecificEnergyUnit unit) { return TryParseUnit(str, null, out unit); @@ -907,7 +882,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out SpecificEner /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out SpecificEnergyUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -926,35 +901,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static SpecificEnergy operator +(SpecificEnergy left, SpecificEnergy right) { - return new SpecificEnergy(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new SpecificEnergy(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static SpecificEnergy operator -(SpecificEnergy left, SpecificEnergy right) { - return new SpecificEnergy(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new SpecificEnergy(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -963,8 +938,8 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? #region Relational Operators - /// Get from / . - public static BrakeSpecificFuelConsumption operator /(double value, SpecificEnergy specificEnergy) + /// Get from / . + public static BrakeSpecificFuelConsumption operator /(QuantityValue value, SpecificEnergy specificEnergy) { return BrakeSpecificFuelConsumption.FromKilogramsPerJoule(value / specificEnergy.JoulesPerKilogram); } @@ -999,8 +974,8 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? return TemperatureDelta.FromKelvins(specificEnergy.JoulesPerKilogram / specificEntropy.JoulesPerKilogramKelvin); } - /// Get from * . - public static double operator *(SpecificEnergy specificEnergy, BrakeSpecificFuelConsumption brakeSpecificFuelConsumption) + /// Get from * . + public static QuantityValue operator *(SpecificEnergy specificEnergy, BrakeSpecificFuelConsumption brakeSpecificFuelConsumption) { return specificEnergy.JoulesPerKilogram * brakeSpecificFuelConsumption.KilogramsPerJoule; } @@ -1012,97 +987,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(SpecificEnergy left, SpecificEnergy right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(SpecificEnergy left, SpecificEnergy right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(SpecificEnergy left, SpecificEnergy right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(SpecificEnergy left, SpecificEnergy right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(SpecificEnergy other, SpecificEnergy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(SpecificEnergy left, SpecificEnergy right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(SpecificEnergy other, SpecificEnergy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(SpecificEnergy left, SpecificEnergy right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(SpecificEnergy other, SpecificEnergy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is SpecificEnergy otherQuantity)) + if (obj is not SpecificEnergy otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(SpecificEnergy other, SpecificEnergy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(SpecificEnergy other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current SpecificEnergy. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(SpecificEnergy), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is SpecificEnergy otherQuantity)) throw new ArgumentException("Expected type SpecificEnergy.", nameof(obj)); + if (obj is not SpecificEnergy otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1114,204 +1074,24 @@ public int CompareTo(object? obj) /// public int CompareTo(SpecificEnergy other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificEnergyUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this SpecificEnergy to another SpecificEnergy with the unit representation . - /// - /// The unit to convert to. - /// A SpecificEnergy with the specified unit. - public SpecificEnergy ToUnit(SpecificEnergyUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A SpecificEnergy with the specified unit. - public SpecificEnergy ToUnit(SpecificEnergyUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(SpecificEnergy), Unit, typeof(SpecificEnergy), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (SpecificEnergy)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(SpecificEnergyUnit unit, [NotNullWhen(true)] out SpecificEnergy? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - SpecificEnergy? convertedOrNull = (Unit, unit) switch - { - // SpecificEnergyUnit -> BaseUnit - (SpecificEnergyUnit.BtuPerPound, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy(_value * 1055.05585262 / 0.45359237, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.CaloriePerGram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy(_value * 4.184e3, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.GigawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * (24 * 3.6e3)) * 1e9d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.GigawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e9d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.GigawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * ((24 * 3.6e3) / 1e3)) * 1e9d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.GigawattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * 3.6e3) * 1e9d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.GigawattHourPerPound, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * 7.93664e3) * 1e9d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.KilocaloriePerGram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * 4.184e3) * 1e3d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.KilojoulePerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value) * 1e3d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.KilowattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * (24 * 3.6e3)) * 1e3d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.KilowattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e3d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.KilowattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * ((24 * 3.6e3) / 1e3)) * 1e3d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.KilowattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * 3.6e3) * 1e3d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.KilowattHourPerPound, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * 7.93664e3) * 1e3d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.MegajoulePerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value) * 1e6d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.MegaJoulePerTonne, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy(_value * 1e3, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.MegawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * (24 * 3.6e3)) * 1e6d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.MegawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e6d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.MegawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * ((24 * 3.6e3) / 1e3)) * 1e6d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.MegawattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * 3.6e3) * 1e6d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.MegawattHourPerPound, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * 7.93664e3) * 1e6d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.TerawattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * (24 * 3.6e3)) * 1e12d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.TerawattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * ((24 * 3.6e3) / 9.0718474e2)) * 1e12d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.TerawattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy((_value * ((24 * 3.6e3) / 1e3)) * 1e12d, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.WattDayPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy(_value * (24 * 3.6e3), SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.WattDayPerShortTon, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy(_value * ((24 * 3.6e3) / 9.0718474e2), SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.WattDayPerTonne, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy(_value * ((24 * 3.6e3) / 1e3), SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.WattHourPerKilogram, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy(_value * 3.6e3, SpecificEnergyUnit.JoulePerKilogram), - (SpecificEnergyUnit.WattHourPerPound, SpecificEnergyUnit.JoulePerKilogram) => new SpecificEnergy(_value * 7.93664e3, SpecificEnergyUnit.JoulePerKilogram), - - // BaseUnit -> SpecificEnergyUnit - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.BtuPerPound) => new SpecificEnergy(_value * 0.45359237 / 1055.05585262, SpecificEnergyUnit.BtuPerPound), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.CaloriePerGram) => new SpecificEnergy(_value / 4.184e3, SpecificEnergyUnit.CaloriePerGram), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerKilogram) => new SpecificEnergy((_value / (24 * 3.6e3)) / 1e9d, SpecificEnergyUnit.GigawattDayPerKilogram), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerShortTon) => new SpecificEnergy((_value / ((24 * 3.6e3) / 9.0718474e2)) / 1e9d, SpecificEnergyUnit.GigawattDayPerShortTon), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattDayPerTonne) => new SpecificEnergy((_value / ((24 * 3.6e3) / 1e3)) / 1e9d, SpecificEnergyUnit.GigawattDayPerTonne), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattHourPerKilogram) => new SpecificEnergy((_value / 3.6e3) / 1e9d, SpecificEnergyUnit.GigawattHourPerKilogram), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.GigawattHourPerPound) => new SpecificEnergy((_value / 7.93664e3) / 1e9d, SpecificEnergyUnit.GigawattHourPerPound), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilocaloriePerGram) => new SpecificEnergy((_value / 4.184e3) / 1e3d, SpecificEnergyUnit.KilocaloriePerGram), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilojoulePerKilogram) => new SpecificEnergy((_value) / 1e3d, SpecificEnergyUnit.KilojoulePerKilogram), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerKilogram) => new SpecificEnergy((_value / (24 * 3.6e3)) / 1e3d, SpecificEnergyUnit.KilowattDayPerKilogram), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerShortTon) => new SpecificEnergy((_value / ((24 * 3.6e3) / 9.0718474e2)) / 1e3d, SpecificEnergyUnit.KilowattDayPerShortTon), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattDayPerTonne) => new SpecificEnergy((_value / ((24 * 3.6e3) / 1e3)) / 1e3d, SpecificEnergyUnit.KilowattDayPerTonne), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattHourPerKilogram) => new SpecificEnergy((_value / 3.6e3) / 1e3d, SpecificEnergyUnit.KilowattHourPerKilogram), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.KilowattHourPerPound) => new SpecificEnergy((_value / 7.93664e3) / 1e3d, SpecificEnergyUnit.KilowattHourPerPound), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegajoulePerKilogram) => new SpecificEnergy((_value) / 1e6d, SpecificEnergyUnit.MegajoulePerKilogram), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegaJoulePerTonne) => new SpecificEnergy(_value / 1e3, SpecificEnergyUnit.MegaJoulePerTonne), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerKilogram) => new SpecificEnergy((_value / (24 * 3.6e3)) / 1e6d, SpecificEnergyUnit.MegawattDayPerKilogram), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerShortTon) => new SpecificEnergy((_value / ((24 * 3.6e3) / 9.0718474e2)) / 1e6d, SpecificEnergyUnit.MegawattDayPerShortTon), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattDayPerTonne) => new SpecificEnergy((_value / ((24 * 3.6e3) / 1e3)) / 1e6d, SpecificEnergyUnit.MegawattDayPerTonne), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattHourPerKilogram) => new SpecificEnergy((_value / 3.6e3) / 1e6d, SpecificEnergyUnit.MegawattHourPerKilogram), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.MegawattHourPerPound) => new SpecificEnergy((_value / 7.93664e3) / 1e6d, SpecificEnergyUnit.MegawattHourPerPound), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerKilogram) => new SpecificEnergy((_value / (24 * 3.6e3)) / 1e12d, SpecificEnergyUnit.TerawattDayPerKilogram), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerShortTon) => new SpecificEnergy((_value / ((24 * 3.6e3) / 9.0718474e2)) / 1e12d, SpecificEnergyUnit.TerawattDayPerShortTon), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.TerawattDayPerTonne) => new SpecificEnergy((_value / ((24 * 3.6e3) / 1e3)) / 1e12d, SpecificEnergyUnit.TerawattDayPerTonne), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerKilogram) => new SpecificEnergy(_value / (24 * 3.6e3), SpecificEnergyUnit.WattDayPerKilogram), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerShortTon) => new SpecificEnergy(_value / ((24 * 3.6e3) / 9.0718474e2), SpecificEnergyUnit.WattDayPerShortTon), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattDayPerTonne) => new SpecificEnergy(_value / ((24 * 3.6e3) / 1e3), SpecificEnergyUnit.WattDayPerTonne), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattHourPerKilogram) => new SpecificEnergy(_value / 3.6e3, SpecificEnergyUnit.WattHourPerKilogram), - (SpecificEnergyUnit.JoulePerKilogram, SpecificEnergyUnit.WattHourPerPound) => new SpecificEnergy(_value / 7.93664e3, SpecificEnergyUnit.WattHourPerPound), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public SpecificEnergy ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not SpecificEnergyUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificEnergyUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(SpecificEnergyUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(SpecificEnergyUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1326,7 +1106,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs index 254787637e..ab0186d0e9 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificEntropy.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// Specific entropy is an amount of energy required to raise temperature of a substance by 1 Kelvin per unit mass. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct SpecificEntropy : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -54,13 +53,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly SpecificEntropyUnit? _unit; /// @@ -105,7 +104,7 @@ public static SpecificEntropyInfo CreateDefault(Func - /// The for is [T^-2][L^2][Θ^-1]. + /// The for is T^-2L^2Θ^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, -2, 0, -1, 0, 0); @@ -120,23 +119,37 @@ public static SpecificEntropyInfo CreateDefault(FuncAn of representing the default unit mappings for SpecificEntropy. public static IEnumerable> GetDefaultMappings() { - yield return new (SpecificEntropyUnit.BtuPerPoundFahrenheit, "BtuPerPoundFahrenheit", "BtusPerPoundFahrenheit", BaseUnits.Undefined); - yield return new (SpecificEntropyUnit.CaloriePerGramKelvin, "CaloriePerGramKelvin", "CaloriesPerGramKelvin", BaseUnits.Undefined); - yield return new (SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, "JoulePerKilogramDegreeCelsius", "JoulesPerKilogramDegreeCelsius", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius)); + yield return new (SpecificEntropyUnit.BtuPerPoundFahrenheit, "BtuPerPoundFahrenheit", "BtusPerPoundFahrenheit", BaseUnits.Undefined, + new QuantityValue(5, 20934) + ); + yield return new (SpecificEntropyUnit.CaloriePerGramKelvin, "CaloriePerGramKelvin", "CaloriesPerGramKelvin", BaseUnits.Undefined, + new QuantityValue(1, 4184) + ); + yield return new (SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, "JoulePerKilogramDegreeCelsius", "JoulesPerKilogramDegreeCelsius", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), + 1 + ); yield return new (SpecificEntropyUnit.JoulePerKilogramKelvin, "JoulePerKilogramKelvin", "JoulesPerKilogramKelvin", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin)); - yield return new (SpecificEntropyUnit.KilocaloriePerGramKelvin, "KilocaloriePerGramKelvin", "KilocaloriesPerGramKelvin", BaseUnits.Undefined); - yield return new (SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, "KilojoulePerKilogramDegreeCelsius", "KilojoulesPerKilogramDegreeCelsius", BaseUnits.Undefined); - yield return new (SpecificEntropyUnit.KilojoulePerKilogramKelvin, "KilojoulePerKilogramKelvin", "KilojoulesPerKilogramKelvin", BaseUnits.Undefined); - yield return new (SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, "MegajoulePerKilogramDegreeCelsius", "MegajoulesPerKilogramDegreeCelsius", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius)); - yield return new (SpecificEntropyUnit.MegajoulePerKilogramKelvin, "MegajoulePerKilogramKelvin", "MegajoulesPerKilogramKelvin", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin)); + yield return new (SpecificEntropyUnit.KilocaloriePerGramKelvin, "KilocaloriePerGramKelvin", "KilocaloriesPerGramKelvin", BaseUnits.Undefined, + new QuantityValue(1, 4184000) + ); + yield return new (SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, "KilojoulePerKilogramDegreeCelsius", "KilojoulesPerKilogramDegreeCelsius", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (SpecificEntropyUnit.KilojoulePerKilogramKelvin, "KilojoulePerKilogramKelvin", "KilojoulesPerKilogramKelvin", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, "MegajoulePerKilogramDegreeCelsius", "MegajoulesPerKilogramDegreeCelsius", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), + new QuantityValue(1, 1000000) + ); + yield return new (SpecificEntropyUnit.MegajoulePerKilogramKelvin, "MegajoulePerKilogramKelvin", "MegajoulesPerKilogramKelvin", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin), + new QuantityValue(1, 1000000) + ); } } static SpecificEntropy() { - Info = SpecificEntropyInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(SpecificEntropyInfo.CreateDefault); } /// @@ -144,7 +157,7 @@ static SpecificEntropy() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public SpecificEntropy(double value, SpecificEntropyUnit unit) + public SpecificEntropy(QuantityValue value, SpecificEntropyUnit unit) { _value = value; _unit = unit; @@ -158,7 +171,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -169,7 +182,8 @@ public SpecificEntropy(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -198,10 +212,8 @@ public SpecificEntropy(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public SpecificEntropyUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -240,84 +252,54 @@ public SpecificEntropy(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BtusPerPoundFahrenheit => As(SpecificEntropyUnit.BtuPerPoundFahrenheit); + public QuantityValue BtusPerPoundFahrenheit => this.As(SpecificEntropyUnit.BtuPerPoundFahrenheit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CaloriesPerGramKelvin => As(SpecificEntropyUnit.CaloriePerGramKelvin); + public QuantityValue CaloriesPerGramKelvin => this.As(SpecificEntropyUnit.CaloriePerGramKelvin); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double JoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); + public QuantityValue JoulesPerKilogramDegreeCelsius => this.As(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double JoulesPerKilogramKelvin => As(SpecificEntropyUnit.JoulePerKilogramKelvin); + public QuantityValue JoulesPerKilogramKelvin => this.As(SpecificEntropyUnit.JoulePerKilogramKelvin); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilocaloriesPerGramKelvin => As(SpecificEntropyUnit.KilocaloriePerGramKelvin); + public QuantityValue KilocaloriesPerGramKelvin => this.As(SpecificEntropyUnit.KilocaloriePerGramKelvin); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilojoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); + public QuantityValue KilojoulesPerKilogramDegreeCelsius => this.As(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilojoulesPerKilogramKelvin => As(SpecificEntropyUnit.KilojoulePerKilogramKelvin); + public QuantityValue KilojoulesPerKilogramKelvin => this.As(SpecificEntropyUnit.KilojoulePerKilogramKelvin); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegajoulesPerKilogramDegreeCelsius => As(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); + public QuantityValue MegajoulesPerKilogramDegreeCelsius => this.As(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegajoulesPerKilogramKelvin => As(SpecificEntropyUnit.MegajoulePerKilogramKelvin); + public QuantityValue MegajoulesPerKilogramKelvin => this.As(SpecificEntropyUnit.MegajoulePerKilogramKelvin); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: SpecificEntropyUnit -> BaseUnit - unitConverter.SetConversionFunction(SpecificEntropyUnit.BtuPerPoundFahrenheit, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.CaloriePerGramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.KilocaloriePerGramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.KilojoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.MegajoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramKelvin)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin, quantity => quantity); - - // Register in unit converter: BaseUnit -> SpecificEntropyUnit - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.BtuPerPoundFahrenheit, quantity => quantity.ToUnit(SpecificEntropyUnit.BtuPerPoundFahrenheit)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.CaloriePerGramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.CaloriePerGramKelvin)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, quantity => quantity.ToUnit(SpecificEntropyUnit.JoulePerKilogramDegreeCelsius)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilocaloriePerGramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.KilocaloriePerGramKelvin)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, quantity => quantity.ToUnit(SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilojoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.KilojoulePerKilogramKelvin)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, quantity => quantity.ToUnit(SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius)); - unitConverter.SetConversionFunction(SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.MegajoulePerKilogramKelvin, quantity => quantity.ToUnit(SpecificEntropyUnit.MegajoulePerKilogramKelvin)); - } - /// /// Get unit abbreviation string. /// @@ -346,7 +328,7 @@ public static string GetAbbreviation(SpecificEntropyUnit unit, IFormatProvider? /// /// Creates a from . /// - public static SpecificEntropy FromBtusPerPoundFahrenheit(double value) + public static SpecificEntropy FromBtusPerPoundFahrenheit(QuantityValue value) { return new SpecificEntropy(value, SpecificEntropyUnit.BtuPerPoundFahrenheit); } @@ -354,7 +336,7 @@ public static SpecificEntropy FromBtusPerPoundFahrenheit(double value) /// /// Creates a from . /// - public static SpecificEntropy FromCaloriesPerGramKelvin(double value) + public static SpecificEntropy FromCaloriesPerGramKelvin(QuantityValue value) { return new SpecificEntropy(value, SpecificEntropyUnit.CaloriePerGramKelvin); } @@ -362,7 +344,7 @@ public static SpecificEntropy FromCaloriesPerGramKelvin(double value) /// /// Creates a from . /// - public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(double value) + public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(QuantityValue value) { return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius); } @@ -370,7 +352,7 @@ public static SpecificEntropy FromJoulesPerKilogramDegreeCelsius(double value) /// /// Creates a from . /// - public static SpecificEntropy FromJoulesPerKilogramKelvin(double value) + public static SpecificEntropy FromJoulesPerKilogramKelvin(QuantityValue value) { return new SpecificEntropy(value, SpecificEntropyUnit.JoulePerKilogramKelvin); } @@ -378,7 +360,7 @@ public static SpecificEntropy FromJoulesPerKilogramKelvin(double value) /// /// Creates a from . /// - public static SpecificEntropy FromKilocaloriesPerGramKelvin(double value) + public static SpecificEntropy FromKilocaloriesPerGramKelvin(QuantityValue value) { return new SpecificEntropy(value, SpecificEntropyUnit.KilocaloriePerGramKelvin); } @@ -386,7 +368,7 @@ public static SpecificEntropy FromKilocaloriesPerGramKelvin(double value) /// /// Creates a from . /// - public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(double value) + public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(QuantityValue value) { return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius); } @@ -394,7 +376,7 @@ public static SpecificEntropy FromKilojoulesPerKilogramDegreeCelsius(double valu /// /// Creates a from . /// - public static SpecificEntropy FromKilojoulesPerKilogramKelvin(double value) + public static SpecificEntropy FromKilojoulesPerKilogramKelvin(QuantityValue value) { return new SpecificEntropy(value, SpecificEntropyUnit.KilojoulePerKilogramKelvin); } @@ -402,7 +384,7 @@ public static SpecificEntropy FromKilojoulesPerKilogramKelvin(double value) /// /// Creates a from . /// - public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(double value) + public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(QuantityValue value) { return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius); } @@ -410,7 +392,7 @@ public static SpecificEntropy FromMegajoulesPerKilogramDegreeCelsius(double valu /// /// Creates a from . /// - public static SpecificEntropy FromMegajoulesPerKilogramKelvin(double value) + public static SpecificEntropy FromMegajoulesPerKilogramKelvin(QuantityValue value) { return new SpecificEntropy(value, SpecificEntropyUnit.MegajoulePerKilogramKelvin); } @@ -421,7 +403,7 @@ public static SpecificEntropy FromMegajoulesPerKilogramKelvin(double value) /// Value to convert from. /// Unit to convert from. /// SpecificEntropy unit value. - public static SpecificEntropy From(double value, SpecificEntropyUnit fromUnit) + public static SpecificEntropy From(QuantityValue value, SpecificEntropyUnit fromUnit) { return new SpecificEntropy(value, fromUnit); } @@ -482,10 +464,7 @@ public static SpecificEntropy Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static SpecificEntropy Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -513,11 +492,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out SpecificEntropy /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out SpecificEntropy result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -538,7 +513,7 @@ public static SpecificEntropyUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -549,7 +524,7 @@ public static SpecificEntropyUnit ParseUnit(string str, IFormatProvider? provide return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out SpecificEntropyUnit unit) { return TryParseUnit(str, null, out unit); @@ -564,7 +539,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out SpecificEntr /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out SpecificEntropyUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -583,35 +558,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static SpecificEntropy operator +(SpecificEntropy left, SpecificEntropy right) { - return new SpecificEntropy(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new SpecificEntropy(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static SpecificEntropy operator -(SpecificEntropy left, SpecificEntropy right) { - return new SpecificEntropy(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new SpecificEntropy(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -639,97 +614,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(SpecificEntropy left, SpecificEntropy right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(SpecificEntropy left, SpecificEntropy right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(SpecificEntropy left, SpecificEntropy right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(SpecificEntropy left, SpecificEntropy right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(SpecificEntropy other, SpecificEntropy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(SpecificEntropy left, SpecificEntropy right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(SpecificEntropy other, SpecificEntropy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(SpecificEntropy left, SpecificEntropy right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(SpecificEntropy other, SpecificEntropy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is SpecificEntropy otherQuantity)) + if (obj is not SpecificEntropy otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(SpecificEntropy other, SpecificEntropy tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(SpecificEntropy other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current SpecificEntropy. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(SpecificEntropy), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is SpecificEntropy otherQuantity)) throw new ArgumentException("Expected type SpecificEntropy.", nameof(obj)); + if (obj is not SpecificEntropy otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -741,162 +701,24 @@ public int CompareTo(object? obj) /// public int CompareTo(SpecificEntropy other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificEntropyUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this SpecificEntropy to another SpecificEntropy with the unit representation . - /// - /// The unit to convert to. - /// A SpecificEntropy with the specified unit. - public SpecificEntropy ToUnit(SpecificEntropyUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A SpecificEntropy with the specified unit. - public SpecificEntropy ToUnit(SpecificEntropyUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(SpecificEntropy), Unit, typeof(SpecificEntropy), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (SpecificEntropy)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(SpecificEntropyUnit unit, [NotNullWhen(true)] out SpecificEntropy? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - SpecificEntropy? convertedOrNull = (Unit, unit) switch - { - // SpecificEntropyUnit -> BaseUnit - (SpecificEntropyUnit.BtuPerPoundFahrenheit, SpecificEntropyUnit.JoulePerKilogramKelvin) => new SpecificEntropy(_value * 4.1868e3, SpecificEntropyUnit.JoulePerKilogramKelvin), - (SpecificEntropyUnit.CaloriePerGramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin) => new SpecificEntropy(_value * 4.184e3, SpecificEntropyUnit.JoulePerKilogramKelvin), - (SpecificEntropyUnit.JoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin) => new SpecificEntropy(_value, SpecificEntropyUnit.JoulePerKilogramKelvin), - (SpecificEntropyUnit.KilocaloriePerGramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin) => new SpecificEntropy((_value * 4.184e3) * 1e3d, SpecificEntropyUnit.JoulePerKilogramKelvin), - (SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin) => new SpecificEntropy((_value) * 1e3d, SpecificEntropyUnit.JoulePerKilogramKelvin), - (SpecificEntropyUnit.KilojoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin) => new SpecificEntropy((_value) * 1e3d, SpecificEntropyUnit.JoulePerKilogramKelvin), - (SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius, SpecificEntropyUnit.JoulePerKilogramKelvin) => new SpecificEntropy((_value) * 1e6d, SpecificEntropyUnit.JoulePerKilogramKelvin), - (SpecificEntropyUnit.MegajoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramKelvin) => new SpecificEntropy((_value) * 1e6d, SpecificEntropyUnit.JoulePerKilogramKelvin), - - // BaseUnit -> SpecificEntropyUnit - (SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.BtuPerPoundFahrenheit) => new SpecificEntropy(_value / 4.1868e3, SpecificEntropyUnit.BtuPerPoundFahrenheit), - (SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.CaloriePerGramKelvin) => new SpecificEntropy(_value / 4.184e3, SpecificEntropyUnit.CaloriePerGramKelvin), - (SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius) => new SpecificEntropy(_value, SpecificEntropyUnit.JoulePerKilogramDegreeCelsius), - (SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilocaloriePerGramKelvin) => new SpecificEntropy((_value / 4.184e3) / 1e3d, SpecificEntropyUnit.KilocaloriePerGramKelvin), - (SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius) => new SpecificEntropy((_value) / 1e3d, SpecificEntropyUnit.KilojoulePerKilogramDegreeCelsius), - (SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.KilojoulePerKilogramKelvin) => new SpecificEntropy((_value) / 1e3d, SpecificEntropyUnit.KilojoulePerKilogramKelvin), - (SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius) => new SpecificEntropy((_value) / 1e6d, SpecificEntropyUnit.MegajoulePerKilogramDegreeCelsius), - (SpecificEntropyUnit.JoulePerKilogramKelvin, SpecificEntropyUnit.MegajoulePerKilogramKelvin) => new SpecificEntropy((_value) / 1e6d, SpecificEntropyUnit.MegajoulePerKilogramKelvin), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public SpecificEntropy ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not SpecificEntropyUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificEntropyUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(SpecificEntropyUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(SpecificEntropyUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -911,7 +733,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs index 3deb82ea42..16e4c211fe 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificFuelConsumption.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Thrust-specific_fuel_consumption /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct SpecificFuelConsumption : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly SpecificFuelConsumptionUnit? _unit; /// @@ -104,7 +103,7 @@ public static SpecificFuelConsumptionInfo CreateDefault(Func - /// The for is [T][L^-1]. + /// The for is TL^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 0, 1, 0, 0, 0, 0); @@ -120,17 +119,21 @@ public static SpecificFuelConsumptionInfo CreateDefault(Func> GetDefaultMappings() { yield return new (SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, "GramPerKilonewtonSecond", "GramsPerKilonewtonSecond", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)); - yield return new (SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, "KilogramPerKilogramForceHour", "KilogramsPerKilogramForceHour", BaseUnits.Undefined); - yield return new (SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond, "KilogramPerKilonewtonSecond", "KilogramsPerKilonewtonSecond", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second)); - yield return new (SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, "PoundMassPerPoundForceHour", "PoundsMassPerPoundForceHour", BaseUnits.Undefined); + yield return new (SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, "KilogramPerKilogramForceHour", "KilogramsPerKilogramForceHour", BaseUnits.Undefined, + new QuantityValue(1765197, 50000000) + ); + yield return new (SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond, "KilogramPerKilonewtonSecond", "KilogramsPerKilonewtonSecond", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second), + new QuantityValue(1, 1000) + ); + yield return new (SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, "PoundMassPerPoundForceHour", "PoundsMassPerPoundForceHour", BaseUnits.Undefined, + new QuantityValue(1765197, 50000000) + ); } } static SpecificFuelConsumption() { - Info = SpecificFuelConsumptionInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(SpecificFuelConsumptionInfo.CreateDefault); } /// @@ -138,7 +141,7 @@ static SpecificFuelConsumption() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public SpecificFuelConsumption(double value, SpecificFuelConsumptionUnit unit) + public SpecificFuelConsumption(QuantityValue value, SpecificFuelConsumptionUnit unit) { _value = value; _unit = unit; @@ -152,7 +155,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -163,7 +166,8 @@ public SpecificFuelConsumption(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -192,10 +196,8 @@ public SpecificFuelConsumption(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public SpecificFuelConsumptionUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -234,49 +236,29 @@ public SpecificFuelConsumption(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramsPerKilonewtonSecond => As(SpecificFuelConsumptionUnit.GramPerKilonewtonSecond); + public QuantityValue GramsPerKilonewtonSecond => this.As(SpecificFuelConsumptionUnit.GramPerKilonewtonSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerKilogramForceHour => As(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour); + public QuantityValue KilogramsPerKilogramForceHour => this.As(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsPerKilonewtonSecond => As(SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond); + public QuantityValue KilogramsPerKilonewtonSecond => this.As(SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsMassPerPoundForceHour => As(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour); + public QuantityValue PoundsMassPerPoundForceHour => this.As(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: SpecificFuelConsumptionUnit -> BaseUnit - unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, quantity => quantity.ToUnit(SpecificFuelConsumptionUnit.GramPerKilonewtonSecond)); - unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond, SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, quantity => quantity.ToUnit(SpecificFuelConsumptionUnit.GramPerKilonewtonSecond)); - unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, quantity => quantity.ToUnit(SpecificFuelConsumptionUnit.GramPerKilonewtonSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> SpecificFuelConsumptionUnit - unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, quantity => quantity.ToUnit(SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour)); - unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond, quantity => quantity.ToUnit(SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond)); - unitConverter.SetConversionFunction(SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, quantity => quantity.ToUnit(SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour)); - } - /// /// Get unit abbreviation string. /// @@ -305,7 +287,7 @@ public static string GetAbbreviation(SpecificFuelConsumptionUnit unit, IFormatPr /// /// Creates a from . /// - public static SpecificFuelConsumption FromGramsPerKilonewtonSecond(double value) + public static SpecificFuelConsumption FromGramsPerKilonewtonSecond(QuantityValue value) { return new SpecificFuelConsumption(value, SpecificFuelConsumptionUnit.GramPerKilonewtonSecond); } @@ -313,7 +295,7 @@ public static SpecificFuelConsumption FromGramsPerKilonewtonSecond(double value) /// /// Creates a from . /// - public static SpecificFuelConsumption FromKilogramsPerKilogramForceHour(double value) + public static SpecificFuelConsumption FromKilogramsPerKilogramForceHour(QuantityValue value) { return new SpecificFuelConsumption(value, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour); } @@ -321,7 +303,7 @@ public static SpecificFuelConsumption FromKilogramsPerKilogramForceHour(double v /// /// Creates a from . /// - public static SpecificFuelConsumption FromKilogramsPerKilonewtonSecond(double value) + public static SpecificFuelConsumption FromKilogramsPerKilonewtonSecond(QuantityValue value) { return new SpecificFuelConsumption(value, SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond); } @@ -329,7 +311,7 @@ public static SpecificFuelConsumption FromKilogramsPerKilonewtonSecond(double va /// /// Creates a from . /// - public static SpecificFuelConsumption FromPoundsMassPerPoundForceHour(double value) + public static SpecificFuelConsumption FromPoundsMassPerPoundForceHour(QuantityValue value) { return new SpecificFuelConsumption(value, SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour); } @@ -340,7 +322,7 @@ public static SpecificFuelConsumption FromPoundsMassPerPoundForceHour(double val /// Value to convert from. /// Unit to convert from. /// SpecificFuelConsumption unit value. - public static SpecificFuelConsumption From(double value, SpecificFuelConsumptionUnit fromUnit) + public static SpecificFuelConsumption From(QuantityValue value, SpecificFuelConsumptionUnit fromUnit) { return new SpecificFuelConsumption(value, fromUnit); } @@ -401,10 +383,7 @@ public static SpecificFuelConsumption Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static SpecificFuelConsumption Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -432,11 +411,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out SpecificFuelCons /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out SpecificFuelConsumption result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -457,7 +432,7 @@ public static SpecificFuelConsumptionUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -468,7 +443,7 @@ public static SpecificFuelConsumptionUnit ParseUnit(string str, IFormatProvider? return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out SpecificFuelConsumptionUnit unit) { return TryParseUnit(str, null, out unit); @@ -483,7 +458,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out SpecificFuel /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out SpecificFuelConsumptionUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -502,35 +477,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static SpecificFuelConsumption operator +(SpecificFuelConsumption left, SpecificFuelConsumption right) { - return new SpecificFuelConsumption(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new SpecificFuelConsumption(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static SpecificFuelConsumption operator -(SpecificFuelConsumption left, SpecificFuelConsumption right) { - return new SpecificFuelConsumption(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new SpecificFuelConsumption(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -542,97 +517,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(SpecificFuelConsumption left, SpecificFuelConsumption right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(SpecificFuelConsumption left, SpecificFuelConsumption right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(SpecificFuelConsumption left, SpecificFuelConsumption right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(SpecificFuelConsumption left, SpecificFuelConsumption right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(SpecificFuelConsumption other, SpecificFuelConsumption tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(SpecificFuelConsumption left, SpecificFuelConsumption right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(SpecificFuelConsumption other, SpecificFuelConsumption tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(SpecificFuelConsumption left, SpecificFuelConsumption right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(SpecificFuelConsumption other, SpecificFuelConsumption tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is SpecificFuelConsumption otherQuantity)) + if (obj is not SpecificFuelConsumption otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(SpecificFuelConsumption other, SpecificFuelConsumption tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(SpecificFuelConsumption other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current SpecificFuelConsumption. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(SpecificFuelConsumption), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is SpecificFuelConsumption otherQuantity)) throw new ArgumentException("Expected type SpecificFuelConsumption.", nameof(obj)); + if (obj is not SpecificFuelConsumption otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -644,152 +604,24 @@ public int CompareTo(object? obj) /// public int CompareTo(SpecificFuelConsumption other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificFuelConsumptionUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this SpecificFuelConsumption to another SpecificFuelConsumption with the unit representation . - /// - /// The unit to convert to. - /// A SpecificFuelConsumption with the specified unit. - public SpecificFuelConsumption ToUnit(SpecificFuelConsumptionUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A SpecificFuelConsumption with the specified unit. - public SpecificFuelConsumption ToUnit(SpecificFuelConsumptionUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(SpecificFuelConsumption), Unit, typeof(SpecificFuelConsumption), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (SpecificFuelConsumption)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(SpecificFuelConsumptionUnit unit, [NotNullWhen(true)] out SpecificFuelConsumption? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - SpecificFuelConsumption? convertedOrNull = (Unit, unit) switch - { - // SpecificFuelConsumptionUnit -> BaseUnit - (SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour, SpecificFuelConsumptionUnit.GramPerKilonewtonSecond) => new SpecificFuelConsumption(_value * 1000 / (9.80665e-3 * 3600), SpecificFuelConsumptionUnit.GramPerKilonewtonSecond), - (SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond, SpecificFuelConsumptionUnit.GramPerKilonewtonSecond) => new SpecificFuelConsumption((_value) * 1e3d, SpecificFuelConsumptionUnit.GramPerKilonewtonSecond), - (SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour, SpecificFuelConsumptionUnit.GramPerKilonewtonSecond) => new SpecificFuelConsumption(_value * 1000 / (9.80665e-3 * 3600), SpecificFuelConsumptionUnit.GramPerKilonewtonSecond), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> SpecificFuelConsumptionUnit - (SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour) => new SpecificFuelConsumption(_value * 9.80665e-3 * 3600 / 1000, SpecificFuelConsumptionUnit.KilogramPerKilogramForceHour), - (SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond) => new SpecificFuelConsumption((_value) / 1e3d, SpecificFuelConsumptionUnit.KilogramPerKilonewtonSecond), - (SpecificFuelConsumptionUnit.GramPerKilonewtonSecond, SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour) => new SpecificFuelConsumption(_value * 9.80665e-3 * 3600 / 1000, SpecificFuelConsumptionUnit.PoundMassPerPoundForceHour), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public SpecificFuelConsumption ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not SpecificFuelConsumptionUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificFuelConsumptionUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is SpecificFuelConsumptionUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificFuelConsumptionUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(SpecificFuelConsumptionUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(SpecificFuelConsumptionUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -804,7 +636,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs index 3b3fbf3487..8cd3d6e9a7 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificVolume.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct SpecificVolume : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly SpecificVolumeUnit? _unit; /// @@ -104,7 +103,7 @@ public static SpecificVolumeInfo CreateDefault(Func - /// The for is [L^3][M^-1]. + /// The for is L^3M^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(3, -1, 0, 0, 0, 0, 0); @@ -119,17 +118,19 @@ public static SpecificVolumeInfo CreateDefault(FuncAn of representing the default unit mappings for SpecificVolume. public static IEnumerable> GetDefaultMappings() { - yield return new (SpecificVolumeUnit.CubicFootPerPound, "CubicFootPerPound", "CubicFeetPerPound", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound)); + yield return new (SpecificVolumeUnit.CubicFootPerPound, "CubicFootPerPound", "CubicFeetPerPound", new BaseUnits(length: LengthUnit.Foot, mass: MassUnit.Pound), + new QuantityValue(28349523125, 1769802912) + ); yield return new (SpecificVolumeUnit.CubicMeterPerKilogram, "CubicMeterPerKilogram", "CubicMetersPerKilogram", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram)); - yield return new (SpecificVolumeUnit.MillicubicMeterPerKilogram, "MillicubicMeterPerKilogram", "MillicubicMetersPerKilogram", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram)); + yield return new (SpecificVolumeUnit.MillicubicMeterPerKilogram, "MillicubicMeterPerKilogram", "MillicubicMetersPerKilogram", new BaseUnits(length: LengthUnit.Decimeter, mass: MassUnit.Kilogram), + 1000 + ); } } static SpecificVolume() { - Info = SpecificVolumeInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(SpecificVolumeInfo.CreateDefault); } /// @@ -137,7 +138,7 @@ static SpecificVolume() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public SpecificVolume(double value, SpecificVolumeUnit unit) + public SpecificVolume(QuantityValue value, SpecificVolumeUnit unit) { _value = value; _unit = unit; @@ -151,7 +152,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -162,7 +163,8 @@ public SpecificVolume(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -191,10 +193,8 @@ public SpecificVolume(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public SpecificVolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -233,42 +233,24 @@ public SpecificVolume(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicFeetPerPound => As(SpecificVolumeUnit.CubicFootPerPound); + public QuantityValue CubicFeetPerPound => this.As(SpecificVolumeUnit.CubicFootPerPound); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicMetersPerKilogram => As(SpecificVolumeUnit.CubicMeterPerKilogram); + public QuantityValue CubicMetersPerKilogram => this.As(SpecificVolumeUnit.CubicMeterPerKilogram); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillicubicMetersPerKilogram => As(SpecificVolumeUnit.MillicubicMeterPerKilogram); + public QuantityValue MillicubicMetersPerKilogram => this.As(SpecificVolumeUnit.MillicubicMeterPerKilogram); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: SpecificVolumeUnit -> BaseUnit - unitConverter.SetConversionFunction(SpecificVolumeUnit.CubicFootPerPound, SpecificVolumeUnit.CubicMeterPerKilogram, quantity => quantity.ToUnit(SpecificVolumeUnit.CubicMeterPerKilogram)); - unitConverter.SetConversionFunction(SpecificVolumeUnit.MillicubicMeterPerKilogram, SpecificVolumeUnit.CubicMeterPerKilogram, quantity => quantity.ToUnit(SpecificVolumeUnit.CubicMeterPerKilogram)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(SpecificVolumeUnit.CubicMeterPerKilogram, SpecificVolumeUnit.CubicMeterPerKilogram, quantity => quantity); - - // Register in unit converter: BaseUnit -> SpecificVolumeUnit - unitConverter.SetConversionFunction(SpecificVolumeUnit.CubicMeterPerKilogram, SpecificVolumeUnit.CubicFootPerPound, quantity => quantity.ToUnit(SpecificVolumeUnit.CubicFootPerPound)); - unitConverter.SetConversionFunction(SpecificVolumeUnit.CubicMeterPerKilogram, SpecificVolumeUnit.MillicubicMeterPerKilogram, quantity => quantity.ToUnit(SpecificVolumeUnit.MillicubicMeterPerKilogram)); - } - /// /// Get unit abbreviation string. /// @@ -297,7 +279,7 @@ public static string GetAbbreviation(SpecificVolumeUnit unit, IFormatProvider? p /// /// Creates a from . /// - public static SpecificVolume FromCubicFeetPerPound(double value) + public static SpecificVolume FromCubicFeetPerPound(QuantityValue value) { return new SpecificVolume(value, SpecificVolumeUnit.CubicFootPerPound); } @@ -305,7 +287,7 @@ public static SpecificVolume FromCubicFeetPerPound(double value) /// /// Creates a from . /// - public static SpecificVolume FromCubicMetersPerKilogram(double value) + public static SpecificVolume FromCubicMetersPerKilogram(QuantityValue value) { return new SpecificVolume(value, SpecificVolumeUnit.CubicMeterPerKilogram); } @@ -313,7 +295,7 @@ public static SpecificVolume FromCubicMetersPerKilogram(double value) /// /// Creates a from . /// - public static SpecificVolume FromMillicubicMetersPerKilogram(double value) + public static SpecificVolume FromMillicubicMetersPerKilogram(QuantityValue value) { return new SpecificVolume(value, SpecificVolumeUnit.MillicubicMeterPerKilogram); } @@ -324,7 +306,7 @@ public static SpecificVolume FromMillicubicMetersPerKilogram(double value) /// Value to convert from. /// Unit to convert from. /// SpecificVolume unit value. - public static SpecificVolume From(double value, SpecificVolumeUnit fromUnit) + public static SpecificVolume From(QuantityValue value, SpecificVolumeUnit fromUnit) { return new SpecificVolume(value, fromUnit); } @@ -385,10 +367,7 @@ public static SpecificVolume Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static SpecificVolume Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -416,11 +395,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out SpecificVolume r /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out SpecificVolume result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -441,7 +416,7 @@ public static SpecificVolumeUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -452,7 +427,7 @@ public static SpecificVolumeUnit ParseUnit(string str, IFormatProvider? provider return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out SpecificVolumeUnit unit) { return TryParseUnit(str, null, out unit); @@ -467,7 +442,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out SpecificVolu /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out SpecificVolumeUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -486,35 +461,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static SpecificVolume operator +(SpecificVolume left, SpecificVolume right) { - return new SpecificVolume(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new SpecificVolume(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static SpecificVolume operator -(SpecificVolume left, SpecificVolume right) { - return new SpecificVolume(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new SpecificVolume(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -527,7 +502,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// The corresponding inverse quantity, . public Density Inverse() { - return Density.FromKilogramsPerCubicMeter(1 / CubicMetersPerKilogram); + return UnitConverter.Default.ConvertTo(Value, Unit, Density.Info); } /// Get from * . @@ -543,97 +518,82 @@ public Density Inverse() /// Returns true if less or equal to. public static bool operator <=(SpecificVolume left, SpecificVolume right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(SpecificVolume left, SpecificVolume right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(SpecificVolume left, SpecificVolume right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(SpecificVolume left, SpecificVolume right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(SpecificVolume other, SpecificVolume tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(SpecificVolume left, SpecificVolume right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(SpecificVolume other, SpecificVolume tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(SpecificVolume left, SpecificVolume right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(SpecificVolume other, SpecificVolume tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is SpecificVolume otherQuantity)) + if (obj is not SpecificVolume otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(SpecificVolume other, SpecificVolume tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(SpecificVolume other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current SpecificVolume. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(SpecificVolume), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is SpecificVolume otherQuantity)) throw new ArgumentException("Expected type SpecificVolume.", nameof(obj)); + if (obj is not SpecificVolume otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -645,150 +605,24 @@ public int CompareTo(object? obj) /// public int CompareTo(SpecificVolume other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificVolumeUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this SpecificVolume to another SpecificVolume with the unit representation . - /// - /// The unit to convert to. - /// A SpecificVolume with the specified unit. - public SpecificVolume ToUnit(SpecificVolumeUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A SpecificVolume with the specified unit. - public SpecificVolume ToUnit(SpecificVolumeUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(SpecificVolume), Unit, typeof(SpecificVolume), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (SpecificVolume)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(SpecificVolumeUnit unit, [NotNullWhen(true)] out SpecificVolume? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - SpecificVolume? convertedOrNull = (Unit, unit) switch - { - // SpecificVolumeUnit -> BaseUnit - (SpecificVolumeUnit.CubicFootPerPound, SpecificVolumeUnit.CubicMeterPerKilogram) => new SpecificVolume(_value * 0.028316846592 / 0.45359237, SpecificVolumeUnit.CubicMeterPerKilogram), - (SpecificVolumeUnit.MillicubicMeterPerKilogram, SpecificVolumeUnit.CubicMeterPerKilogram) => new SpecificVolume((_value) * 1e-3d, SpecificVolumeUnit.CubicMeterPerKilogram), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> SpecificVolumeUnit - (SpecificVolumeUnit.CubicMeterPerKilogram, SpecificVolumeUnit.CubicFootPerPound) => new SpecificVolume(_value * 0.45359237 / 0.028316846592, SpecificVolumeUnit.CubicFootPerPound), - (SpecificVolumeUnit.CubicMeterPerKilogram, SpecificVolumeUnit.MillicubicMeterPerKilogram) => new SpecificVolume((_value) / 1e-3d, SpecificVolumeUnit.MillicubicMeterPerKilogram), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public SpecificVolume ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not SpecificVolumeUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificVolumeUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is SpecificVolumeUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificVolumeUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(SpecificVolumeUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(SpecificVolumeUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -803,7 +637,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs index 612dbcfcb3..cca2ada1f9 100644 --- a/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/SpecificWeight.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Specific_weight /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct SpecificWeight : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -59,13 +58,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly SpecificWeightUnit? _unit; /// @@ -110,7 +109,7 @@ public static SpecificWeightInfo CreateDefault(Func - /// The for is [T^-2][L^-2][M]. + /// The for is T^-2L^-2M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, 1, -2, 0, 0, 0, 0); @@ -125,31 +124,61 @@ public static SpecificWeightInfo CreateDefault(FuncAn of representing the default unit mappings for SpecificWeight. public static IEnumerable> GetDefaultMappings() { - yield return new (SpecificWeightUnit.KilogramForcePerCubicCentimeter, "KilogramForcePerCubicCentimeter", "KilogramsForcePerCubicCentimeter", BaseUnits.Undefined); - yield return new (SpecificWeightUnit.KilogramForcePerCubicMeter, "KilogramForcePerCubicMeter", "KilogramsForcePerCubicMeter", BaseUnits.Undefined); - yield return new (SpecificWeightUnit.KilogramForcePerCubicMillimeter, "KilogramForcePerCubicMillimeter", "KilogramsForcePerCubicMillimeter", BaseUnits.Undefined); - yield return new (SpecificWeightUnit.KilonewtonPerCubicCentimeter, "KilonewtonPerCubicCentimeter", "KilonewtonsPerCubicCentimeter", BaseUnits.Undefined); - yield return new (SpecificWeightUnit.KilonewtonPerCubicMeter, "KilonewtonPerCubicMeter", "KilonewtonsPerCubicMeter", BaseUnits.Undefined); - yield return new (SpecificWeightUnit.KilonewtonPerCubicMillimeter, "KilonewtonPerCubicMillimeter", "KilonewtonsPerCubicMillimeter", BaseUnits.Undefined); - yield return new (SpecificWeightUnit.KilopoundForcePerCubicFoot, "KilopoundForcePerCubicFoot", "KilopoundsForcePerCubicFoot", BaseUnits.Undefined); - yield return new (SpecificWeightUnit.KilopoundForcePerCubicInch, "KilopoundForcePerCubicInch", "KilopoundsForcePerCubicInch", BaseUnits.Undefined); - yield return new (SpecificWeightUnit.MeganewtonPerCubicMeter, "MeganewtonPerCubicMeter", "MeganewtonsPerCubicMeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (SpecificWeightUnit.NewtonPerCubicCentimeter, "NewtonPerCubicCentimeter", "NewtonsPerCubicCentimeter", BaseUnits.Undefined); + yield return new (SpecificWeightUnit.KilogramForcePerCubicCentimeter, "KilogramForcePerCubicCentimeter", "KilogramsForcePerCubicCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 9806650) + ); + yield return new (SpecificWeightUnit.KilogramForcePerCubicMeter, "KilogramForcePerCubicMeter", "KilogramsForcePerCubicMeter", BaseUnits.Undefined, + new QuantityValue(20000, 196133) + ); + yield return new (SpecificWeightUnit.KilogramForcePerCubicMillimeter, "KilogramForcePerCubicMillimeter", "KilogramsForcePerCubicMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 9806650000) + ); + yield return new (SpecificWeightUnit.KilonewtonPerCubicCentimeter, "KilonewtonPerCubicCentimeter", "KilonewtonsPerCubicCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 1000000000) + ); + yield return new (SpecificWeightUnit.KilonewtonPerCubicMeter, "KilonewtonPerCubicMeter", "KilonewtonsPerCubicMeter", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (SpecificWeightUnit.KilonewtonPerCubicMillimeter, "KilonewtonPerCubicMillimeter", "KilonewtonsPerCubicMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 1000000000000) + ); + yield return new (SpecificWeightUnit.KilopoundForcePerCubicFoot, "KilopoundForcePerCubicFoot", "KilopoundsForcePerCubicFoot", BaseUnits.Undefined, + new QuantityValue(7079211648, 1112055403815125) + ); + yield return new (SpecificWeightUnit.KilopoundForcePerCubicInch, "KilopoundForcePerCubicInch", "KilopoundsForcePerCubicInch", BaseUnits.Undefined, + new QuantityValue(4096766, 1112055403815125) + ); + yield return new (SpecificWeightUnit.MeganewtonPerCubicMeter, "MeganewtonPerCubicMeter", "MeganewtonsPerCubicMeter", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (SpecificWeightUnit.NewtonPerCubicCentimeter, "NewtonPerCubicCentimeter", "NewtonsPerCubicCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 1000000) + ); yield return new (SpecificWeightUnit.NewtonPerCubicMeter, "NewtonPerCubicMeter", "NewtonsPerCubicMeter", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (SpecificWeightUnit.NewtonPerCubicMillimeter, "NewtonPerCubicMillimeter", "NewtonsPerCubicMillimeter", BaseUnits.Undefined); - yield return new (SpecificWeightUnit.PoundForcePerCubicFoot, "PoundForcePerCubicFoot", "PoundsForcePerCubicFoot", BaseUnits.Undefined); - yield return new (SpecificWeightUnit.PoundForcePerCubicInch, "PoundForcePerCubicInch", "PoundsForcePerCubicInch", BaseUnits.Undefined); - yield return new (SpecificWeightUnit.TonneForcePerCubicCentimeter, "TonneForcePerCubicCentimeter", "TonnesForcePerCubicCentimeter", BaseUnits.Undefined); - yield return new (SpecificWeightUnit.TonneForcePerCubicMeter, "TonneForcePerCubicMeter", "TonnesForcePerCubicMeter", BaseUnits.Undefined); - yield return new (SpecificWeightUnit.TonneForcePerCubicMillimeter, "TonneForcePerCubicMillimeter", "TonnesForcePerCubicMillimeter", BaseUnits.Undefined); + yield return new (SpecificWeightUnit.NewtonPerCubicMillimeter, "NewtonPerCubicMillimeter", "NewtonsPerCubicMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 1000000000) + ); + yield return new (SpecificWeightUnit.PoundForcePerCubicFoot, "PoundForcePerCubicFoot", "PoundsForcePerCubicFoot", BaseUnits.Undefined, + new QuantityValue(56633693184, 8896443230521) + ); + yield return new (SpecificWeightUnit.PoundForcePerCubicInch, "PoundForcePerCubicInch", "PoundsForcePerCubicInch", BaseUnits.Undefined, + new QuantityValue(32774128, 8896443230521) + ); + yield return new (SpecificWeightUnit.TonneForcePerCubicCentimeter, "TonneForcePerCubicCentimeter", "TonnesForcePerCubicCentimeter", BaseUnits.Undefined, + new QuantityValue(1, 9806650000) + ); + yield return new (SpecificWeightUnit.TonneForcePerCubicMeter, "TonneForcePerCubicMeter", "TonnesForcePerCubicMeter", BaseUnits.Undefined, + new QuantityValue(20, 196133) + ); + yield return new (SpecificWeightUnit.TonneForcePerCubicMillimeter, "TonneForcePerCubicMillimeter", "TonnesForcePerCubicMillimeter", BaseUnits.Undefined, + new QuantityValue(1, 9806650000000) + ); } } static SpecificWeight() { - Info = SpecificWeightInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(SpecificWeightInfo.CreateDefault); } /// @@ -157,7 +186,7 @@ static SpecificWeight() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public SpecificWeight(double value, SpecificWeightUnit unit) + public SpecificWeight(QuantityValue value, SpecificWeightUnit unit) { _value = value; _unit = unit; @@ -171,7 +200,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -182,7 +211,8 @@ public SpecificWeight(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -211,10 +241,8 @@ public SpecificWeight(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public SpecificWeightUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -253,140 +281,94 @@ public SpecificWeight(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsForcePerCubicCentimeter => As(SpecificWeightUnit.KilogramForcePerCubicCentimeter); + public QuantityValue KilogramsForcePerCubicCentimeter => this.As(SpecificWeightUnit.KilogramForcePerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsForcePerCubicMeter => As(SpecificWeightUnit.KilogramForcePerCubicMeter); + public QuantityValue KilogramsForcePerCubicMeter => this.As(SpecificWeightUnit.KilogramForcePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramsForcePerCubicMillimeter => As(SpecificWeightUnit.KilogramForcePerCubicMillimeter); + public QuantityValue KilogramsForcePerCubicMillimeter => this.As(SpecificWeightUnit.KilogramForcePerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonsPerCubicCentimeter => As(SpecificWeightUnit.KilonewtonPerCubicCentimeter); + public QuantityValue KilonewtonsPerCubicCentimeter => this.As(SpecificWeightUnit.KilonewtonPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonsPerCubicMeter => As(SpecificWeightUnit.KilonewtonPerCubicMeter); + public QuantityValue KilonewtonsPerCubicMeter => this.As(SpecificWeightUnit.KilonewtonPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonsPerCubicMillimeter => As(SpecificWeightUnit.KilonewtonPerCubicMillimeter); + public QuantityValue KilonewtonsPerCubicMillimeter => this.As(SpecificWeightUnit.KilonewtonPerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsForcePerCubicFoot => As(SpecificWeightUnit.KilopoundForcePerCubicFoot); + public QuantityValue KilopoundsForcePerCubicFoot => this.As(SpecificWeightUnit.KilopoundForcePerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundsForcePerCubicInch => As(SpecificWeightUnit.KilopoundForcePerCubicInch); + public QuantityValue KilopoundsForcePerCubicInch => this.As(SpecificWeightUnit.KilopoundForcePerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MeganewtonsPerCubicMeter => As(SpecificWeightUnit.MeganewtonPerCubicMeter); + public QuantityValue MeganewtonsPerCubicMeter => this.As(SpecificWeightUnit.MeganewtonPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonsPerCubicCentimeter => As(SpecificWeightUnit.NewtonPerCubicCentimeter); + public QuantityValue NewtonsPerCubicCentimeter => this.As(SpecificWeightUnit.NewtonPerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonsPerCubicMeter => As(SpecificWeightUnit.NewtonPerCubicMeter); + public QuantityValue NewtonsPerCubicMeter => this.As(SpecificWeightUnit.NewtonPerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonsPerCubicMillimeter => As(SpecificWeightUnit.NewtonPerCubicMillimeter); + public QuantityValue NewtonsPerCubicMillimeter => this.As(SpecificWeightUnit.NewtonPerCubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsForcePerCubicFoot => As(SpecificWeightUnit.PoundForcePerCubicFoot); + public QuantityValue PoundsForcePerCubicFoot => this.As(SpecificWeightUnit.PoundForcePerCubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundsForcePerCubicInch => As(SpecificWeightUnit.PoundForcePerCubicInch); + public QuantityValue PoundsForcePerCubicInch => this.As(SpecificWeightUnit.PoundForcePerCubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesForcePerCubicCentimeter => As(SpecificWeightUnit.TonneForcePerCubicCentimeter); + public QuantityValue TonnesForcePerCubicCentimeter => this.As(SpecificWeightUnit.TonneForcePerCubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesForcePerCubicMeter => As(SpecificWeightUnit.TonneForcePerCubicMeter); + public QuantityValue TonnesForcePerCubicMeter => this.As(SpecificWeightUnit.TonneForcePerCubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonnesForcePerCubicMillimeter => As(SpecificWeightUnit.TonneForcePerCubicMillimeter); + public QuantityValue TonnesForcePerCubicMillimeter => this.As(SpecificWeightUnit.TonneForcePerCubicMillimeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: SpecificWeightUnit -> BaseUnit - unitConverter.SetConversionFunction(SpecificWeightUnit.KilogramForcePerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.KilogramForcePerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.KilogramForcePerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.KilonewtonPerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.KilonewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.KilonewtonPerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.KilopoundForcePerCubicFoot, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.KilopoundForcePerCubicInch, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.MeganewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.PoundForcePerCubicFoot, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.PoundForcePerCubicInch, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.TonneForcePerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.TonneForcePerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.TonneForcePerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> SpecificWeightUnit - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicCentimeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilogramForcePerCubicCentimeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilogramForcePerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicMillimeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilogramForcePerCubicMillimeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicCentimeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilonewtonPerCubicCentimeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilonewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicMillimeter, quantity => quantity.ToUnit(SpecificWeightUnit.KilonewtonPerCubicMillimeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilopoundForcePerCubicFoot, quantity => quantity.ToUnit(SpecificWeightUnit.KilopoundForcePerCubicFoot)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilopoundForcePerCubicInch, quantity => quantity.ToUnit(SpecificWeightUnit.KilopoundForcePerCubicInch)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.MeganewtonPerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.MeganewtonPerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicCentimeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicCentimeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMillimeter, quantity => quantity.ToUnit(SpecificWeightUnit.NewtonPerCubicMillimeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.PoundForcePerCubicFoot, quantity => quantity.ToUnit(SpecificWeightUnit.PoundForcePerCubicFoot)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.PoundForcePerCubicInch, quantity => quantity.ToUnit(SpecificWeightUnit.PoundForcePerCubicInch)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicCentimeter, quantity => quantity.ToUnit(SpecificWeightUnit.TonneForcePerCubicCentimeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicMeter, quantity => quantity.ToUnit(SpecificWeightUnit.TonneForcePerCubicMeter)); - unitConverter.SetConversionFunction(SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicMillimeter, quantity => quantity.ToUnit(SpecificWeightUnit.TonneForcePerCubicMillimeter)); - } - /// /// Get unit abbreviation string. /// @@ -415,7 +397,7 @@ public static string GetAbbreviation(SpecificWeightUnit unit, IFormatProvider? p /// /// Creates a from . /// - public static SpecificWeight FromKilogramsForcePerCubicCentimeter(double value) + public static SpecificWeight FromKilogramsForcePerCubicCentimeter(QuantityValue value) { return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicCentimeter); } @@ -423,7 +405,7 @@ public static SpecificWeight FromKilogramsForcePerCubicCentimeter(double value) /// /// Creates a from . /// - public static SpecificWeight FromKilogramsForcePerCubicMeter(double value) + public static SpecificWeight FromKilogramsForcePerCubicMeter(QuantityValue value) { return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMeter); } @@ -431,7 +413,7 @@ public static SpecificWeight FromKilogramsForcePerCubicMeter(double value) /// /// Creates a from . /// - public static SpecificWeight FromKilogramsForcePerCubicMillimeter(double value) + public static SpecificWeight FromKilogramsForcePerCubicMillimeter(QuantityValue value) { return new SpecificWeight(value, SpecificWeightUnit.KilogramForcePerCubicMillimeter); } @@ -439,7 +421,7 @@ public static SpecificWeight FromKilogramsForcePerCubicMillimeter(double value) /// /// Creates a from . /// - public static SpecificWeight FromKilonewtonsPerCubicCentimeter(double value) + public static SpecificWeight FromKilonewtonsPerCubicCentimeter(QuantityValue value) { return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicCentimeter); } @@ -447,7 +429,7 @@ public static SpecificWeight FromKilonewtonsPerCubicCentimeter(double value) /// /// Creates a from . /// - public static SpecificWeight FromKilonewtonsPerCubicMeter(double value) + public static SpecificWeight FromKilonewtonsPerCubicMeter(QuantityValue value) { return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMeter); } @@ -455,7 +437,7 @@ public static SpecificWeight FromKilonewtonsPerCubicMeter(double value) /// /// Creates a from . /// - public static SpecificWeight FromKilonewtonsPerCubicMillimeter(double value) + public static SpecificWeight FromKilonewtonsPerCubicMillimeter(QuantityValue value) { return new SpecificWeight(value, SpecificWeightUnit.KilonewtonPerCubicMillimeter); } @@ -463,7 +445,7 @@ public static SpecificWeight FromKilonewtonsPerCubicMillimeter(double value) /// /// Creates a from . /// - public static SpecificWeight FromKilopoundsForcePerCubicFoot(double value) + public static SpecificWeight FromKilopoundsForcePerCubicFoot(QuantityValue value) { return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicFoot); } @@ -471,7 +453,7 @@ public static SpecificWeight FromKilopoundsForcePerCubicFoot(double value) /// /// Creates a from . /// - public static SpecificWeight FromKilopoundsForcePerCubicInch(double value) + public static SpecificWeight FromKilopoundsForcePerCubicInch(QuantityValue value) { return new SpecificWeight(value, SpecificWeightUnit.KilopoundForcePerCubicInch); } @@ -479,7 +461,7 @@ public static SpecificWeight FromKilopoundsForcePerCubicInch(double value) /// /// Creates a from . /// - public static SpecificWeight FromMeganewtonsPerCubicMeter(double value) + public static SpecificWeight FromMeganewtonsPerCubicMeter(QuantityValue value) { return new SpecificWeight(value, SpecificWeightUnit.MeganewtonPerCubicMeter); } @@ -487,7 +469,7 @@ public static SpecificWeight FromMeganewtonsPerCubicMeter(double value) /// /// Creates a from . /// - public static SpecificWeight FromNewtonsPerCubicCentimeter(double value) + public static SpecificWeight FromNewtonsPerCubicCentimeter(QuantityValue value) { return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicCentimeter); } @@ -495,7 +477,7 @@ public static SpecificWeight FromNewtonsPerCubicCentimeter(double value) /// /// Creates a from . /// - public static SpecificWeight FromNewtonsPerCubicMeter(double value) + public static SpecificWeight FromNewtonsPerCubicMeter(QuantityValue value) { return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMeter); } @@ -503,7 +485,7 @@ public static SpecificWeight FromNewtonsPerCubicMeter(double value) /// /// Creates a from . /// - public static SpecificWeight FromNewtonsPerCubicMillimeter(double value) + public static SpecificWeight FromNewtonsPerCubicMillimeter(QuantityValue value) { return new SpecificWeight(value, SpecificWeightUnit.NewtonPerCubicMillimeter); } @@ -511,7 +493,7 @@ public static SpecificWeight FromNewtonsPerCubicMillimeter(double value) /// /// Creates a from . /// - public static SpecificWeight FromPoundsForcePerCubicFoot(double value) + public static SpecificWeight FromPoundsForcePerCubicFoot(QuantityValue value) { return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicFoot); } @@ -519,7 +501,7 @@ public static SpecificWeight FromPoundsForcePerCubicFoot(double value) /// /// Creates a from . /// - public static SpecificWeight FromPoundsForcePerCubicInch(double value) + public static SpecificWeight FromPoundsForcePerCubicInch(QuantityValue value) { return new SpecificWeight(value, SpecificWeightUnit.PoundForcePerCubicInch); } @@ -527,7 +509,7 @@ public static SpecificWeight FromPoundsForcePerCubicInch(double value) /// /// Creates a from . /// - public static SpecificWeight FromTonnesForcePerCubicCentimeter(double value) + public static SpecificWeight FromTonnesForcePerCubicCentimeter(QuantityValue value) { return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicCentimeter); } @@ -535,7 +517,7 @@ public static SpecificWeight FromTonnesForcePerCubicCentimeter(double value) /// /// Creates a from . /// - public static SpecificWeight FromTonnesForcePerCubicMeter(double value) + public static SpecificWeight FromTonnesForcePerCubicMeter(QuantityValue value) { return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMeter); } @@ -543,7 +525,7 @@ public static SpecificWeight FromTonnesForcePerCubicMeter(double value) /// /// Creates a from . /// - public static SpecificWeight FromTonnesForcePerCubicMillimeter(double value) + public static SpecificWeight FromTonnesForcePerCubicMillimeter(QuantityValue value) { return new SpecificWeight(value, SpecificWeightUnit.TonneForcePerCubicMillimeter); } @@ -554,7 +536,7 @@ public static SpecificWeight FromTonnesForcePerCubicMillimeter(double value) /// Value to convert from. /// Unit to convert from. /// SpecificWeight unit value. - public static SpecificWeight From(double value, SpecificWeightUnit fromUnit) + public static SpecificWeight From(QuantityValue value, SpecificWeightUnit fromUnit) { return new SpecificWeight(value, fromUnit); } @@ -615,10 +597,7 @@ public static SpecificWeight Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static SpecificWeight Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -646,11 +625,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out SpecificWeight r /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out SpecificWeight result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -671,7 +646,7 @@ public static SpecificWeightUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -682,7 +657,7 @@ public static SpecificWeightUnit ParseUnit(string str, IFormatProvider? provider return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out SpecificWeightUnit unit) { return TryParseUnit(str, null, out unit); @@ -697,7 +672,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out SpecificWeig /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out SpecificWeightUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -716,35 +691,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static SpecificWeight operator +(SpecificWeight left, SpecificWeight right) { - return new SpecificWeight(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new SpecificWeight(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static SpecificWeight operator -(SpecificWeight left, SpecificWeight right) { - return new SpecificWeight(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new SpecificWeight(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -784,97 +759,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(SpecificWeight left, SpecificWeight right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(SpecificWeight left, SpecificWeight right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(SpecificWeight left, SpecificWeight right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(SpecificWeight left, SpecificWeight right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(SpecificWeight other, SpecificWeight tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(SpecificWeight left, SpecificWeight right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(SpecificWeight other, SpecificWeight tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(SpecificWeight left, SpecificWeight right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(SpecificWeight other, SpecificWeight tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is SpecificWeight otherQuantity)) + if (obj is not SpecificWeight otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(SpecificWeight other, SpecificWeight tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(SpecificWeight other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current SpecificWeight. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(SpecificWeight), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is SpecificWeight otherQuantity)) throw new ArgumentException("Expected type SpecificWeight.", nameof(obj)); + if (obj is not SpecificWeight otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -886,178 +846,24 @@ public int CompareTo(object? obj) /// public int CompareTo(SpecificWeight other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpecificWeightUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this SpecificWeight to another SpecificWeight with the unit representation . - /// - /// The unit to convert to. - /// A SpecificWeight with the specified unit. - public SpecificWeight ToUnit(SpecificWeightUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A SpecificWeight with the specified unit. - public SpecificWeight ToUnit(SpecificWeightUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(SpecificWeight), Unit, typeof(SpecificWeight), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (SpecificWeight)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(SpecificWeightUnit unit, [NotNullWhen(true)] out SpecificWeight? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - SpecificWeight? convertedOrNull = (Unit, unit) switch - { - // SpecificWeightUnit -> BaseUnit - (SpecificWeightUnit.KilogramForcePerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 9.80665e6, SpecificWeightUnit.NewtonPerCubicMeter), - (SpecificWeightUnit.KilogramForcePerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 9.80665, SpecificWeightUnit.NewtonPerCubicMeter), - (SpecificWeightUnit.KilogramForcePerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 9.80665e9, SpecificWeightUnit.NewtonPerCubicMeter), - (SpecificWeightUnit.KilonewtonPerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight((_value * 1000000) * 1e3d, SpecificWeightUnit.NewtonPerCubicMeter), - (SpecificWeightUnit.KilonewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight((_value) * 1e3d, SpecificWeightUnit.NewtonPerCubicMeter), - (SpecificWeightUnit.KilonewtonPerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight((_value * 1000000000) * 1e3d, SpecificWeightUnit.NewtonPerCubicMeter), - (SpecificWeightUnit.KilopoundForcePerCubicFoot, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight((_value * 4.4482216152605 / 0.028316846592) * 1e3d, SpecificWeightUnit.NewtonPerCubicMeter), - (SpecificWeightUnit.KilopoundForcePerCubicInch, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight((_value * 4.4482216152605 / 1.6387064e-5) * 1e3d, SpecificWeightUnit.NewtonPerCubicMeter), - (SpecificWeightUnit.MeganewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight((_value) * 1e6d, SpecificWeightUnit.NewtonPerCubicMeter), - (SpecificWeightUnit.NewtonPerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 1000000, SpecificWeightUnit.NewtonPerCubicMeter), - (SpecificWeightUnit.NewtonPerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 1000000000, SpecificWeightUnit.NewtonPerCubicMeter), - (SpecificWeightUnit.PoundForcePerCubicFoot, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 4.4482216152605 / 0.028316846592, SpecificWeightUnit.NewtonPerCubicMeter), - (SpecificWeightUnit.PoundForcePerCubicInch, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 4.4482216152605 / 1.6387064e-5, SpecificWeightUnit.NewtonPerCubicMeter), - (SpecificWeightUnit.TonneForcePerCubicCentimeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 9.80665e9, SpecificWeightUnit.NewtonPerCubicMeter), - (SpecificWeightUnit.TonneForcePerCubicMeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 9.80665e3, SpecificWeightUnit.NewtonPerCubicMeter), - (SpecificWeightUnit.TonneForcePerCubicMillimeter, SpecificWeightUnit.NewtonPerCubicMeter) => new SpecificWeight(_value * 9.80665e12, SpecificWeightUnit.NewtonPerCubicMeter), - - // BaseUnit -> SpecificWeightUnit - (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicCentimeter) => new SpecificWeight(_value / 9.80665e6, SpecificWeightUnit.KilogramForcePerCubicCentimeter), - (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicMeter) => new SpecificWeight(_value / 9.80665, SpecificWeightUnit.KilogramForcePerCubicMeter), - (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilogramForcePerCubicMillimeter) => new SpecificWeight(_value / 9.80665e9, SpecificWeightUnit.KilogramForcePerCubicMillimeter), - (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicCentimeter) => new SpecificWeight((_value * 0.000001) / 1e3d, SpecificWeightUnit.KilonewtonPerCubicCentimeter), - (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicMeter) => new SpecificWeight((_value) / 1e3d, SpecificWeightUnit.KilonewtonPerCubicMeter), - (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilonewtonPerCubicMillimeter) => new SpecificWeight((_value * 0.000000001) / 1e3d, SpecificWeightUnit.KilonewtonPerCubicMillimeter), - (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilopoundForcePerCubicFoot) => new SpecificWeight((_value * 0.028316846592 / 4.4482216152605) / 1e3d, SpecificWeightUnit.KilopoundForcePerCubicFoot), - (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.KilopoundForcePerCubicInch) => new SpecificWeight((_value * 1.6387064e-5 / 4.4482216152605) / 1e3d, SpecificWeightUnit.KilopoundForcePerCubicInch), - (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.MeganewtonPerCubicMeter) => new SpecificWeight((_value) / 1e6d, SpecificWeightUnit.MeganewtonPerCubicMeter), - (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicCentimeter) => new SpecificWeight(_value * 0.000001, SpecificWeightUnit.NewtonPerCubicCentimeter), - (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.NewtonPerCubicMillimeter) => new SpecificWeight(_value * 0.000000001, SpecificWeightUnit.NewtonPerCubicMillimeter), - (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.PoundForcePerCubicFoot) => new SpecificWeight(_value * 0.028316846592 / 4.4482216152605, SpecificWeightUnit.PoundForcePerCubicFoot), - (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.PoundForcePerCubicInch) => new SpecificWeight(_value * 1.6387064e-5 / 4.4482216152605, SpecificWeightUnit.PoundForcePerCubicInch), - (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicCentimeter) => new SpecificWeight(_value / 9.80665e9, SpecificWeightUnit.TonneForcePerCubicCentimeter), - (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicMeter) => new SpecificWeight(_value / 9.80665e3, SpecificWeightUnit.TonneForcePerCubicMeter), - (SpecificWeightUnit.NewtonPerCubicMeter, SpecificWeightUnit.TonneForcePerCubicMillimeter) => new SpecificWeight(_value / 9.80665e12, SpecificWeightUnit.TonneForcePerCubicMillimeter), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public SpecificWeight ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not SpecificWeightUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpecificWeightUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(SpecificWeightUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(SpecificWeightUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1072,7 +878,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Speed.g.cs b/UnitsNet/GeneratedCode/Quantities/Speed.g.cs index 6e46faf02b..403b6ce661 100644 --- a/UnitsNet/GeneratedCode/Quantities/Speed.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Speed.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Speed : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -60,13 +59,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly SpeedUnit? _unit; /// @@ -111,7 +110,7 @@ public static SpeedInfo CreateDefault(Func } /// - /// The for is [T^-1][L]. + /// The for is T^-1L. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 0, -1, 0, 0, 0, 0); @@ -126,47 +125,109 @@ public static SpeedInfo CreateDefault(Func /// An of representing the default unit mappings for Speed. public static IEnumerable> GetDefaultMappings() { - yield return new (SpeedUnit.CentimeterPerHour, "CentimeterPerHour", "CentimetersPerHour", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Hour)); - yield return new (SpeedUnit.CentimeterPerMinute, "CentimeterPerMinute", "CentimetersPerMinute", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Minute)); - yield return new (SpeedUnit.CentimeterPerSecond, "CentimeterPerSecond", "CentimetersPerSecond", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Second)); - yield return new (SpeedUnit.DecimeterPerMinute, "DecimeterPerMinute", "DecimetersPerMinute", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Minute)); - yield return new (SpeedUnit.DecimeterPerSecond, "DecimeterPerSecond", "DecimetersPerSecond", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Second)); - yield return new (SpeedUnit.FootPerHour, "FootPerHour", "FeetPerHour", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Hour)); - yield return new (SpeedUnit.FootPerMinute, "FootPerMinute", "FeetPerMinute", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Minute)); - yield return new (SpeedUnit.FootPerSecond, "FootPerSecond", "FeetPerSecond", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second)); - yield return new (SpeedUnit.InchPerHour, "InchPerHour", "InchesPerHour", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Hour)); - yield return new (SpeedUnit.InchPerMinute, "InchPerMinute", "InchesPerMinute", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Minute)); - yield return new (SpeedUnit.InchPerSecond, "InchPerSecond", "InchesPerSecond", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Second)); - yield return new (SpeedUnit.KilometerPerHour, "KilometerPerHour", "KilometersPerHour", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Hour)); - yield return new (SpeedUnit.KilometerPerMinute, "KilometerPerMinute", "KilometersPerMinute", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Minute)); - yield return new (SpeedUnit.KilometerPerSecond, "KilometerPerSecond", "KilometersPerSecond", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second)); - yield return new (SpeedUnit.Knot, "Knot", "Knots", new BaseUnits(length: LengthUnit.NauticalMile, time: DurationUnit.Hour)); - yield return new (SpeedUnit.Mach, "Mach", "Mach", BaseUnits.Undefined); - yield return new (SpeedUnit.MeterPerHour, "MeterPerHour", "MetersPerHour", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Hour)); - yield return new (SpeedUnit.MeterPerMinute, "MeterPerMinute", "MetersPerMinute", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Minute)); + yield return new (SpeedUnit.CentimeterPerHour, "CentimeterPerHour", "CentimetersPerHour", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Hour), + 360000 + ); + yield return new (SpeedUnit.CentimeterPerMinute, "CentimeterPerMinute", "CentimetersPerMinute", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Minute), + 6000 + ); + yield return new (SpeedUnit.CentimeterPerSecond, "CentimeterPerSecond", "CentimetersPerSecond", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Second), + 100 + ); + yield return new (SpeedUnit.DecimeterPerMinute, "DecimeterPerMinute", "DecimetersPerMinute", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Minute), + 600 + ); + yield return new (SpeedUnit.DecimeterPerSecond, "DecimeterPerSecond", "DecimetersPerSecond", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Second), + 10 + ); + yield return new (SpeedUnit.FootPerHour, "FootPerHour", "FeetPerHour", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Hour), + new QuantityValue(1500000, 127) + ); + yield return new (SpeedUnit.FootPerMinute, "FootPerMinute", "FeetPerMinute", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Minute), + new QuantityValue(25000, 127) + ); + yield return new (SpeedUnit.FootPerSecond, "FootPerSecond", "FeetPerSecond", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second), + new QuantityValue(1250, 381) + ); + yield return new (SpeedUnit.InchPerHour, "InchPerHour", "InchesPerHour", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Hour), + new QuantityValue(18000000, 127) + ); + yield return new (SpeedUnit.InchPerMinute, "InchPerMinute", "InchesPerMinute", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Minute), + new QuantityValue(300000, 127) + ); + yield return new (SpeedUnit.InchPerSecond, "InchPerSecond", "InchesPerSecond", new BaseUnits(length: LengthUnit.Inch, time: DurationUnit.Second), + new QuantityValue(5000, 127) + ); + yield return new (SpeedUnit.KilometerPerHour, "KilometerPerHour", "KilometersPerHour", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Hour), + new QuantityValue(18, 5) + ); + yield return new (SpeedUnit.KilometerPerMinute, "KilometerPerMinute", "KilometersPerMinute", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Minute), + new QuantityValue(3, 50) + ); + yield return new (SpeedUnit.KilometerPerSecond, "KilometerPerSecond", "KilometersPerSecond", new BaseUnits(length: LengthUnit.Kilometer, time: DurationUnit.Second), + new QuantityValue(1, 1000) + ); + yield return new (SpeedUnit.Knot, "Knot", "Knots", new BaseUnits(length: LengthUnit.NauticalMile, time: DurationUnit.Hour), + new QuantityValue(900, 463) + ); + yield return new (SpeedUnit.Mach, "Mach", "Mach", BaseUnits.Undefined, + new QuantityValue(100, 34029) + ); + yield return new (SpeedUnit.MeterPerHour, "MeterPerHour", "MetersPerHour", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Hour), + 3600 + ); + yield return new (SpeedUnit.MeterPerMinute, "MeterPerMinute", "MetersPerMinute", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Minute), + 60 + ); yield return new (SpeedUnit.MeterPerSecond, "MeterPerSecond", "MetersPerSecond", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)); - yield return new (SpeedUnit.MicrometerPerMinute, "MicrometerPerMinute", "MicrometersPerMinute", new BaseUnits(length: LengthUnit.Micrometer, time: DurationUnit.Minute)); - yield return new (SpeedUnit.MicrometerPerSecond, "MicrometerPerSecond", "MicrometersPerSecond", new BaseUnits(length: LengthUnit.Micrometer, time: DurationUnit.Second)); - yield return new (SpeedUnit.MilePerHour, "MilePerHour", "MilesPerHour", new BaseUnits(length: LengthUnit.Mile, time: DurationUnit.Hour)); - yield return new (SpeedUnit.MillimeterPerHour, "MillimeterPerHour", "MillimetersPerHour", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Hour)); - yield return new (SpeedUnit.MillimeterPerMinute, "MillimeterPerMinute", "MillimetersPerMinute", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Minute)); - yield return new (SpeedUnit.MillimeterPerSecond, "MillimeterPerSecond", "MillimetersPerSecond", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second)); - yield return new (SpeedUnit.NanometerPerMinute, "NanometerPerMinute", "NanometersPerMinute", new BaseUnits(length: LengthUnit.Nanometer, time: DurationUnit.Minute)); - yield return new (SpeedUnit.NanometerPerSecond, "NanometerPerSecond", "NanometersPerSecond", new BaseUnits(length: LengthUnit.Nanometer, time: DurationUnit.Second)); - yield return new (SpeedUnit.UsSurveyFootPerHour, "UsSurveyFootPerHour", "UsSurveyFeetPerHour", new BaseUnits(length: LengthUnit.UsSurveyFoot, time: DurationUnit.Hour)); - yield return new (SpeedUnit.UsSurveyFootPerMinute, "UsSurveyFootPerMinute", "UsSurveyFeetPerMinute", new BaseUnits(length: LengthUnit.UsSurveyFoot, time: DurationUnit.Minute)); - yield return new (SpeedUnit.UsSurveyFootPerSecond, "UsSurveyFootPerSecond", "UsSurveyFeetPerSecond", new BaseUnits(length: LengthUnit.UsSurveyFoot, time: DurationUnit.Second)); - yield return new (SpeedUnit.YardPerHour, "YardPerHour", "YardsPerHour", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Hour)); - yield return new (SpeedUnit.YardPerMinute, "YardPerMinute", "YardsPerMinute", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Minute)); - yield return new (SpeedUnit.YardPerSecond, "YardPerSecond", "YardsPerSecond", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Second)); + yield return new (SpeedUnit.MicrometerPerMinute, "MicrometerPerMinute", "MicrometersPerMinute", new BaseUnits(length: LengthUnit.Micrometer, time: DurationUnit.Minute), + 60000000 + ); + yield return new (SpeedUnit.MicrometerPerSecond, "MicrometerPerSecond", "MicrometersPerSecond", new BaseUnits(length: LengthUnit.Micrometer, time: DurationUnit.Second), + 1000000 + ); + yield return new (SpeedUnit.MilePerHour, "MilePerHour", "MilesPerHour", new BaseUnits(length: LengthUnit.Mile, time: DurationUnit.Hour), + new QuantityValue(3125, 1397) + ); + yield return new (SpeedUnit.MillimeterPerHour, "MillimeterPerHour", "MillimetersPerHour", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Hour), + 3600000 + ); + yield return new (SpeedUnit.MillimeterPerMinute, "MillimeterPerMinute", "MillimetersPerMinute", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Minute), + 60000 + ); + yield return new (SpeedUnit.MillimeterPerSecond, "MillimeterPerSecond", "MillimetersPerSecond", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second), + 1000 + ); + yield return new (SpeedUnit.NanometerPerMinute, "NanometerPerMinute", "NanometersPerMinute", new BaseUnits(length: LengthUnit.Nanometer, time: DurationUnit.Minute), + 60000000000 + ); + yield return new (SpeedUnit.NanometerPerSecond, "NanometerPerSecond", "NanometersPerSecond", new BaseUnits(length: LengthUnit.Nanometer, time: DurationUnit.Second), + 1000000000 + ); + yield return new (SpeedUnit.UsSurveyFootPerHour, "UsSurveyFootPerHour", "UsSurveyFeetPerHour", new BaseUnits(length: LengthUnit.UsSurveyFoot, time: DurationUnit.Hour), + 11811 + ); + yield return new (SpeedUnit.UsSurveyFootPerMinute, "UsSurveyFootPerMinute", "UsSurveyFeetPerMinute", new BaseUnits(length: LengthUnit.UsSurveyFoot, time: DurationUnit.Minute), + new QuantityValue(3937, 20) + ); + yield return new (SpeedUnit.UsSurveyFootPerSecond, "UsSurveyFootPerSecond", "UsSurveyFeetPerSecond", new BaseUnits(length: LengthUnit.UsSurveyFoot, time: DurationUnit.Second), + new QuantityValue(3937, 1200) + ); + yield return new (SpeedUnit.YardPerHour, "YardPerHour", "YardsPerHour", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Hour), + new QuantityValue(500000, 127) + ); + yield return new (SpeedUnit.YardPerMinute, "YardPerMinute", "YardsPerMinute", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Minute), + new QuantityValue(25000, 381) + ); + yield return new (SpeedUnit.YardPerSecond, "YardPerSecond", "YardsPerSecond", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Second), + new QuantityValue(1250, 1143) + ); } } static Speed() { - Info = SpeedInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(SpeedInfo.CreateDefault); } /// @@ -174,7 +235,7 @@ static Speed() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Speed(double value, SpeedUnit unit) + public Speed(QuantityValue value, SpeedUnit unit) { _value = value; _unit = unit; @@ -188,7 +249,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -199,7 +260,8 @@ public Speed(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -228,10 +290,8 @@ public Speed(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public SpeedUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -270,252 +330,174 @@ public Speed(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentimetersPerHour => As(SpeedUnit.CentimeterPerHour); + public QuantityValue CentimetersPerHour => this.As(SpeedUnit.CentimeterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentimetersPerMinute => As(SpeedUnit.CentimeterPerMinute); + public QuantityValue CentimetersPerMinute => this.As(SpeedUnit.CentimeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentimetersPerSecond => As(SpeedUnit.CentimeterPerSecond); + public QuantityValue CentimetersPerSecond => this.As(SpeedUnit.CentimeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecimetersPerMinute => As(SpeedUnit.DecimeterPerMinute); + public QuantityValue DecimetersPerMinute => this.As(SpeedUnit.DecimeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecimetersPerSecond => As(SpeedUnit.DecimeterPerSecond); + public QuantityValue DecimetersPerSecond => this.As(SpeedUnit.DecimeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double FeetPerHour => As(SpeedUnit.FootPerHour); + public QuantityValue FeetPerHour => this.As(SpeedUnit.FootPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double FeetPerMinute => As(SpeedUnit.FootPerMinute); + public QuantityValue FeetPerMinute => this.As(SpeedUnit.FootPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double FeetPerSecond => As(SpeedUnit.FootPerSecond); + public QuantityValue FeetPerSecond => this.As(SpeedUnit.FootPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InchesPerHour => As(SpeedUnit.InchPerHour); + public QuantityValue InchesPerHour => this.As(SpeedUnit.InchPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InchesPerMinute => As(SpeedUnit.InchPerMinute); + public QuantityValue InchesPerMinute => this.As(SpeedUnit.InchPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InchesPerSecond => As(SpeedUnit.InchPerSecond); + public QuantityValue InchesPerSecond => this.As(SpeedUnit.InchPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilometersPerHour => As(SpeedUnit.KilometerPerHour); + public QuantityValue KilometersPerHour => this.As(SpeedUnit.KilometerPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilometersPerMinute => As(SpeedUnit.KilometerPerMinute); + public QuantityValue KilometersPerMinute => this.As(SpeedUnit.KilometerPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilometersPerSecond => As(SpeedUnit.KilometerPerSecond); + public QuantityValue KilometersPerSecond => this.As(SpeedUnit.KilometerPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Knots => As(SpeedUnit.Knot); + public QuantityValue Knots => this.As(SpeedUnit.Knot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Mach => As(SpeedUnit.Mach); + public QuantityValue Mach => this.As(SpeedUnit.Mach); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MetersPerHour => As(SpeedUnit.MeterPerHour); + public QuantityValue MetersPerHour => this.As(SpeedUnit.MeterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MetersPerMinute => As(SpeedUnit.MeterPerMinute); + public QuantityValue MetersPerMinute => this.As(SpeedUnit.MeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MetersPerSecond => As(SpeedUnit.MeterPerSecond); + public QuantityValue MetersPerSecond => this.As(SpeedUnit.MeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrometersPerMinute => As(SpeedUnit.MicrometerPerMinute); + public QuantityValue MicrometersPerMinute => this.As(SpeedUnit.MicrometerPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrometersPerSecond => As(SpeedUnit.MicrometerPerSecond); + public QuantityValue MicrometersPerSecond => this.As(SpeedUnit.MicrometerPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MilesPerHour => As(SpeedUnit.MilePerHour); + public QuantityValue MilesPerHour => this.As(SpeedUnit.MilePerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimetersPerHour => As(SpeedUnit.MillimeterPerHour); + public QuantityValue MillimetersPerHour => this.As(SpeedUnit.MillimeterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimetersPerMinute => As(SpeedUnit.MillimeterPerMinute); + public QuantityValue MillimetersPerMinute => this.As(SpeedUnit.MillimeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimetersPerSecond => As(SpeedUnit.MillimeterPerSecond); + public QuantityValue MillimetersPerSecond => this.As(SpeedUnit.MillimeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanometersPerMinute => As(SpeedUnit.NanometerPerMinute); + public QuantityValue NanometersPerMinute => this.As(SpeedUnit.NanometerPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanometersPerSecond => As(SpeedUnit.NanometerPerSecond); + public QuantityValue NanometersPerSecond => this.As(SpeedUnit.NanometerPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsSurveyFeetPerHour => As(SpeedUnit.UsSurveyFootPerHour); + public QuantityValue UsSurveyFeetPerHour => this.As(SpeedUnit.UsSurveyFootPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsSurveyFeetPerMinute => As(SpeedUnit.UsSurveyFootPerMinute); + public QuantityValue UsSurveyFeetPerMinute => this.As(SpeedUnit.UsSurveyFootPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsSurveyFeetPerSecond => As(SpeedUnit.UsSurveyFootPerSecond); + public QuantityValue UsSurveyFeetPerSecond => this.As(SpeedUnit.UsSurveyFootPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double YardsPerHour => As(SpeedUnit.YardPerHour); + public QuantityValue YardsPerHour => this.As(SpeedUnit.YardPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double YardsPerMinute => As(SpeedUnit.YardPerMinute); + public QuantityValue YardsPerMinute => this.As(SpeedUnit.YardPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double YardsPerSecond => As(SpeedUnit.YardPerSecond); + public QuantityValue YardsPerSecond => this.As(SpeedUnit.YardPerSecond); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: SpeedUnit -> BaseUnit - unitConverter.SetConversionFunction(SpeedUnit.CentimeterPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.CentimeterPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.CentimeterPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.DecimeterPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.DecimeterPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.FootPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.FootPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.FootPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.InchPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.InchPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.InchPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.KilometerPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.KilometerPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.KilometerPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.Knot, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.Mach, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MicrometerPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MicrometerPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MilePerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MillimeterPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MillimeterPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MillimeterPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.NanometerPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.NanometerPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.UsSurveyFootPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.UsSurveyFootPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.UsSurveyFootPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.YardPerHour, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.YardPerMinute, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.YardPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MeterPerSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MeterPerSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> SpeedUnit - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerHour, quantity => quantity.ToUnit(SpeedUnit.CentimeterPerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerMinute, quantity => quantity.ToUnit(SpeedUnit.CentimeterPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.CentimeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.DecimeterPerMinute, quantity => quantity.ToUnit(SpeedUnit.DecimeterPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.DecimeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.DecimeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.FootPerHour, quantity => quantity.ToUnit(SpeedUnit.FootPerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.FootPerMinute, quantity => quantity.ToUnit(SpeedUnit.FootPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.FootPerSecond, quantity => quantity.ToUnit(SpeedUnit.FootPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.InchPerHour, quantity => quantity.ToUnit(SpeedUnit.InchPerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.InchPerMinute, quantity => quantity.ToUnit(SpeedUnit.InchPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.InchPerSecond, quantity => quantity.ToUnit(SpeedUnit.InchPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerHour, quantity => quantity.ToUnit(SpeedUnit.KilometerPerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerMinute, quantity => quantity.ToUnit(SpeedUnit.KilometerPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerSecond, quantity => quantity.ToUnit(SpeedUnit.KilometerPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.Knot, quantity => quantity.ToUnit(SpeedUnit.Knot)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.Mach, quantity => quantity.ToUnit(SpeedUnit.Mach)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MeterPerHour, quantity => quantity.ToUnit(SpeedUnit.MeterPerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MeterPerMinute, quantity => quantity.ToUnit(SpeedUnit.MeterPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MicrometerPerMinute, quantity => quantity.ToUnit(SpeedUnit.MicrometerPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MicrometerPerSecond, quantity => quantity.ToUnit(SpeedUnit.MicrometerPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MilePerHour, quantity => quantity.ToUnit(SpeedUnit.MilePerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerHour, quantity => quantity.ToUnit(SpeedUnit.MillimeterPerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerMinute, quantity => quantity.ToUnit(SpeedUnit.MillimeterPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerSecond, quantity => quantity.ToUnit(SpeedUnit.MillimeterPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.NanometerPerMinute, quantity => quantity.ToUnit(SpeedUnit.NanometerPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.NanometerPerSecond, quantity => quantity.ToUnit(SpeedUnit.NanometerPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerHour, quantity => quantity.ToUnit(SpeedUnit.UsSurveyFootPerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerMinute, quantity => quantity.ToUnit(SpeedUnit.UsSurveyFootPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerSecond, quantity => quantity.ToUnit(SpeedUnit.UsSurveyFootPerSecond)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.YardPerHour, quantity => quantity.ToUnit(SpeedUnit.YardPerHour)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.YardPerMinute, quantity => quantity.ToUnit(SpeedUnit.YardPerMinute)); - unitConverter.SetConversionFunction(SpeedUnit.MeterPerSecond, SpeedUnit.YardPerSecond, quantity => quantity.ToUnit(SpeedUnit.YardPerSecond)); - } - /// /// Get unit abbreviation string. /// @@ -544,7 +526,7 @@ public static string GetAbbreviation(SpeedUnit unit, IFormatProvider? provider) /// /// Creates a from . /// - public static Speed FromCentimetersPerHour(double value) + public static Speed FromCentimetersPerHour(QuantityValue value) { return new Speed(value, SpeedUnit.CentimeterPerHour); } @@ -552,7 +534,7 @@ public static Speed FromCentimetersPerHour(double value) /// /// Creates a from . /// - public static Speed FromCentimetersPerMinute(double value) + public static Speed FromCentimetersPerMinute(QuantityValue value) { return new Speed(value, SpeedUnit.CentimeterPerMinute); } @@ -560,7 +542,7 @@ public static Speed FromCentimetersPerMinute(double value) /// /// Creates a from . /// - public static Speed FromCentimetersPerSecond(double value) + public static Speed FromCentimetersPerSecond(QuantityValue value) { return new Speed(value, SpeedUnit.CentimeterPerSecond); } @@ -568,7 +550,7 @@ public static Speed FromCentimetersPerSecond(double value) /// /// Creates a from . /// - public static Speed FromDecimetersPerMinute(double value) + public static Speed FromDecimetersPerMinute(QuantityValue value) { return new Speed(value, SpeedUnit.DecimeterPerMinute); } @@ -576,7 +558,7 @@ public static Speed FromDecimetersPerMinute(double value) /// /// Creates a from . /// - public static Speed FromDecimetersPerSecond(double value) + public static Speed FromDecimetersPerSecond(QuantityValue value) { return new Speed(value, SpeedUnit.DecimeterPerSecond); } @@ -584,7 +566,7 @@ public static Speed FromDecimetersPerSecond(double value) /// /// Creates a from . /// - public static Speed FromFeetPerHour(double value) + public static Speed FromFeetPerHour(QuantityValue value) { return new Speed(value, SpeedUnit.FootPerHour); } @@ -592,7 +574,7 @@ public static Speed FromFeetPerHour(double value) /// /// Creates a from . /// - public static Speed FromFeetPerMinute(double value) + public static Speed FromFeetPerMinute(QuantityValue value) { return new Speed(value, SpeedUnit.FootPerMinute); } @@ -600,7 +582,7 @@ public static Speed FromFeetPerMinute(double value) /// /// Creates a from . /// - public static Speed FromFeetPerSecond(double value) + public static Speed FromFeetPerSecond(QuantityValue value) { return new Speed(value, SpeedUnit.FootPerSecond); } @@ -608,7 +590,7 @@ public static Speed FromFeetPerSecond(double value) /// /// Creates a from . /// - public static Speed FromInchesPerHour(double value) + public static Speed FromInchesPerHour(QuantityValue value) { return new Speed(value, SpeedUnit.InchPerHour); } @@ -616,7 +598,7 @@ public static Speed FromInchesPerHour(double value) /// /// Creates a from . /// - public static Speed FromInchesPerMinute(double value) + public static Speed FromInchesPerMinute(QuantityValue value) { return new Speed(value, SpeedUnit.InchPerMinute); } @@ -624,7 +606,7 @@ public static Speed FromInchesPerMinute(double value) /// /// Creates a from . /// - public static Speed FromInchesPerSecond(double value) + public static Speed FromInchesPerSecond(QuantityValue value) { return new Speed(value, SpeedUnit.InchPerSecond); } @@ -632,7 +614,7 @@ public static Speed FromInchesPerSecond(double value) /// /// Creates a from . /// - public static Speed FromKilometersPerHour(double value) + public static Speed FromKilometersPerHour(QuantityValue value) { return new Speed(value, SpeedUnit.KilometerPerHour); } @@ -640,7 +622,7 @@ public static Speed FromKilometersPerHour(double value) /// /// Creates a from . /// - public static Speed FromKilometersPerMinute(double value) + public static Speed FromKilometersPerMinute(QuantityValue value) { return new Speed(value, SpeedUnit.KilometerPerMinute); } @@ -648,7 +630,7 @@ public static Speed FromKilometersPerMinute(double value) /// /// Creates a from . /// - public static Speed FromKilometersPerSecond(double value) + public static Speed FromKilometersPerSecond(QuantityValue value) { return new Speed(value, SpeedUnit.KilometerPerSecond); } @@ -656,7 +638,7 @@ public static Speed FromKilometersPerSecond(double value) /// /// Creates a from . /// - public static Speed FromKnots(double value) + public static Speed FromKnots(QuantityValue value) { return new Speed(value, SpeedUnit.Knot); } @@ -664,7 +646,7 @@ public static Speed FromKnots(double value) /// /// Creates a from . /// - public static Speed FromMach(double value) + public static Speed FromMach(QuantityValue value) { return new Speed(value, SpeedUnit.Mach); } @@ -672,7 +654,7 @@ public static Speed FromMach(double value) /// /// Creates a from . /// - public static Speed FromMetersPerHour(double value) + public static Speed FromMetersPerHour(QuantityValue value) { return new Speed(value, SpeedUnit.MeterPerHour); } @@ -680,7 +662,7 @@ public static Speed FromMetersPerHour(double value) /// /// Creates a from . /// - public static Speed FromMetersPerMinute(double value) + public static Speed FromMetersPerMinute(QuantityValue value) { return new Speed(value, SpeedUnit.MeterPerMinute); } @@ -688,7 +670,7 @@ public static Speed FromMetersPerMinute(double value) /// /// Creates a from . /// - public static Speed FromMetersPerSecond(double value) + public static Speed FromMetersPerSecond(QuantityValue value) { return new Speed(value, SpeedUnit.MeterPerSecond); } @@ -696,7 +678,7 @@ public static Speed FromMetersPerSecond(double value) /// /// Creates a from . /// - public static Speed FromMicrometersPerMinute(double value) + public static Speed FromMicrometersPerMinute(QuantityValue value) { return new Speed(value, SpeedUnit.MicrometerPerMinute); } @@ -704,7 +686,7 @@ public static Speed FromMicrometersPerMinute(double value) /// /// Creates a from . /// - public static Speed FromMicrometersPerSecond(double value) + public static Speed FromMicrometersPerSecond(QuantityValue value) { return new Speed(value, SpeedUnit.MicrometerPerSecond); } @@ -712,7 +694,7 @@ public static Speed FromMicrometersPerSecond(double value) /// /// Creates a from . /// - public static Speed FromMilesPerHour(double value) + public static Speed FromMilesPerHour(QuantityValue value) { return new Speed(value, SpeedUnit.MilePerHour); } @@ -720,7 +702,7 @@ public static Speed FromMilesPerHour(double value) /// /// Creates a from . /// - public static Speed FromMillimetersPerHour(double value) + public static Speed FromMillimetersPerHour(QuantityValue value) { return new Speed(value, SpeedUnit.MillimeterPerHour); } @@ -728,7 +710,7 @@ public static Speed FromMillimetersPerHour(double value) /// /// Creates a from . /// - public static Speed FromMillimetersPerMinute(double value) + public static Speed FromMillimetersPerMinute(QuantityValue value) { return new Speed(value, SpeedUnit.MillimeterPerMinute); } @@ -736,7 +718,7 @@ public static Speed FromMillimetersPerMinute(double value) /// /// Creates a from . /// - public static Speed FromMillimetersPerSecond(double value) + public static Speed FromMillimetersPerSecond(QuantityValue value) { return new Speed(value, SpeedUnit.MillimeterPerSecond); } @@ -744,7 +726,7 @@ public static Speed FromMillimetersPerSecond(double value) /// /// Creates a from . /// - public static Speed FromNanometersPerMinute(double value) + public static Speed FromNanometersPerMinute(QuantityValue value) { return new Speed(value, SpeedUnit.NanometerPerMinute); } @@ -752,7 +734,7 @@ public static Speed FromNanometersPerMinute(double value) /// /// Creates a from . /// - public static Speed FromNanometersPerSecond(double value) + public static Speed FromNanometersPerSecond(QuantityValue value) { return new Speed(value, SpeedUnit.NanometerPerSecond); } @@ -760,7 +742,7 @@ public static Speed FromNanometersPerSecond(double value) /// /// Creates a from . /// - public static Speed FromUsSurveyFeetPerHour(double value) + public static Speed FromUsSurveyFeetPerHour(QuantityValue value) { return new Speed(value, SpeedUnit.UsSurveyFootPerHour); } @@ -768,7 +750,7 @@ public static Speed FromUsSurveyFeetPerHour(double value) /// /// Creates a from . /// - public static Speed FromUsSurveyFeetPerMinute(double value) + public static Speed FromUsSurveyFeetPerMinute(QuantityValue value) { return new Speed(value, SpeedUnit.UsSurveyFootPerMinute); } @@ -776,7 +758,7 @@ public static Speed FromUsSurveyFeetPerMinute(double value) /// /// Creates a from . /// - public static Speed FromUsSurveyFeetPerSecond(double value) + public static Speed FromUsSurveyFeetPerSecond(QuantityValue value) { return new Speed(value, SpeedUnit.UsSurveyFootPerSecond); } @@ -784,7 +766,7 @@ public static Speed FromUsSurveyFeetPerSecond(double value) /// /// Creates a from . /// - public static Speed FromYardsPerHour(double value) + public static Speed FromYardsPerHour(QuantityValue value) { return new Speed(value, SpeedUnit.YardPerHour); } @@ -792,7 +774,7 @@ public static Speed FromYardsPerHour(double value) /// /// Creates a from . /// - public static Speed FromYardsPerMinute(double value) + public static Speed FromYardsPerMinute(QuantityValue value) { return new Speed(value, SpeedUnit.YardPerMinute); } @@ -800,7 +782,7 @@ public static Speed FromYardsPerMinute(double value) /// /// Creates a from . /// - public static Speed FromYardsPerSecond(double value) + public static Speed FromYardsPerSecond(QuantityValue value) { return new Speed(value, SpeedUnit.YardPerSecond); } @@ -811,7 +793,7 @@ public static Speed FromYardsPerSecond(double value) /// Value to convert from. /// Unit to convert from. /// Speed unit value. - public static Speed From(double value, SpeedUnit fromUnit) + public static Speed From(QuantityValue value, SpeedUnit fromUnit) { return new Speed(value, fromUnit); } @@ -872,10 +854,7 @@ public static Speed Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Speed Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -903,11 +882,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Speed result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Speed result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -928,7 +903,7 @@ public static SpeedUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -939,7 +914,7 @@ public static SpeedUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out SpeedUnit unit) { return TryParseUnit(str, null, out unit); @@ -954,7 +929,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out SpeedUnit un /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out SpeedUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -973,35 +948,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Speed operator +(Speed left, Speed right) { - return new Speed(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Speed(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Speed operator -(Speed left, Speed right) { - return new Speed(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Speed(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -1065,97 +1040,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Speed left, Speed right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Speed left, Speed right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Speed left, Speed right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Speed left, Speed right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Speed other, Speed tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Speed left, Speed right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Speed other, Speed tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Speed left, Speed right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Speed other, Speed tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Speed otherQuantity)) + if (obj is not Speed otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Speed other, Speed tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Speed other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Speed. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Speed), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Speed otherQuantity)) throw new ArgumentException("Expected type Speed.", nameof(obj)); + if (obj is not Speed otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1167,210 +1127,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Speed other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(SpeedUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Speed to another Speed with the unit representation . - /// - /// The unit to convert to. - /// A Speed with the specified unit. - public Speed ToUnit(SpeedUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Speed with the specified unit. - public Speed ToUnit(SpeedUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Speed), Unit, typeof(Speed), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Speed)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(SpeedUnit unit, [NotNullWhen(true)] out Speed? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Speed? convertedOrNull = (Unit, unit) switch - { - // SpeedUnit -> BaseUnit - (SpeedUnit.CentimeterPerHour, SpeedUnit.MeterPerSecond) => new Speed((_value / 3600) * 1e-2d, SpeedUnit.MeterPerSecond), - (SpeedUnit.CentimeterPerMinute, SpeedUnit.MeterPerSecond) => new Speed((_value / 60) * 1e-2d, SpeedUnit.MeterPerSecond), - (SpeedUnit.CentimeterPerSecond, SpeedUnit.MeterPerSecond) => new Speed((_value) * 1e-2d, SpeedUnit.MeterPerSecond), - (SpeedUnit.DecimeterPerMinute, SpeedUnit.MeterPerSecond) => new Speed((_value / 60) * 1e-1d, SpeedUnit.MeterPerSecond), - (SpeedUnit.DecimeterPerSecond, SpeedUnit.MeterPerSecond) => new Speed((_value) * 1e-1d, SpeedUnit.MeterPerSecond), - (SpeedUnit.FootPerHour, SpeedUnit.MeterPerSecond) => new Speed(_value * 0.3048 / 3600, SpeedUnit.MeterPerSecond), - (SpeedUnit.FootPerMinute, SpeedUnit.MeterPerSecond) => new Speed(_value * 0.3048 / 60, SpeedUnit.MeterPerSecond), - (SpeedUnit.FootPerSecond, SpeedUnit.MeterPerSecond) => new Speed(_value * 0.3048, SpeedUnit.MeterPerSecond), - (SpeedUnit.InchPerHour, SpeedUnit.MeterPerSecond) => new Speed((_value / 3600) * 2.54e-2, SpeedUnit.MeterPerSecond), - (SpeedUnit.InchPerMinute, SpeedUnit.MeterPerSecond) => new Speed((_value / 60) * 2.54e-2, SpeedUnit.MeterPerSecond), - (SpeedUnit.InchPerSecond, SpeedUnit.MeterPerSecond) => new Speed(_value * 2.54e-2, SpeedUnit.MeterPerSecond), - (SpeedUnit.KilometerPerHour, SpeedUnit.MeterPerSecond) => new Speed((_value / 3600) * 1e3d, SpeedUnit.MeterPerSecond), - (SpeedUnit.KilometerPerMinute, SpeedUnit.MeterPerSecond) => new Speed((_value / 60) * 1e3d, SpeedUnit.MeterPerSecond), - (SpeedUnit.KilometerPerSecond, SpeedUnit.MeterPerSecond) => new Speed((_value) * 1e3d, SpeedUnit.MeterPerSecond), - (SpeedUnit.Knot, SpeedUnit.MeterPerSecond) => new Speed(_value * (1852.0 / 3600.0), SpeedUnit.MeterPerSecond), - (SpeedUnit.Mach, SpeedUnit.MeterPerSecond) => new Speed(_value * 340.29, SpeedUnit.MeterPerSecond), - (SpeedUnit.MeterPerHour, SpeedUnit.MeterPerSecond) => new Speed(_value / 3600, SpeedUnit.MeterPerSecond), - (SpeedUnit.MeterPerMinute, SpeedUnit.MeterPerSecond) => new Speed(_value / 60, SpeedUnit.MeterPerSecond), - (SpeedUnit.MicrometerPerMinute, SpeedUnit.MeterPerSecond) => new Speed((_value / 60) * 1e-6d, SpeedUnit.MeterPerSecond), - (SpeedUnit.MicrometerPerSecond, SpeedUnit.MeterPerSecond) => new Speed((_value) * 1e-6d, SpeedUnit.MeterPerSecond), - (SpeedUnit.MilePerHour, SpeedUnit.MeterPerSecond) => new Speed(_value * 0.44704, SpeedUnit.MeterPerSecond), - (SpeedUnit.MillimeterPerHour, SpeedUnit.MeterPerSecond) => new Speed((_value / 3600) * 1e-3d, SpeedUnit.MeterPerSecond), - (SpeedUnit.MillimeterPerMinute, SpeedUnit.MeterPerSecond) => new Speed((_value / 60) * 1e-3d, SpeedUnit.MeterPerSecond), - (SpeedUnit.MillimeterPerSecond, SpeedUnit.MeterPerSecond) => new Speed((_value) * 1e-3d, SpeedUnit.MeterPerSecond), - (SpeedUnit.NanometerPerMinute, SpeedUnit.MeterPerSecond) => new Speed((_value / 60) * 1e-9d, SpeedUnit.MeterPerSecond), - (SpeedUnit.NanometerPerSecond, SpeedUnit.MeterPerSecond) => new Speed((_value) * 1e-9d, SpeedUnit.MeterPerSecond), - (SpeedUnit.UsSurveyFootPerHour, SpeedUnit.MeterPerSecond) => new Speed((_value * 1200 / 3937) / 3600, SpeedUnit.MeterPerSecond), - (SpeedUnit.UsSurveyFootPerMinute, SpeedUnit.MeterPerSecond) => new Speed((_value * 1200 / 3937) / 60, SpeedUnit.MeterPerSecond), - (SpeedUnit.UsSurveyFootPerSecond, SpeedUnit.MeterPerSecond) => new Speed(_value * 1200 / 3937, SpeedUnit.MeterPerSecond), - (SpeedUnit.YardPerHour, SpeedUnit.MeterPerSecond) => new Speed(_value * 0.9144 / 3600, SpeedUnit.MeterPerSecond), - (SpeedUnit.YardPerMinute, SpeedUnit.MeterPerSecond) => new Speed(_value * 0.9144 / 60, SpeedUnit.MeterPerSecond), - (SpeedUnit.YardPerSecond, SpeedUnit.MeterPerSecond) => new Speed(_value * 0.9144, SpeedUnit.MeterPerSecond), - - // BaseUnit -> SpeedUnit - (SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerHour) => new Speed((_value * 3600) / 1e-2d, SpeedUnit.CentimeterPerHour), - (SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerMinute) => new Speed((_value * 60) / 1e-2d, SpeedUnit.CentimeterPerMinute), - (SpeedUnit.MeterPerSecond, SpeedUnit.CentimeterPerSecond) => new Speed((_value) / 1e-2d, SpeedUnit.CentimeterPerSecond), - (SpeedUnit.MeterPerSecond, SpeedUnit.DecimeterPerMinute) => new Speed((_value * 60) / 1e-1d, SpeedUnit.DecimeterPerMinute), - (SpeedUnit.MeterPerSecond, SpeedUnit.DecimeterPerSecond) => new Speed((_value) / 1e-1d, SpeedUnit.DecimeterPerSecond), - (SpeedUnit.MeterPerSecond, SpeedUnit.FootPerHour) => new Speed(_value / 0.3048 * 3600, SpeedUnit.FootPerHour), - (SpeedUnit.MeterPerSecond, SpeedUnit.FootPerMinute) => new Speed(_value / 0.3048 * 60, SpeedUnit.FootPerMinute), - (SpeedUnit.MeterPerSecond, SpeedUnit.FootPerSecond) => new Speed(_value / 0.3048, SpeedUnit.FootPerSecond), - (SpeedUnit.MeterPerSecond, SpeedUnit.InchPerHour) => new Speed((_value / 2.54e-2) * 3600, SpeedUnit.InchPerHour), - (SpeedUnit.MeterPerSecond, SpeedUnit.InchPerMinute) => new Speed((_value / 2.54e-2) * 60, SpeedUnit.InchPerMinute), - (SpeedUnit.MeterPerSecond, SpeedUnit.InchPerSecond) => new Speed(_value / 2.54e-2, SpeedUnit.InchPerSecond), - (SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerHour) => new Speed((_value * 3600) / 1e3d, SpeedUnit.KilometerPerHour), - (SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerMinute) => new Speed((_value * 60) / 1e3d, SpeedUnit.KilometerPerMinute), - (SpeedUnit.MeterPerSecond, SpeedUnit.KilometerPerSecond) => new Speed((_value) / 1e3d, SpeedUnit.KilometerPerSecond), - (SpeedUnit.MeterPerSecond, SpeedUnit.Knot) => new Speed(_value / (1852.0 / 3600.0), SpeedUnit.Knot), - (SpeedUnit.MeterPerSecond, SpeedUnit.Mach) => new Speed(_value / 340.29, SpeedUnit.Mach), - (SpeedUnit.MeterPerSecond, SpeedUnit.MeterPerHour) => new Speed(_value * 3600, SpeedUnit.MeterPerHour), - (SpeedUnit.MeterPerSecond, SpeedUnit.MeterPerMinute) => new Speed(_value * 60, SpeedUnit.MeterPerMinute), - (SpeedUnit.MeterPerSecond, SpeedUnit.MicrometerPerMinute) => new Speed((_value * 60) / 1e-6d, SpeedUnit.MicrometerPerMinute), - (SpeedUnit.MeterPerSecond, SpeedUnit.MicrometerPerSecond) => new Speed((_value) / 1e-6d, SpeedUnit.MicrometerPerSecond), - (SpeedUnit.MeterPerSecond, SpeedUnit.MilePerHour) => new Speed(_value / 0.44704, SpeedUnit.MilePerHour), - (SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerHour) => new Speed((_value * 3600) / 1e-3d, SpeedUnit.MillimeterPerHour), - (SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerMinute) => new Speed((_value * 60) / 1e-3d, SpeedUnit.MillimeterPerMinute), - (SpeedUnit.MeterPerSecond, SpeedUnit.MillimeterPerSecond) => new Speed((_value) / 1e-3d, SpeedUnit.MillimeterPerSecond), - (SpeedUnit.MeterPerSecond, SpeedUnit.NanometerPerMinute) => new Speed((_value * 60) / 1e-9d, SpeedUnit.NanometerPerMinute), - (SpeedUnit.MeterPerSecond, SpeedUnit.NanometerPerSecond) => new Speed((_value) / 1e-9d, SpeedUnit.NanometerPerSecond), - (SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerHour) => new Speed((_value * 3937 / 1200) * 3600, SpeedUnit.UsSurveyFootPerHour), - (SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerMinute) => new Speed((_value * 3937 / 1200) * 60, SpeedUnit.UsSurveyFootPerMinute), - (SpeedUnit.MeterPerSecond, SpeedUnit.UsSurveyFootPerSecond) => new Speed(_value * 3937 / 1200, SpeedUnit.UsSurveyFootPerSecond), - (SpeedUnit.MeterPerSecond, SpeedUnit.YardPerHour) => new Speed(_value / 0.9144 * 3600, SpeedUnit.YardPerHour), - (SpeedUnit.MeterPerSecond, SpeedUnit.YardPerMinute) => new Speed(_value / 0.9144 * 60, SpeedUnit.YardPerMinute), - (SpeedUnit.MeterPerSecond, SpeedUnit.YardPerSecond) => new Speed(_value / 0.9144, SpeedUnit.YardPerSecond), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Speed ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not SpeedUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(SpeedUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(SpeedUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(SpeedUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1385,7 +1159,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs index 0269d9f0a6..e171050263 100644 --- a/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/StandardVolumeFlow.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct StandardVolumeFlow : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly StandardVolumeFlowUnit? _unit; /// @@ -101,7 +100,7 @@ public static StandardVolumeFlowInfo CreateDefault(Func - /// The for is [T^-1][M]. + /// The for is T^-1M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 1, -1, 0, 0, 0, 0); @@ -116,23 +115,37 @@ public static StandardVolumeFlowInfo CreateDefault(FuncAn of representing the default unit mappings for StandardVolumeFlow. public static IEnumerable> GetDefaultMappings() { - yield return new (StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, "StandardCubicCentimeterPerMinute", "StandardCubicCentimetersPerMinute", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Minute)); - yield return new (StandardVolumeFlowUnit.StandardCubicFootPerHour, "StandardCubicFootPerHour", "StandardCubicFeetPerHour", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Hour)); - yield return new (StandardVolumeFlowUnit.StandardCubicFootPerMinute, "StandardCubicFootPerMinute", "StandardCubicFeetPerMinute", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Minute)); - yield return new (StandardVolumeFlowUnit.StandardCubicFootPerSecond, "StandardCubicFootPerSecond", "StandardCubicFeetPerSecond", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second)); - yield return new (StandardVolumeFlowUnit.StandardCubicMeterPerDay, "StandardCubicMeterPerDay", "StandardCubicMetersPerDay", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Day)); - yield return new (StandardVolumeFlowUnit.StandardCubicMeterPerHour, "StandardCubicMeterPerHour", "StandardCubicMetersPerHour", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Hour)); - yield return new (StandardVolumeFlowUnit.StandardCubicMeterPerMinute, "StandardCubicMeterPerMinute", "StandardCubicMetersPerMinute", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Minute)); + yield return new (StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, "StandardCubicCentimeterPerMinute", "StandardCubicCentimetersPerMinute", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Minute), + 60000000 + ); + yield return new (StandardVolumeFlowUnit.StandardCubicFootPerHour, "StandardCubicFootPerHour", "StandardCubicFeetPerHour", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Hour), + new QuantityValue(781250000000, 6145149) + ); + yield return new (StandardVolumeFlowUnit.StandardCubicFootPerMinute, "StandardCubicFootPerMinute", "StandardCubicFeetPerMinute", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Minute), + new QuantityValue(39062500000, 18435447) + ); + yield return new (StandardVolumeFlowUnit.StandardCubicFootPerSecond, "StandardCubicFootPerSecond", "StandardCubicFeetPerSecond", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second), + new QuantityValue(1953125000, 55306341) + ); + yield return new (StandardVolumeFlowUnit.StandardCubicMeterPerDay, "StandardCubicMeterPerDay", "StandardCubicMetersPerDay", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Day), + 86400 + ); + yield return new (StandardVolumeFlowUnit.StandardCubicMeterPerHour, "StandardCubicMeterPerHour", "StandardCubicMetersPerHour", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Hour), + 3600 + ); + yield return new (StandardVolumeFlowUnit.StandardCubicMeterPerMinute, "StandardCubicMeterPerMinute", "StandardCubicMetersPerMinute", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Minute), + 60 + ); yield return new (StandardVolumeFlowUnit.StandardCubicMeterPerSecond, "StandardCubicMeterPerSecond", "StandardCubicMetersPerSecond", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)); - yield return new (StandardVolumeFlowUnit.StandardLiterPerMinute, "StandardLiterPerMinute", "StandardLitersPerMinute", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Minute)); + yield return new (StandardVolumeFlowUnit.StandardLiterPerMinute, "StandardLiterPerMinute", "StandardLitersPerMinute", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Minute), + 60000 + ); } } static StandardVolumeFlow() { - Info = StandardVolumeFlowInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(StandardVolumeFlowInfo.CreateDefault); } /// @@ -140,7 +153,7 @@ static StandardVolumeFlow() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public StandardVolumeFlow(double value, StandardVolumeFlowUnit unit) + public StandardVolumeFlow(QuantityValue value, StandardVolumeFlowUnit unit) { _value = value; _unit = unit; @@ -154,7 +167,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -165,7 +178,8 @@ public StandardVolumeFlow(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -194,10 +208,8 @@ public StandardVolumeFlow(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public StandardVolumeFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -236,84 +248,54 @@ public StandardVolumeFlow(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double StandardCubicCentimetersPerMinute => As(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute); + public QuantityValue StandardCubicCentimetersPerMinute => this.As(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double StandardCubicFeetPerHour => As(StandardVolumeFlowUnit.StandardCubicFootPerHour); + public QuantityValue StandardCubicFeetPerHour => this.As(StandardVolumeFlowUnit.StandardCubicFootPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double StandardCubicFeetPerMinute => As(StandardVolumeFlowUnit.StandardCubicFootPerMinute); + public QuantityValue StandardCubicFeetPerMinute => this.As(StandardVolumeFlowUnit.StandardCubicFootPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double StandardCubicFeetPerSecond => As(StandardVolumeFlowUnit.StandardCubicFootPerSecond); + public QuantityValue StandardCubicFeetPerSecond => this.As(StandardVolumeFlowUnit.StandardCubicFootPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double StandardCubicMetersPerDay => As(StandardVolumeFlowUnit.StandardCubicMeterPerDay); + public QuantityValue StandardCubicMetersPerDay => this.As(StandardVolumeFlowUnit.StandardCubicMeterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double StandardCubicMetersPerHour => As(StandardVolumeFlowUnit.StandardCubicMeterPerHour); + public QuantityValue StandardCubicMetersPerHour => this.As(StandardVolumeFlowUnit.StandardCubicMeterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double StandardCubicMetersPerMinute => As(StandardVolumeFlowUnit.StandardCubicMeterPerMinute); + public QuantityValue StandardCubicMetersPerMinute => this.As(StandardVolumeFlowUnit.StandardCubicMeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double StandardCubicMetersPerSecond => As(StandardVolumeFlowUnit.StandardCubicMeterPerSecond); + public QuantityValue StandardCubicMetersPerSecond => this.As(StandardVolumeFlowUnit.StandardCubicMeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double StandardLitersPerMinute => As(StandardVolumeFlowUnit.StandardLiterPerMinute); + public QuantityValue StandardLitersPerMinute => this.As(StandardVolumeFlowUnit.StandardLiterPerMinute); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: StandardVolumeFlowUnit -> BaseUnit - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicFootPerHour, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicFootPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicFootPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerDay, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerHour, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardLiterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> StandardVolumeFlowUnit - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerHour, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicFootPerHour)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerMinute, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicFootPerMinute)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerSecond, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicFootPerSecond)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerDay, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerDay)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerHour, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerHour)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerMinute, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardCubicMeterPerMinute)); - unitConverter.SetConversionFunction(StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardLiterPerMinute, quantity => quantity.ToUnit(StandardVolumeFlowUnit.StandardLiterPerMinute)); - } - /// /// Get unit abbreviation string. /// @@ -342,7 +324,7 @@ public static string GetAbbreviation(StandardVolumeFlowUnit unit, IFormatProvide /// /// Creates a from . /// - public static StandardVolumeFlow FromStandardCubicCentimetersPerMinute(double value) + public static StandardVolumeFlow FromStandardCubicCentimetersPerMinute(QuantityValue value) { return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute); } @@ -350,7 +332,7 @@ public static StandardVolumeFlow FromStandardCubicCentimetersPerMinute(double va /// /// Creates a from . /// - public static StandardVolumeFlow FromStandardCubicFeetPerHour(double value) + public static StandardVolumeFlow FromStandardCubicFeetPerHour(QuantityValue value) { return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicFootPerHour); } @@ -358,7 +340,7 @@ public static StandardVolumeFlow FromStandardCubicFeetPerHour(double value) /// /// Creates a from . /// - public static StandardVolumeFlow FromStandardCubicFeetPerMinute(double value) + public static StandardVolumeFlow FromStandardCubicFeetPerMinute(QuantityValue value) { return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicFootPerMinute); } @@ -366,7 +348,7 @@ public static StandardVolumeFlow FromStandardCubicFeetPerMinute(double value) /// /// Creates a from . /// - public static StandardVolumeFlow FromStandardCubicFeetPerSecond(double value) + public static StandardVolumeFlow FromStandardCubicFeetPerSecond(QuantityValue value) { return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicFootPerSecond); } @@ -374,7 +356,7 @@ public static StandardVolumeFlow FromStandardCubicFeetPerSecond(double value) /// /// Creates a from . /// - public static StandardVolumeFlow FromStandardCubicMetersPerDay(double value) + public static StandardVolumeFlow FromStandardCubicMetersPerDay(QuantityValue value) { return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicMeterPerDay); } @@ -382,7 +364,7 @@ public static StandardVolumeFlow FromStandardCubicMetersPerDay(double value) /// /// Creates a from . /// - public static StandardVolumeFlow FromStandardCubicMetersPerHour(double value) + public static StandardVolumeFlow FromStandardCubicMetersPerHour(QuantityValue value) { return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicMeterPerHour); } @@ -390,7 +372,7 @@ public static StandardVolumeFlow FromStandardCubicMetersPerHour(double value) /// /// Creates a from . /// - public static StandardVolumeFlow FromStandardCubicMetersPerMinute(double value) + public static StandardVolumeFlow FromStandardCubicMetersPerMinute(QuantityValue value) { return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicMeterPerMinute); } @@ -398,7 +380,7 @@ public static StandardVolumeFlow FromStandardCubicMetersPerMinute(double value) /// /// Creates a from . /// - public static StandardVolumeFlow FromStandardCubicMetersPerSecond(double value) + public static StandardVolumeFlow FromStandardCubicMetersPerSecond(QuantityValue value) { return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardCubicMeterPerSecond); } @@ -406,7 +388,7 @@ public static StandardVolumeFlow FromStandardCubicMetersPerSecond(double value) /// /// Creates a from . /// - public static StandardVolumeFlow FromStandardLitersPerMinute(double value) + public static StandardVolumeFlow FromStandardLitersPerMinute(QuantityValue value) { return new StandardVolumeFlow(value, StandardVolumeFlowUnit.StandardLiterPerMinute); } @@ -417,7 +399,7 @@ public static StandardVolumeFlow FromStandardLitersPerMinute(double value) /// Value to convert from. /// Unit to convert from. /// StandardVolumeFlow unit value. - public static StandardVolumeFlow From(double value, StandardVolumeFlowUnit fromUnit) + public static StandardVolumeFlow From(QuantityValue value, StandardVolumeFlowUnit fromUnit) { return new StandardVolumeFlow(value, fromUnit); } @@ -478,10 +460,7 @@ public static StandardVolumeFlow Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static StandardVolumeFlow Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -509,11 +488,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out StandardVolumeFl /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out StandardVolumeFlow result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -534,7 +509,7 @@ public static StandardVolumeFlowUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -545,7 +520,7 @@ public static StandardVolumeFlowUnit ParseUnit(string str, IFormatProvider? prov return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out StandardVolumeFlowUnit unit) { return TryParseUnit(str, null, out unit); @@ -560,7 +535,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out StandardVolu /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out StandardVolumeFlowUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -579,35 +554,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static StandardVolumeFlow operator +(StandardVolumeFlow left, StandardVolumeFlow right) { - return new StandardVolumeFlow(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new StandardVolumeFlow(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static StandardVolumeFlow operator -(StandardVolumeFlow left, StandardVolumeFlow right) { - return new StandardVolumeFlow(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new StandardVolumeFlow(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -619,97 +594,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(StandardVolumeFlow left, StandardVolumeFlow right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(StandardVolumeFlow left, StandardVolumeFlow right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(StandardVolumeFlow left, StandardVolumeFlow right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(StandardVolumeFlow left, StandardVolumeFlow right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(StandardVolumeFlow other, StandardVolumeFlow tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(StandardVolumeFlow left, StandardVolumeFlow right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(StandardVolumeFlow other, StandardVolumeFlow tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(StandardVolumeFlow left, StandardVolumeFlow right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(StandardVolumeFlow other, StandardVolumeFlow tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is StandardVolumeFlow otherQuantity)) + if (obj is not StandardVolumeFlow otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(StandardVolumeFlow other, StandardVolumeFlow tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(StandardVolumeFlow other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current StandardVolumeFlow. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(StandardVolumeFlow), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is StandardVolumeFlow otherQuantity)) throw new ArgumentException("Expected type StandardVolumeFlow.", nameof(obj)); + if (obj is not StandardVolumeFlow otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -721,162 +681,24 @@ public int CompareTo(object? obj) /// public int CompareTo(StandardVolumeFlow other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(StandardVolumeFlowUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this StandardVolumeFlow to another StandardVolumeFlow with the unit representation . - /// - /// The unit to convert to. - /// A StandardVolumeFlow with the specified unit. - public StandardVolumeFlow ToUnit(StandardVolumeFlowUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A StandardVolumeFlow with the specified unit. - public StandardVolumeFlow ToUnit(StandardVolumeFlowUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(StandardVolumeFlow), Unit, typeof(StandardVolumeFlow), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (StandardVolumeFlow)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(StandardVolumeFlowUnit unit, [NotNullWhen(true)] out StandardVolumeFlow? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - StandardVolumeFlow? convertedOrNull = (Unit, unit) switch - { - // StandardVolumeFlowUnit -> BaseUnit - (StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond) => new StandardVolumeFlow(_value / 6e7, StandardVolumeFlowUnit.StandardCubicMeterPerSecond), - (StandardVolumeFlowUnit.StandardCubicFootPerHour, StandardVolumeFlowUnit.StandardCubicMeterPerSecond) => new StandardVolumeFlow(_value * 0.028316846592 / 3600, StandardVolumeFlowUnit.StandardCubicMeterPerSecond), - (StandardVolumeFlowUnit.StandardCubicFootPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond) => new StandardVolumeFlow(_value * 0.028316846592 / 60, StandardVolumeFlowUnit.StandardCubicMeterPerSecond), - (StandardVolumeFlowUnit.StandardCubicFootPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerSecond) => new StandardVolumeFlow(_value * 0.028316846592, StandardVolumeFlowUnit.StandardCubicMeterPerSecond), - (StandardVolumeFlowUnit.StandardCubicMeterPerDay, StandardVolumeFlowUnit.StandardCubicMeterPerSecond) => new StandardVolumeFlow(_value / 86400, StandardVolumeFlowUnit.StandardCubicMeterPerSecond), - (StandardVolumeFlowUnit.StandardCubicMeterPerHour, StandardVolumeFlowUnit.StandardCubicMeterPerSecond) => new StandardVolumeFlow(_value / 3600, StandardVolumeFlowUnit.StandardCubicMeterPerSecond), - (StandardVolumeFlowUnit.StandardCubicMeterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond) => new StandardVolumeFlow(_value / 60, StandardVolumeFlowUnit.StandardCubicMeterPerSecond), - (StandardVolumeFlowUnit.StandardLiterPerMinute, StandardVolumeFlowUnit.StandardCubicMeterPerSecond) => new StandardVolumeFlow(_value / 60000, StandardVolumeFlowUnit.StandardCubicMeterPerSecond), - - // BaseUnit -> StandardVolumeFlowUnit - (StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute) => new StandardVolumeFlow(_value * 6e7, StandardVolumeFlowUnit.StandardCubicCentimeterPerMinute), - (StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerHour) => new StandardVolumeFlow(_value / (0.028316846592 / 3600), StandardVolumeFlowUnit.StandardCubicFootPerHour), - (StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerMinute) => new StandardVolumeFlow(_value / (0.028316846592 / 60), StandardVolumeFlowUnit.StandardCubicFootPerMinute), - (StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicFootPerSecond) => new StandardVolumeFlow(_value / 0.028316846592, StandardVolumeFlowUnit.StandardCubicFootPerSecond), - (StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerDay) => new StandardVolumeFlow(_value * 86400, StandardVolumeFlowUnit.StandardCubicMeterPerDay), - (StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerHour) => new StandardVolumeFlow(_value * 3600, StandardVolumeFlowUnit.StandardCubicMeterPerHour), - (StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardCubicMeterPerMinute) => new StandardVolumeFlow(_value * 60, StandardVolumeFlowUnit.StandardCubicMeterPerMinute), - (StandardVolumeFlowUnit.StandardCubicMeterPerSecond, StandardVolumeFlowUnit.StandardLiterPerMinute) => new StandardVolumeFlow(_value * 60000, StandardVolumeFlowUnit.StandardLiterPerMinute), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public StandardVolumeFlow ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not StandardVolumeFlowUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(StandardVolumeFlowUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(StandardVolumeFlowUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(StandardVolumeFlowUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -891,7 +713,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs b/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs index f33a79d09a..0442d195bc 100644 --- a/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Temperature.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Temperature : IAffineQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly TemperatureUnit? _unit; /// @@ -101,7 +100,7 @@ public static TemperatureInfo CreateDefault(Func - /// The for is [Θ]. + /// The for is Θ. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 0, 0, 1, 0, 0); @@ -116,24 +115,47 @@ public static TemperatureInfo CreateDefault(FuncAn of representing the default unit mappings for Temperature. public static IEnumerable> GetDefaultMappings() { - yield return new (TemperatureUnit.DegreeCelsius, "DegreeCelsius", "DegreesCelsius", new BaseUnits(temperature: TemperatureUnit.DegreeCelsius)); - yield return new (TemperatureUnit.DegreeDelisle, "DegreeDelisle", "DegreesDelisle", new BaseUnits(temperature: TemperatureUnit.DegreeDelisle)); - yield return new (TemperatureUnit.DegreeFahrenheit, "DegreeFahrenheit", "DegreesFahrenheit", new BaseUnits(temperature: TemperatureUnit.DegreeFahrenheit)); - yield return new (TemperatureUnit.DegreeNewton, "DegreeNewton", "DegreesNewton", new BaseUnits(temperature: TemperatureUnit.DegreeNewton)); - yield return new (TemperatureUnit.DegreeRankine, "DegreeRankine", "DegreesRankine", new BaseUnits(temperature: TemperatureUnit.DegreeRankine)); - yield return new (TemperatureUnit.DegreeReaumur, "DegreeReaumur", "DegreesReaumur", new BaseUnits(temperature: TemperatureUnit.DegreeReaumur)); - yield return new (TemperatureUnit.DegreeRoemer, "DegreeRoemer", "DegreesRoemer", new BaseUnits(temperature: TemperatureUnit.DegreeRoemer)); + yield return new (TemperatureUnit.DegreeCelsius, "DegreeCelsius", "DegreesCelsius", new BaseUnits(temperature: TemperatureUnit.DegreeCelsius), + new ConversionExpression(1, new QuantityValue(-5463, 20)), + new ConversionExpression(1, new QuantityValue(5463, 20)) + ); + yield return new (TemperatureUnit.DegreeDelisle, "DegreeDelisle", "DegreesDelisle", new BaseUnits(temperature: TemperatureUnit.DegreeDelisle), + new ConversionExpression(new QuantityValue(-3, 2), new QuantityValue(22389, 40)), + new ConversionExpression(new QuantityValue(-2, 3), new QuantityValue(7463, 20)) + ); + yield return new (TemperatureUnit.DegreeFahrenheit, "DegreeFahrenheit", "DegreesFahrenheit", new BaseUnits(temperature: TemperatureUnit.DegreeFahrenheit), + new ConversionExpression(new QuantityValue(9, 5), new QuantityValue(-45967, 100)), + new ConversionExpression(new QuantityValue(5, 9), new QuantityValue(45967, 180)) + ); + yield return new (TemperatureUnit.DegreeNewton, "DegreeNewton", "DegreesNewton", new BaseUnits(temperature: TemperatureUnit.DegreeNewton), + new ConversionExpression(new QuantityValue(33, 100), new QuantityValue(-180279, 2000)), + new ConversionExpression(new QuantityValue(100, 33), new QuantityValue(5463, 20)) + ); + yield return new (TemperatureUnit.DegreeRankine, "DegreeRankine", "DegreesRankine", new BaseUnits(temperature: TemperatureUnit.DegreeRankine), + new QuantityValue(9, 5) + ); + yield return new (TemperatureUnit.DegreeReaumur, "DegreeReaumur", "DegreesReaumur", new BaseUnits(temperature: TemperatureUnit.DegreeReaumur), + new ConversionExpression(new QuantityValue(4, 5), new QuantityValue(-5463, 25)), + new ConversionExpression(new QuantityValue(5, 4), new QuantityValue(5463, 20)) + ); + yield return new (TemperatureUnit.DegreeRoemer, "DegreeRoemer", "DegreesRoemer", new BaseUnits(temperature: TemperatureUnit.DegreeRoemer), + new ConversionExpression(new QuantityValue(21, 40), new QuantityValue(-108723, 800)), + new ConversionExpression(new QuantityValue(40, 21), new QuantityValue(36241, 140)) + ); yield return new (TemperatureUnit.Kelvin, "Kelvin", "Kelvins", new BaseUnits(temperature: TemperatureUnit.Kelvin)); - yield return new (TemperatureUnit.MillidegreeCelsius, "MillidegreeCelsius", "MillidegreesCelsius", new BaseUnits(temperature: TemperatureUnit.MillidegreeCelsius)); - yield return new (TemperatureUnit.SolarTemperature, "SolarTemperature", "SolarTemperatures", new BaseUnits(temperature: TemperatureUnit.SolarTemperature)); + yield return new (TemperatureUnit.MillidegreeCelsius, "MillidegreeCelsius", "MillidegreesCelsius", new BaseUnits(temperature: TemperatureUnit.MillidegreeCelsius), + new ConversionExpression(1000, -273150), + new ConversionExpression(new QuantityValue(1, 1000), new QuantityValue(5463, 20)) + ); + yield return new (TemperatureUnit.SolarTemperature, "SolarTemperature", "SolarTemperatures", new BaseUnits(temperature: TemperatureUnit.SolarTemperature), + new QuantityValue(1, 5778) + ); } } static Temperature() { - Info = TemperatureInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(TemperatureInfo.CreateDefault); } /// @@ -141,7 +163,7 @@ static Temperature() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Temperature(double value, TemperatureUnit unit) + public Temperature(QuantityValue value, TemperatureUnit unit) { _value = value; _unit = unit; @@ -155,7 +177,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -166,7 +188,8 @@ public Temperature(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -195,10 +218,8 @@ public Temperature(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public TemperatureUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -237,91 +258,59 @@ public Temperature(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesCelsius => As(TemperatureUnit.DegreeCelsius); + public QuantityValue DegreesCelsius => this.As(TemperatureUnit.DegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesDelisle => As(TemperatureUnit.DegreeDelisle); + public QuantityValue DegreesDelisle => this.As(TemperatureUnit.DegreeDelisle); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesFahrenheit => As(TemperatureUnit.DegreeFahrenheit); + public QuantityValue DegreesFahrenheit => this.As(TemperatureUnit.DegreeFahrenheit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesNewton => As(TemperatureUnit.DegreeNewton); + public QuantityValue DegreesNewton => this.As(TemperatureUnit.DegreeNewton); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesRankine => As(TemperatureUnit.DegreeRankine); + public QuantityValue DegreesRankine => this.As(TemperatureUnit.DegreeRankine); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesReaumur => As(TemperatureUnit.DegreeReaumur); + public QuantityValue DegreesReaumur => this.As(TemperatureUnit.DegreeReaumur); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesRoemer => As(TemperatureUnit.DegreeRoemer); + public QuantityValue DegreesRoemer => this.As(TemperatureUnit.DegreeRoemer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kelvins => As(TemperatureUnit.Kelvin); + public QuantityValue Kelvins => this.As(TemperatureUnit.Kelvin); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillidegreesCelsius => As(TemperatureUnit.MillidegreeCelsius); + public QuantityValue MillidegreesCelsius => this.As(TemperatureUnit.MillidegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SolarTemperatures => As(TemperatureUnit.SolarTemperature); + public QuantityValue SolarTemperatures => this.As(TemperatureUnit.SolarTemperature); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: TemperatureUnit -> BaseUnit - unitConverter.SetConversionFunction(TemperatureUnit.DegreeCelsius, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); - unitConverter.SetConversionFunction(TemperatureUnit.DegreeDelisle, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); - unitConverter.SetConversionFunction(TemperatureUnit.DegreeFahrenheit, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); - unitConverter.SetConversionFunction(TemperatureUnit.DegreeNewton, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); - unitConverter.SetConversionFunction(TemperatureUnit.DegreeRankine, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); - unitConverter.SetConversionFunction(TemperatureUnit.DegreeReaumur, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); - unitConverter.SetConversionFunction(TemperatureUnit.DegreeRoemer, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); - unitConverter.SetConversionFunction(TemperatureUnit.MillidegreeCelsius, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); - unitConverter.SetConversionFunction(TemperatureUnit.SolarTemperature, TemperatureUnit.Kelvin, quantity => quantity.ToUnit(TemperatureUnit.Kelvin)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.Kelvin, quantity => quantity); - - // Register in unit converter: BaseUnit -> TemperatureUnit - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeCelsius, quantity => quantity.ToUnit(TemperatureUnit.DegreeCelsius)); - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeDelisle, quantity => quantity.ToUnit(TemperatureUnit.DegreeDelisle)); - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeFahrenheit, quantity => quantity.ToUnit(TemperatureUnit.DegreeFahrenheit)); - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeNewton, quantity => quantity.ToUnit(TemperatureUnit.DegreeNewton)); - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeRankine, quantity => quantity.ToUnit(TemperatureUnit.DegreeRankine)); - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeReaumur, quantity => quantity.ToUnit(TemperatureUnit.DegreeReaumur)); - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.DegreeRoemer, quantity => quantity.ToUnit(TemperatureUnit.DegreeRoemer)); - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.MillidegreeCelsius, quantity => quantity.ToUnit(TemperatureUnit.MillidegreeCelsius)); - unitConverter.SetConversionFunction(TemperatureUnit.Kelvin, TemperatureUnit.SolarTemperature, quantity => quantity.ToUnit(TemperatureUnit.SolarTemperature)); - } - /// /// Get unit abbreviation string. /// @@ -350,7 +339,7 @@ public static string GetAbbreviation(TemperatureUnit unit, IFormatProvider? prov /// /// Creates a from . /// - public static Temperature FromDegreesCelsius(double value) + public static Temperature FromDegreesCelsius(QuantityValue value) { return new Temperature(value, TemperatureUnit.DegreeCelsius); } @@ -358,7 +347,7 @@ public static Temperature FromDegreesCelsius(double value) /// /// Creates a from . /// - public static Temperature FromDegreesDelisle(double value) + public static Temperature FromDegreesDelisle(QuantityValue value) { return new Temperature(value, TemperatureUnit.DegreeDelisle); } @@ -366,7 +355,7 @@ public static Temperature FromDegreesDelisle(double value) /// /// Creates a from . /// - public static Temperature FromDegreesFahrenheit(double value) + public static Temperature FromDegreesFahrenheit(QuantityValue value) { return new Temperature(value, TemperatureUnit.DegreeFahrenheit); } @@ -374,7 +363,7 @@ public static Temperature FromDegreesFahrenheit(double value) /// /// Creates a from . /// - public static Temperature FromDegreesNewton(double value) + public static Temperature FromDegreesNewton(QuantityValue value) { return new Temperature(value, TemperatureUnit.DegreeNewton); } @@ -382,7 +371,7 @@ public static Temperature FromDegreesNewton(double value) /// /// Creates a from . /// - public static Temperature FromDegreesRankine(double value) + public static Temperature FromDegreesRankine(QuantityValue value) { return new Temperature(value, TemperatureUnit.DegreeRankine); } @@ -390,7 +379,7 @@ public static Temperature FromDegreesRankine(double value) /// /// Creates a from . /// - public static Temperature FromDegreesReaumur(double value) + public static Temperature FromDegreesReaumur(QuantityValue value) { return new Temperature(value, TemperatureUnit.DegreeReaumur); } @@ -398,7 +387,7 @@ public static Temperature FromDegreesReaumur(double value) /// /// Creates a from . /// - public static Temperature FromDegreesRoemer(double value) + public static Temperature FromDegreesRoemer(QuantityValue value) { return new Temperature(value, TemperatureUnit.DegreeRoemer); } @@ -406,7 +395,7 @@ public static Temperature FromDegreesRoemer(double value) /// /// Creates a from . /// - public static Temperature FromKelvins(double value) + public static Temperature FromKelvins(QuantityValue value) { return new Temperature(value, TemperatureUnit.Kelvin); } @@ -414,7 +403,7 @@ public static Temperature FromKelvins(double value) /// /// Creates a from . /// - public static Temperature FromMillidegreesCelsius(double value) + public static Temperature FromMillidegreesCelsius(QuantityValue value) { return new Temperature(value, TemperatureUnit.MillidegreeCelsius); } @@ -422,7 +411,7 @@ public static Temperature FromMillidegreesCelsius(double value) /// /// Creates a from . /// - public static Temperature FromSolarTemperatures(double value) + public static Temperature FromSolarTemperatures(QuantityValue value) { return new Temperature(value, TemperatureUnit.SolarTemperature); } @@ -433,7 +422,7 @@ public static Temperature FromSolarTemperatures(double value) /// Value to convert from. /// Unit to convert from. /// Temperature unit value. - public static Temperature From(double value, TemperatureUnit fromUnit) + public static Temperature From(QuantityValue value, TemperatureUnit fromUnit) { return new Temperature(value, fromUnit); } @@ -494,10 +483,7 @@ public static Temperature Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Temperature Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -525,11 +511,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Temperature resu /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Temperature result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -550,7 +532,7 @@ public static TemperatureUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -561,7 +543,7 @@ public static TemperatureUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out TemperatureUnit unit) { return TryParseUnit(str, null, out unit); @@ -576,7 +558,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out TemperatureU /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out TemperatureUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -589,97 +571,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Temperature left, Temperature right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Temperature left, Temperature right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Temperature left, Temperature right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Temperature left, Temperature right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Temperature other, Temperature tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Temperature left, Temperature right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Temperature other, Temperature tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Temperature left, Temperature right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Temperature other, Temperature tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Temperature otherQuantity)) + if (obj is not Temperature otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Temperature other, Temperature tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Temperature other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Temperature. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Temperature), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Temperature otherQuantity)) throw new ArgumentException("Expected type Temperature.", nameof(obj)); + if (obj is not Temperature otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -691,164 +658,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Temperature other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Temperature to another Temperature with the unit representation . - /// - /// The unit to convert to. - /// A Temperature with the specified unit. - public Temperature ToUnit(TemperatureUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Temperature with the specified unit. - public Temperature ToUnit(TemperatureUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Temperature), Unit, typeof(Temperature), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Temperature)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(TemperatureUnit unit, [NotNullWhen(true)] out Temperature? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Temperature? convertedOrNull = (Unit, unit) switch - { - // TemperatureUnit -> BaseUnit - (TemperatureUnit.DegreeCelsius, TemperatureUnit.Kelvin) => new Temperature(_value + 273.15, TemperatureUnit.Kelvin), - (TemperatureUnit.DegreeDelisle, TemperatureUnit.Kelvin) => new Temperature(_value * -2 / 3 + 373.15, TemperatureUnit.Kelvin), - (TemperatureUnit.DegreeFahrenheit, TemperatureUnit.Kelvin) => new Temperature(_value * 5 / 9 + 459.67 * 5 / 9, TemperatureUnit.Kelvin), - (TemperatureUnit.DegreeNewton, TemperatureUnit.Kelvin) => new Temperature(_value * 100 / 33 + 273.15, TemperatureUnit.Kelvin), - (TemperatureUnit.DegreeRankine, TemperatureUnit.Kelvin) => new Temperature(_value * 5 / 9, TemperatureUnit.Kelvin), - (TemperatureUnit.DegreeReaumur, TemperatureUnit.Kelvin) => new Temperature(_value * 5 / 4 + 273.15, TemperatureUnit.Kelvin), - (TemperatureUnit.DegreeRoemer, TemperatureUnit.Kelvin) => new Temperature(_value * 40 / 21 + 273.15 - 7.5 * 40d / 21, TemperatureUnit.Kelvin), - (TemperatureUnit.MillidegreeCelsius, TemperatureUnit.Kelvin) => new Temperature(_value / 1000 + 273.15, TemperatureUnit.Kelvin), - (TemperatureUnit.SolarTemperature, TemperatureUnit.Kelvin) => new Temperature(_value * 5778, TemperatureUnit.Kelvin), - - // BaseUnit -> TemperatureUnit - (TemperatureUnit.Kelvin, TemperatureUnit.DegreeCelsius) => new Temperature(_value - 273.15, TemperatureUnit.DegreeCelsius), - (TemperatureUnit.Kelvin, TemperatureUnit.DegreeDelisle) => new Temperature((_value - 373.15) * -3 / 2, TemperatureUnit.DegreeDelisle), - (TemperatureUnit.Kelvin, TemperatureUnit.DegreeFahrenheit) => new Temperature((_value - 459.67 * 5 / 9) * 9 / 5, TemperatureUnit.DegreeFahrenheit), - (TemperatureUnit.Kelvin, TemperatureUnit.DegreeNewton) => new Temperature((_value - 273.15) * 33 / 100, TemperatureUnit.DegreeNewton), - (TemperatureUnit.Kelvin, TemperatureUnit.DegreeRankine) => new Temperature(_value * 9 / 5, TemperatureUnit.DegreeRankine), - (TemperatureUnit.Kelvin, TemperatureUnit.DegreeReaumur) => new Temperature((_value - 273.15) * 4 / 5, TemperatureUnit.DegreeReaumur), - (TemperatureUnit.Kelvin, TemperatureUnit.DegreeRoemer) => new Temperature((_value - (273.15 - 7.5 * 40d / 21)) * 21 / 40, TemperatureUnit.DegreeRoemer), - (TemperatureUnit.Kelvin, TemperatureUnit.MillidegreeCelsius) => new Temperature((_value - 273.15) * 1000, TemperatureUnit.MillidegreeCelsius), - (TemperatureUnit.Kelvin, TemperatureUnit.SolarTemperature) => new Temperature(_value / 5778, TemperatureUnit.SolarTemperature), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Temperature ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not TemperatureUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(TemperatureUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(TemperatureUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -863,7 +690,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs index 899b060c28..9bdba85480 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureChangeRate.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct TemperatureChangeRate : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly TemperatureChangeRateUnit? _unit; /// @@ -104,7 +103,7 @@ public static TemperatureChangeRateInfo CreateDefault(Func - /// The for is [T^-1][Θ]. + /// The for is T^-1Θ. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, -1, 0, 1, 0, 0); @@ -119,31 +118,61 @@ public static TemperatureChangeRateInfo CreateDefault(FuncAn of representing the default unit mappings for TemperatureChangeRate. public static IEnumerable> GetDefaultMappings() { - yield return new (TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, "CentidegreeCelsiusPerSecond", "CentidegreesCelsiusPerSecond", BaseUnits.Undefined); - yield return new (TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, "DecadegreeCelsiusPerSecond", "DecadegreesCelsiusPerSecond", BaseUnits.Undefined); - yield return new (TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, "DecidegreeCelsiusPerSecond", "DecidegreesCelsiusPerSecond", BaseUnits.Undefined); - yield return new (TemperatureChangeRateUnit.DegreeCelsiusPerHour, "DegreeCelsiusPerHour", "DegreesCelsiusPerHour", new BaseUnits(time: DurationUnit.Hour, temperature: TemperatureUnit.DegreeCelsius)); - yield return new (TemperatureChangeRateUnit.DegreeCelsiusPerMinute, "DegreeCelsiusPerMinute", "DegreesCelsiusPerMinute", new BaseUnits(time: DurationUnit.Minute, temperature: TemperatureUnit.DegreeCelsius)); + yield return new (TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, "CentidegreeCelsiusPerSecond", "CentidegreesCelsiusPerSecond", BaseUnits.Undefined, + 100 + ); + yield return new (TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, "DecadegreeCelsiusPerSecond", "DecadegreesCelsiusPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 10) + ); + yield return new (TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, "DecidegreeCelsiusPerSecond", "DecidegreesCelsiusPerSecond", BaseUnits.Undefined, + 10 + ); + yield return new (TemperatureChangeRateUnit.DegreeCelsiusPerHour, "DegreeCelsiusPerHour", "DegreesCelsiusPerHour", new BaseUnits(time: DurationUnit.Hour, temperature: TemperatureUnit.DegreeCelsius), + 3600 + ); + yield return new (TemperatureChangeRateUnit.DegreeCelsiusPerMinute, "DegreeCelsiusPerMinute", "DegreesCelsiusPerMinute", new BaseUnits(time: DurationUnit.Minute, temperature: TemperatureUnit.DegreeCelsius), + 60 + ); yield return new (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, "DegreeCelsiusPerSecond", "DegreesCelsiusPerSecond", new BaseUnits(time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius)); - yield return new (TemperatureChangeRateUnit.DegreeFahrenheitPerHour, "DegreeFahrenheitPerHour", "DegreesFahrenheitPerHour", new BaseUnits(time: DurationUnit.Hour, temperature: TemperatureUnit.DegreeFahrenheit)); - yield return new (TemperatureChangeRateUnit.DegreeFahrenheitPerMinute, "DegreeFahrenheitPerMinute", "DegreesFahrenheitPerMinute", new BaseUnits(time: DurationUnit.Minute, temperature: TemperatureUnit.DegreeFahrenheit)); - yield return new (TemperatureChangeRateUnit.DegreeFahrenheitPerSecond, "DegreeFahrenheitPerSecond", "DegreesFahrenheitPerSecond", new BaseUnits(time: DurationUnit.Second, temperature: TemperatureUnit.DegreeFahrenheit)); - yield return new (TemperatureChangeRateUnit.DegreeKelvinPerHour, "DegreeKelvinPerHour", "DegreesKelvinPerHour", new BaseUnits(time: DurationUnit.Hour, temperature: TemperatureUnit.Kelvin)); - yield return new (TemperatureChangeRateUnit.DegreeKelvinPerMinute, "DegreeKelvinPerMinute", "DegreesKelvinPerMinute", new BaseUnits(time: DurationUnit.Minute, temperature: TemperatureUnit.Kelvin)); - yield return new (TemperatureChangeRateUnit.DegreeKelvinPerSecond, "DegreeKelvinPerSecond", "DegreesKelvinPerSecond", new BaseUnits(time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin)); - yield return new (TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, "HectodegreeCelsiusPerSecond", "HectodegreesCelsiusPerSecond", BaseUnits.Undefined); - yield return new (TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, "KilodegreeCelsiusPerSecond", "KilodegreesCelsiusPerSecond", new BaseUnits(time: DurationUnit.Millisecond, temperature: TemperatureUnit.DegreeCelsius)); - yield return new (TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, "MicrodegreeCelsiusPerSecond", "MicrodegreesCelsiusPerSecond", BaseUnits.Undefined); - yield return new (TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, "MillidegreeCelsiusPerSecond", "MillidegreesCelsiusPerSecond", BaseUnits.Undefined); - yield return new (TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, "NanodegreeCelsiusPerSecond", "NanodegreesCelsiusPerSecond", BaseUnits.Undefined); + yield return new (TemperatureChangeRateUnit.DegreeFahrenheitPerHour, "DegreeFahrenheitPerHour", "DegreesFahrenheitPerHour", new BaseUnits(time: DurationUnit.Hour, temperature: TemperatureUnit.DegreeFahrenheit), + 6480 + ); + yield return new (TemperatureChangeRateUnit.DegreeFahrenheitPerMinute, "DegreeFahrenheitPerMinute", "DegreesFahrenheitPerMinute", new BaseUnits(time: DurationUnit.Minute, temperature: TemperatureUnit.DegreeFahrenheit), + 108 + ); + yield return new (TemperatureChangeRateUnit.DegreeFahrenheitPerSecond, "DegreeFahrenheitPerSecond", "DegreesFahrenheitPerSecond", new BaseUnits(time: DurationUnit.Second, temperature: TemperatureUnit.DegreeFahrenheit), + new QuantityValue(9, 5) + ); + yield return new (TemperatureChangeRateUnit.DegreeKelvinPerHour, "DegreeKelvinPerHour", "DegreesKelvinPerHour", new BaseUnits(time: DurationUnit.Hour, temperature: TemperatureUnit.Kelvin), + 3600 + ); + yield return new (TemperatureChangeRateUnit.DegreeKelvinPerMinute, "DegreeKelvinPerMinute", "DegreesKelvinPerMinute", new BaseUnits(time: DurationUnit.Minute, temperature: TemperatureUnit.Kelvin), + 60 + ); + yield return new (TemperatureChangeRateUnit.DegreeKelvinPerSecond, "DegreeKelvinPerSecond", "DegreesKelvinPerSecond", new BaseUnits(time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin), + 1 + ); + yield return new (TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, "HectodegreeCelsiusPerSecond", "HectodegreesCelsiusPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 100) + ); + yield return new (TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, "KilodegreeCelsiusPerSecond", "KilodegreesCelsiusPerSecond", new BaseUnits(time: DurationUnit.Millisecond, temperature: TemperatureUnit.DegreeCelsius), + new QuantityValue(1, 1000) + ); + yield return new (TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, "MicrodegreeCelsiusPerSecond", "MicrodegreesCelsiusPerSecond", BaseUnits.Undefined, + 1000000 + ); + yield return new (TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, "MillidegreeCelsiusPerSecond", "MillidegreesCelsiusPerSecond", BaseUnits.Undefined, + 1000 + ); + yield return new (TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, "NanodegreeCelsiusPerSecond", "NanodegreesCelsiusPerSecond", BaseUnits.Undefined, + 1000000000 + ); } } static TemperatureChangeRate() { - Info = TemperatureChangeRateInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(TemperatureChangeRateInfo.CreateDefault); } /// @@ -151,7 +180,7 @@ static TemperatureChangeRate() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public TemperatureChangeRate(double value, TemperatureChangeRateUnit unit) + public TemperatureChangeRate(QuantityValue value, TemperatureChangeRateUnit unit) { _value = value; _unit = unit; @@ -165,7 +194,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -176,7 +205,8 @@ public TemperatureChangeRate(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -205,10 +235,8 @@ public TemperatureChangeRate(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public TemperatureChangeRateUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -247,140 +275,94 @@ public TemperatureChangeRate(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); + public QuantityValue CentidegreesCelsiusPerSecond => this.As(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecadegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); + public QuantityValue DecadegreesCelsiusPerSecond => this.As(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); + public QuantityValue DecidegreesCelsiusPerSecond => this.As(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesCelsiusPerHour => As(TemperatureChangeRateUnit.DegreeCelsiusPerHour); + public QuantityValue DegreesCelsiusPerHour => this.As(TemperatureChangeRateUnit.DegreeCelsiusPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesCelsiusPerMinute => As(TemperatureChangeRateUnit.DegreeCelsiusPerMinute); + public QuantityValue DegreesCelsiusPerMinute => this.As(TemperatureChangeRateUnit.DegreeCelsiusPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.DegreeCelsiusPerSecond); + public QuantityValue DegreesCelsiusPerSecond => this.As(TemperatureChangeRateUnit.DegreeCelsiusPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesFahrenheitPerHour => As(TemperatureChangeRateUnit.DegreeFahrenheitPerHour); + public QuantityValue DegreesFahrenheitPerHour => this.As(TemperatureChangeRateUnit.DegreeFahrenheitPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesFahrenheitPerMinute => As(TemperatureChangeRateUnit.DegreeFahrenheitPerMinute); + public QuantityValue DegreesFahrenheitPerMinute => this.As(TemperatureChangeRateUnit.DegreeFahrenheitPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesFahrenheitPerSecond => As(TemperatureChangeRateUnit.DegreeFahrenheitPerSecond); + public QuantityValue DegreesFahrenheitPerSecond => this.As(TemperatureChangeRateUnit.DegreeFahrenheitPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesKelvinPerHour => As(TemperatureChangeRateUnit.DegreeKelvinPerHour); + public QuantityValue DegreesKelvinPerHour => this.As(TemperatureChangeRateUnit.DegreeKelvinPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesKelvinPerMinute => As(TemperatureChangeRateUnit.DegreeKelvinPerMinute); + public QuantityValue DegreesKelvinPerMinute => this.As(TemperatureChangeRateUnit.DegreeKelvinPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesKelvinPerSecond => As(TemperatureChangeRateUnit.DegreeKelvinPerSecond); + public QuantityValue DegreesKelvinPerSecond => this.As(TemperatureChangeRateUnit.DegreeKelvinPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HectodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); + public QuantityValue HectodegreesCelsiusPerSecond => this.As(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); + public QuantityValue KilodegreesCelsiusPerSecond => this.As(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); + public QuantityValue MicrodegreesCelsiusPerSecond => this.As(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillidegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); + public QuantityValue MillidegreesCelsiusPerSecond => this.As(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanodegreesCelsiusPerSecond => As(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); + public QuantityValue NanodegreesCelsiusPerSecond => this.As(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: TemperatureChangeRateUnit -> BaseUnit - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerHour, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerMinute, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeFahrenheitPerHour, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeFahrenheitPerMinute, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeFahrenheitPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeKelvinPerHour, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeKelvinPerMinute, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeKelvinPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> TemperatureChangeRateUnit - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerHour, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerHour)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerMinute, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeCelsiusPerMinute)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeFahrenheitPerHour, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeFahrenheitPerHour)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeFahrenheitPerMinute, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeFahrenheitPerMinute)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeFahrenheitPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeFahrenheitPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeKelvinPerHour, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeKelvinPerHour)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeKelvinPerMinute, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeKelvinPerMinute)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeKelvinPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.DegreeKelvinPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond)); - unitConverter.SetConversionFunction(TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, quantity => quantity.ToUnit(TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond)); - } - /// /// Get unit abbreviation string. /// @@ -409,7 +391,7 @@ public static string GetAbbreviation(TemperatureChangeRateUnit unit, IFormatProv /// /// Creates a from . /// - public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(double value) + public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(QuantityValue value) { return new TemperatureChangeRate(value, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond); } @@ -417,7 +399,7 @@ public static TemperatureChangeRate FromCentidegreesCelsiusPerSecond(double valu /// /// Creates a from . /// - public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(double value) + public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(QuantityValue value) { return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond); } @@ -425,7 +407,7 @@ public static TemperatureChangeRate FromDecadegreesCelsiusPerSecond(double value /// /// Creates a from . /// - public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(double value) + public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(QuantityValue value) { return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond); } @@ -433,7 +415,7 @@ public static TemperatureChangeRate FromDecidegreesCelsiusPerSecond(double value /// /// Creates a from . /// - public static TemperatureChangeRate FromDegreesCelsiusPerHour(double value) + public static TemperatureChangeRate FromDegreesCelsiusPerHour(QuantityValue value) { return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerHour); } @@ -441,7 +423,7 @@ public static TemperatureChangeRate FromDegreesCelsiusPerHour(double value) /// /// Creates a from . /// - public static TemperatureChangeRate FromDegreesCelsiusPerMinute(double value) + public static TemperatureChangeRate FromDegreesCelsiusPerMinute(QuantityValue value) { return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerMinute); } @@ -449,7 +431,7 @@ public static TemperatureChangeRate FromDegreesCelsiusPerMinute(double value) /// /// Creates a from . /// - public static TemperatureChangeRate FromDegreesCelsiusPerSecond(double value) + public static TemperatureChangeRate FromDegreesCelsiusPerSecond(QuantityValue value) { return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeCelsiusPerSecond); } @@ -457,7 +439,7 @@ public static TemperatureChangeRate FromDegreesCelsiusPerSecond(double value) /// /// Creates a from . /// - public static TemperatureChangeRate FromDegreesFahrenheitPerHour(double value) + public static TemperatureChangeRate FromDegreesFahrenheitPerHour(QuantityValue value) { return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeFahrenheitPerHour); } @@ -465,7 +447,7 @@ public static TemperatureChangeRate FromDegreesFahrenheitPerHour(double value) /// /// Creates a from . /// - public static TemperatureChangeRate FromDegreesFahrenheitPerMinute(double value) + public static TemperatureChangeRate FromDegreesFahrenheitPerMinute(QuantityValue value) { return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeFahrenheitPerMinute); } @@ -473,7 +455,7 @@ public static TemperatureChangeRate FromDegreesFahrenheitPerMinute(double value) /// /// Creates a from . /// - public static TemperatureChangeRate FromDegreesFahrenheitPerSecond(double value) + public static TemperatureChangeRate FromDegreesFahrenheitPerSecond(QuantityValue value) { return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeFahrenheitPerSecond); } @@ -481,7 +463,7 @@ public static TemperatureChangeRate FromDegreesFahrenheitPerSecond(double value) /// /// Creates a from . /// - public static TemperatureChangeRate FromDegreesKelvinPerHour(double value) + public static TemperatureChangeRate FromDegreesKelvinPerHour(QuantityValue value) { return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeKelvinPerHour); } @@ -489,7 +471,7 @@ public static TemperatureChangeRate FromDegreesKelvinPerHour(double value) /// /// Creates a from . /// - public static TemperatureChangeRate FromDegreesKelvinPerMinute(double value) + public static TemperatureChangeRate FromDegreesKelvinPerMinute(QuantityValue value) { return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeKelvinPerMinute); } @@ -497,7 +479,7 @@ public static TemperatureChangeRate FromDegreesKelvinPerMinute(double value) /// /// Creates a from . /// - public static TemperatureChangeRate FromDegreesKelvinPerSecond(double value) + public static TemperatureChangeRate FromDegreesKelvinPerSecond(QuantityValue value) { return new TemperatureChangeRate(value, TemperatureChangeRateUnit.DegreeKelvinPerSecond); } @@ -505,7 +487,7 @@ public static TemperatureChangeRate FromDegreesKelvinPerSecond(double value) /// /// Creates a from . /// - public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(double value) + public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(QuantityValue value) { return new TemperatureChangeRate(value, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond); } @@ -513,7 +495,7 @@ public static TemperatureChangeRate FromHectodegreesCelsiusPerSecond(double valu /// /// Creates a from . /// - public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(double value) + public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(QuantityValue value) { return new TemperatureChangeRate(value, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond); } @@ -521,7 +503,7 @@ public static TemperatureChangeRate FromKilodegreesCelsiusPerSecond(double value /// /// Creates a from . /// - public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(double value) + public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(QuantityValue value) { return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond); } @@ -529,7 +511,7 @@ public static TemperatureChangeRate FromMicrodegreesCelsiusPerSecond(double valu /// /// Creates a from . /// - public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(double value) + public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(QuantityValue value) { return new TemperatureChangeRate(value, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond); } @@ -537,7 +519,7 @@ public static TemperatureChangeRate FromMillidegreesCelsiusPerSecond(double valu /// /// Creates a from . /// - public static TemperatureChangeRate FromNanodegreesCelsiusPerSecond(double value) + public static TemperatureChangeRate FromNanodegreesCelsiusPerSecond(QuantityValue value) { return new TemperatureChangeRate(value, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond); } @@ -548,7 +530,7 @@ public static TemperatureChangeRate FromNanodegreesCelsiusPerSecond(double value /// Value to convert from. /// Unit to convert from. /// TemperatureChangeRate unit value. - public static TemperatureChangeRate From(double value, TemperatureChangeRateUnit fromUnit) + public static TemperatureChangeRate From(QuantityValue value, TemperatureChangeRateUnit fromUnit) { return new TemperatureChangeRate(value, fromUnit); } @@ -609,10 +591,7 @@ public static TemperatureChangeRate Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static TemperatureChangeRate Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -640,11 +619,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out TemperatureChang /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out TemperatureChangeRate result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -665,7 +640,7 @@ public static TemperatureChangeRateUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -676,7 +651,7 @@ public static TemperatureChangeRateUnit ParseUnit(string str, IFormatProvider? p return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out TemperatureChangeRateUnit unit) { return TryParseUnit(str, null, out unit); @@ -691,7 +666,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out TemperatureC /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out TemperatureChangeRateUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -710,35 +685,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static TemperatureChangeRate operator +(TemperatureChangeRate left, TemperatureChangeRate right) { - return new TemperatureChangeRate(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new TemperatureChangeRate(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static TemperatureChangeRate operator -(TemperatureChangeRate left, TemperatureChangeRate right) { - return new TemperatureChangeRate(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new TemperatureChangeRate(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -760,97 +735,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(TemperatureChangeRate left, TemperatureChangeRate right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(TemperatureChangeRate left, TemperatureChangeRate right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(TemperatureChangeRate left, TemperatureChangeRate right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(TemperatureChangeRate left, TemperatureChangeRate right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(TemperatureChangeRate other, TemperatureChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(TemperatureChangeRate left, TemperatureChangeRate right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(TemperatureChangeRate other, TemperatureChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(TemperatureChangeRate left, TemperatureChangeRate right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(TemperatureChangeRate other, TemperatureChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is TemperatureChangeRate otherQuantity)) + if (obj is not TemperatureChangeRate otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(TemperatureChangeRate other, TemperatureChangeRate tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(TemperatureChangeRate other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current TemperatureChangeRate. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(TemperatureChangeRate), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is TemperatureChangeRate otherQuantity)) throw new ArgumentException("Expected type TemperatureChangeRate.", nameof(obj)); + if (obj is not TemperatureChangeRate otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -862,178 +822,24 @@ public int CompareTo(object? obj) /// public int CompareTo(TemperatureChangeRate other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureChangeRateUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this TemperatureChangeRate to another TemperatureChangeRate with the unit representation . - /// - /// The unit to convert to. - /// A TemperatureChangeRate with the specified unit. - public TemperatureChangeRate ToUnit(TemperatureChangeRateUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A TemperatureChangeRate with the specified unit. - public TemperatureChangeRate ToUnit(TemperatureChangeRateUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(TemperatureChangeRate), Unit, typeof(TemperatureChangeRate), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (TemperatureChangeRate)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(TemperatureChangeRateUnit unit, [NotNullWhen(true)] out TemperatureChangeRate? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - TemperatureChangeRate? convertedOrNull = (Unit, unit) switch - { - // TemperatureChangeRateUnit -> BaseUnit - (TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) * 1e-2d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) * 1e1d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) * 1e-1d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.DegreeCelsiusPerHour, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate(_value / 3600, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.DegreeCelsiusPerMinute, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate(_value / 60, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.DegreeFahrenheitPerHour, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate(_value * 5 / 9 / 3600, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.DegreeFahrenheitPerMinute, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate(_value * 5 / 9 / 60, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.DegreeFahrenheitPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate(_value * 5 / 9, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.DegreeKelvinPerHour, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate(_value / 3600, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.DegreeKelvinPerMinute, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate(_value / 60, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.DegreeKelvinPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate(_value, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) * 1e2d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) * 1e3d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) * 1e-6d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) * 1e-3d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) * 1e-9d, TemperatureChangeRateUnit.DegreeCelsiusPerSecond), - - // BaseUnit -> TemperatureChangeRateUnit - (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) / 1e-2d, TemperatureChangeRateUnit.CentidegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) / 1e1d, TemperatureChangeRateUnit.DecadegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) / 1e-1d, TemperatureChangeRateUnit.DecidegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerHour) => new TemperatureChangeRate(_value * 3600, TemperatureChangeRateUnit.DegreeCelsiusPerHour), - (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeCelsiusPerMinute) => new TemperatureChangeRate(_value * 60, TemperatureChangeRateUnit.DegreeCelsiusPerMinute), - (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeFahrenheitPerHour) => new TemperatureChangeRate(_value * 9 / 5 * 3600, TemperatureChangeRateUnit.DegreeFahrenheitPerHour), - (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeFahrenheitPerMinute) => new TemperatureChangeRate(_value * 9 / 5 * 60, TemperatureChangeRateUnit.DegreeFahrenheitPerMinute), - (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeFahrenheitPerSecond) => new TemperatureChangeRate(_value * 9 / 5, TemperatureChangeRateUnit.DegreeFahrenheitPerSecond), - (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeKelvinPerHour) => new TemperatureChangeRate(_value * 3600, TemperatureChangeRateUnit.DegreeKelvinPerHour), - (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeKelvinPerMinute) => new TemperatureChangeRate(_value * 60, TemperatureChangeRateUnit.DegreeKelvinPerMinute), - (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.DegreeKelvinPerSecond) => new TemperatureChangeRate(_value, TemperatureChangeRateUnit.DegreeKelvinPerSecond), - (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) / 1e2d, TemperatureChangeRateUnit.HectodegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) / 1e3d, TemperatureChangeRateUnit.KilodegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) / 1e-6d, TemperatureChangeRateUnit.MicrodegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) / 1e-3d, TemperatureChangeRateUnit.MillidegreeCelsiusPerSecond), - (TemperatureChangeRateUnit.DegreeCelsiusPerSecond, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond) => new TemperatureChangeRate((_value) / 1e-9d, TemperatureChangeRateUnit.NanodegreeCelsiusPerSecond), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public TemperatureChangeRate ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not TemperatureChangeRateUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureChangeRateUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(TemperatureChangeRateUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(TemperatureChangeRateUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1048,7 +854,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs index 203b2b2e4c..61fbcf592c 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureDelta.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// Difference between two temperatures. The conversions are different than for Temperature. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct TemperatureDelta : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -59,13 +58,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly TemperatureDeltaUnit? _unit; /// @@ -110,7 +109,7 @@ public static TemperatureDeltaInfo CreateDefault(Func - /// The for is [Θ]. + /// The for is Θ. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, 0, 0, 0, 1, 0, 0); @@ -125,23 +124,37 @@ public static TemperatureDeltaInfo CreateDefault(FuncAn of representing the default unit mappings for TemperatureDelta. public static IEnumerable> GetDefaultMappings() { - yield return new (TemperatureDeltaUnit.DegreeCelsius, "DegreeCelsius", "DegreesCelsius", new BaseUnits(temperature: TemperatureUnit.DegreeCelsius)); - yield return new (TemperatureDeltaUnit.DegreeDelisle, "DegreeDelisle", "DegreesDelisle", new BaseUnits(temperature: TemperatureUnit.DegreeDelisle)); - yield return new (TemperatureDeltaUnit.DegreeFahrenheit, "DegreeFahrenheit", "DegreesFahrenheit", new BaseUnits(temperature: TemperatureUnit.DegreeFahrenheit)); - yield return new (TemperatureDeltaUnit.DegreeNewton, "DegreeNewton", "DegreesNewton", new BaseUnits(temperature: TemperatureUnit.DegreeNewton)); - yield return new (TemperatureDeltaUnit.DegreeRankine, "DegreeRankine", "DegreesRankine", new BaseUnits(temperature: TemperatureUnit.DegreeRankine)); - yield return new (TemperatureDeltaUnit.DegreeReaumur, "DegreeReaumur", "DegreesReaumur", new BaseUnits(temperature: TemperatureUnit.DegreeReaumur)); - yield return new (TemperatureDeltaUnit.DegreeRoemer, "DegreeRoemer", "DegreesRoemer", new BaseUnits(temperature: TemperatureUnit.DegreeRoemer)); + yield return new (TemperatureDeltaUnit.DegreeCelsius, "DegreeCelsius", "DegreesCelsius", new BaseUnits(temperature: TemperatureUnit.DegreeCelsius), + 1 + ); + yield return new (TemperatureDeltaUnit.DegreeDelisle, "DegreeDelisle", "DegreesDelisle", new BaseUnits(temperature: TemperatureUnit.DegreeDelisle), + new QuantityValue(-3, 2) + ); + yield return new (TemperatureDeltaUnit.DegreeFahrenheit, "DegreeFahrenheit", "DegreesFahrenheit", new BaseUnits(temperature: TemperatureUnit.DegreeFahrenheit), + new QuantityValue(9, 5) + ); + yield return new (TemperatureDeltaUnit.DegreeNewton, "DegreeNewton", "DegreesNewton", new BaseUnits(temperature: TemperatureUnit.DegreeNewton), + new QuantityValue(33, 100) + ); + yield return new (TemperatureDeltaUnit.DegreeRankine, "DegreeRankine", "DegreesRankine", new BaseUnits(temperature: TemperatureUnit.DegreeRankine), + new QuantityValue(9, 5) + ); + yield return new (TemperatureDeltaUnit.DegreeReaumur, "DegreeReaumur", "DegreesReaumur", new BaseUnits(temperature: TemperatureUnit.DegreeReaumur), + new QuantityValue(4, 5) + ); + yield return new (TemperatureDeltaUnit.DegreeRoemer, "DegreeRoemer", "DegreesRoemer", new BaseUnits(temperature: TemperatureUnit.DegreeRoemer), + new QuantityValue(21, 40) + ); yield return new (TemperatureDeltaUnit.Kelvin, "Kelvin", "Kelvins", new BaseUnits(temperature: TemperatureUnit.Kelvin)); - yield return new (TemperatureDeltaUnit.MillidegreeCelsius, "MillidegreeCelsius", "MillidegreesCelsius", BaseUnits.Undefined); + yield return new (TemperatureDeltaUnit.MillidegreeCelsius, "MillidegreeCelsius", "MillidegreesCelsius", BaseUnits.Undefined, + 1000 + ); } } static TemperatureDelta() { - Info = TemperatureDeltaInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(TemperatureDeltaInfo.CreateDefault); } /// @@ -149,7 +162,7 @@ static TemperatureDelta() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public TemperatureDelta(double value, TemperatureDeltaUnit unit) + public TemperatureDelta(QuantityValue value, TemperatureDeltaUnit unit) { _value = value; _unit = unit; @@ -163,7 +176,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -174,7 +187,8 @@ public TemperatureDelta(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -203,10 +217,8 @@ public TemperatureDelta(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public TemperatureDeltaUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -245,84 +257,54 @@ public TemperatureDelta(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesCelsius => As(TemperatureDeltaUnit.DegreeCelsius); + public QuantityValue DegreesCelsius => this.As(TemperatureDeltaUnit.DegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesDelisle => As(TemperatureDeltaUnit.DegreeDelisle); + public QuantityValue DegreesDelisle => this.As(TemperatureDeltaUnit.DegreeDelisle); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesFahrenheit => As(TemperatureDeltaUnit.DegreeFahrenheit); + public QuantityValue DegreesFahrenheit => this.As(TemperatureDeltaUnit.DegreeFahrenheit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesNewton => As(TemperatureDeltaUnit.DegreeNewton); + public QuantityValue DegreesNewton => this.As(TemperatureDeltaUnit.DegreeNewton); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesRankine => As(TemperatureDeltaUnit.DegreeRankine); + public QuantityValue DegreesRankine => this.As(TemperatureDeltaUnit.DegreeRankine); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesReaumur => As(TemperatureDeltaUnit.DegreeReaumur); + public QuantityValue DegreesReaumur => this.As(TemperatureDeltaUnit.DegreeReaumur); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesRoemer => As(TemperatureDeltaUnit.DegreeRoemer); + public QuantityValue DegreesRoemer => this.As(TemperatureDeltaUnit.DegreeRoemer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kelvins => As(TemperatureDeltaUnit.Kelvin); + public QuantityValue Kelvins => this.As(TemperatureDeltaUnit.Kelvin); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillidegreesCelsius => As(TemperatureDeltaUnit.MillidegreeCelsius); + public QuantityValue MillidegreesCelsius => this.As(TemperatureDeltaUnit.MillidegreeCelsius); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: TemperatureDeltaUnit -> BaseUnit - unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeCelsius, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToUnit(TemperatureDeltaUnit.Kelvin)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeDelisle, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToUnit(TemperatureDeltaUnit.Kelvin)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeFahrenheit, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToUnit(TemperatureDeltaUnit.Kelvin)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeNewton, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToUnit(TemperatureDeltaUnit.Kelvin)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeRankine, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToUnit(TemperatureDeltaUnit.Kelvin)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeReaumur, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToUnit(TemperatureDeltaUnit.Kelvin)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.DegreeRoemer, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToUnit(TemperatureDeltaUnit.Kelvin)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.MillidegreeCelsius, TemperatureDeltaUnit.Kelvin, quantity => quantity.ToUnit(TemperatureDeltaUnit.Kelvin)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.Kelvin, quantity => quantity); - - // Register in unit converter: BaseUnit -> TemperatureDeltaUnit - unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeCelsius, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeCelsius)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeDelisle, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeDelisle)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeFahrenheit, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeFahrenheit)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeNewton, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeNewton)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeRankine, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeRankine)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeReaumur, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeReaumur)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeRoemer, quantity => quantity.ToUnit(TemperatureDeltaUnit.DegreeRoemer)); - unitConverter.SetConversionFunction(TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.MillidegreeCelsius, quantity => quantity.ToUnit(TemperatureDeltaUnit.MillidegreeCelsius)); - } - /// /// Get unit abbreviation string. /// @@ -351,7 +333,7 @@ public static string GetAbbreviation(TemperatureDeltaUnit unit, IFormatProvider? /// /// Creates a from . /// - public static TemperatureDelta FromDegreesCelsius(double value) + public static TemperatureDelta FromDegreesCelsius(QuantityValue value) { return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeCelsius); } @@ -359,7 +341,7 @@ public static TemperatureDelta FromDegreesCelsius(double value) /// /// Creates a from . /// - public static TemperatureDelta FromDegreesDelisle(double value) + public static TemperatureDelta FromDegreesDelisle(QuantityValue value) { return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeDelisle); } @@ -367,7 +349,7 @@ public static TemperatureDelta FromDegreesDelisle(double value) /// /// Creates a from . /// - public static TemperatureDelta FromDegreesFahrenheit(double value) + public static TemperatureDelta FromDegreesFahrenheit(QuantityValue value) { return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeFahrenheit); } @@ -375,7 +357,7 @@ public static TemperatureDelta FromDegreesFahrenheit(double value) /// /// Creates a from . /// - public static TemperatureDelta FromDegreesNewton(double value) + public static TemperatureDelta FromDegreesNewton(QuantityValue value) { return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeNewton); } @@ -383,7 +365,7 @@ public static TemperatureDelta FromDegreesNewton(double value) /// /// Creates a from . /// - public static TemperatureDelta FromDegreesRankine(double value) + public static TemperatureDelta FromDegreesRankine(QuantityValue value) { return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRankine); } @@ -391,7 +373,7 @@ public static TemperatureDelta FromDegreesRankine(double value) /// /// Creates a from . /// - public static TemperatureDelta FromDegreesReaumur(double value) + public static TemperatureDelta FromDegreesReaumur(QuantityValue value) { return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeReaumur); } @@ -399,7 +381,7 @@ public static TemperatureDelta FromDegreesReaumur(double value) /// /// Creates a from . /// - public static TemperatureDelta FromDegreesRoemer(double value) + public static TemperatureDelta FromDegreesRoemer(QuantityValue value) { return new TemperatureDelta(value, TemperatureDeltaUnit.DegreeRoemer); } @@ -407,7 +389,7 @@ public static TemperatureDelta FromDegreesRoemer(double value) /// /// Creates a from . /// - public static TemperatureDelta FromKelvins(double value) + public static TemperatureDelta FromKelvins(QuantityValue value) { return new TemperatureDelta(value, TemperatureDeltaUnit.Kelvin); } @@ -415,7 +397,7 @@ public static TemperatureDelta FromKelvins(double value) /// /// Creates a from . /// - public static TemperatureDelta FromMillidegreesCelsius(double value) + public static TemperatureDelta FromMillidegreesCelsius(QuantityValue value) { return new TemperatureDelta(value, TemperatureDeltaUnit.MillidegreeCelsius); } @@ -426,7 +408,7 @@ public static TemperatureDelta FromMillidegreesCelsius(double value) /// Value to convert from. /// Unit to convert from. /// TemperatureDelta unit value. - public static TemperatureDelta From(double value, TemperatureDeltaUnit fromUnit) + public static TemperatureDelta From(QuantityValue value, TemperatureDeltaUnit fromUnit) { return new TemperatureDelta(value, fromUnit); } @@ -487,10 +469,7 @@ public static TemperatureDelta Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static TemperatureDelta Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -518,11 +497,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out TemperatureDelta /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out TemperatureDelta result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -543,7 +518,7 @@ public static TemperatureDeltaUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -554,7 +529,7 @@ public static TemperatureDeltaUnit ParseUnit(string str, IFormatProvider? provid return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out TemperatureDeltaUnit unit) { return TryParseUnit(str, null, out unit); @@ -569,7 +544,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out TemperatureD /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out TemperatureDeltaUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -588,35 +563,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static TemperatureDelta operator +(TemperatureDelta left, TemperatureDelta right) { - return new TemperatureDelta(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new TemperatureDelta(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static TemperatureDelta operator -(TemperatureDelta left, TemperatureDelta right) { - return new TemperatureDelta(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new TemperatureDelta(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -674,97 +649,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(TemperatureDelta left, TemperatureDelta right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(TemperatureDelta left, TemperatureDelta right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(TemperatureDelta left, TemperatureDelta right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(TemperatureDelta left, TemperatureDelta right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(TemperatureDelta other, TemperatureDelta tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(TemperatureDelta left, TemperatureDelta right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(TemperatureDelta other, TemperatureDelta tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(TemperatureDelta left, TemperatureDelta right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(TemperatureDelta other, TemperatureDelta tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is TemperatureDelta otherQuantity)) + if (obj is not TemperatureDelta otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(TemperatureDelta other, TemperatureDelta tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(TemperatureDelta other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current TemperatureDelta. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(TemperatureDelta), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is TemperatureDelta otherQuantity)) throw new ArgumentException("Expected type TemperatureDelta.", nameof(obj)); + if (obj is not TemperatureDelta otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -776,162 +736,24 @@ public int CompareTo(object? obj) /// public int CompareTo(TemperatureDelta other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureDeltaUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this TemperatureDelta to another TemperatureDelta with the unit representation . - /// - /// The unit to convert to. - /// A TemperatureDelta with the specified unit. - public TemperatureDelta ToUnit(TemperatureDeltaUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A TemperatureDelta with the specified unit. - public TemperatureDelta ToUnit(TemperatureDeltaUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(TemperatureDelta), Unit, typeof(TemperatureDelta), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (TemperatureDelta)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(TemperatureDeltaUnit unit, [NotNullWhen(true)] out TemperatureDelta? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - TemperatureDelta? convertedOrNull = (Unit, unit) switch - { - // TemperatureDeltaUnit -> BaseUnit - (TemperatureDeltaUnit.DegreeCelsius, TemperatureDeltaUnit.Kelvin) => new TemperatureDelta(_value, TemperatureDeltaUnit.Kelvin), - (TemperatureDeltaUnit.DegreeDelisle, TemperatureDeltaUnit.Kelvin) => new TemperatureDelta(_value * -2 / 3, TemperatureDeltaUnit.Kelvin), - (TemperatureDeltaUnit.DegreeFahrenheit, TemperatureDeltaUnit.Kelvin) => new TemperatureDelta(_value * 5 / 9, TemperatureDeltaUnit.Kelvin), - (TemperatureDeltaUnit.DegreeNewton, TemperatureDeltaUnit.Kelvin) => new TemperatureDelta(_value * 100 / 33, TemperatureDeltaUnit.Kelvin), - (TemperatureDeltaUnit.DegreeRankine, TemperatureDeltaUnit.Kelvin) => new TemperatureDelta(_value * 5 / 9, TemperatureDeltaUnit.Kelvin), - (TemperatureDeltaUnit.DegreeReaumur, TemperatureDeltaUnit.Kelvin) => new TemperatureDelta(_value * 5 / 4, TemperatureDeltaUnit.Kelvin), - (TemperatureDeltaUnit.DegreeRoemer, TemperatureDeltaUnit.Kelvin) => new TemperatureDelta(_value * 40 / 21, TemperatureDeltaUnit.Kelvin), - (TemperatureDeltaUnit.MillidegreeCelsius, TemperatureDeltaUnit.Kelvin) => new TemperatureDelta((_value) * 1e-3d, TemperatureDeltaUnit.Kelvin), - - // BaseUnit -> TemperatureDeltaUnit - (TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeCelsius) => new TemperatureDelta(_value, TemperatureDeltaUnit.DegreeCelsius), - (TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeDelisle) => new TemperatureDelta(_value * -3 / 2, TemperatureDeltaUnit.DegreeDelisle), - (TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeFahrenheit) => new TemperatureDelta(_value * 9 / 5, TemperatureDeltaUnit.DegreeFahrenheit), - (TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeNewton) => new TemperatureDelta(_value * 33 / 100, TemperatureDeltaUnit.DegreeNewton), - (TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeRankine) => new TemperatureDelta(_value * 9 / 5, TemperatureDeltaUnit.DegreeRankine), - (TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeReaumur) => new TemperatureDelta(_value * 4 / 5, TemperatureDeltaUnit.DegreeReaumur), - (TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.DegreeRoemer) => new TemperatureDelta(_value * 21 / 40, TemperatureDeltaUnit.DegreeRoemer), - (TemperatureDeltaUnit.Kelvin, TemperatureDeltaUnit.MillidegreeCelsius) => new TemperatureDelta((_value) / 1e-3d, TemperatureDeltaUnit.MillidegreeCelsius), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public TemperatureDelta ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not TemperatureDeltaUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureDeltaUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(TemperatureDeltaUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(TemperatureDeltaUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -946,7 +768,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs b/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs index 1379e6b593..c1267343ee 100644 --- a/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/TemperatureGradient.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct TemperatureGradient : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly TemperatureGradientUnit? _unit; /// @@ -104,7 +103,7 @@ public static TemperatureGradientInfo CreateDefault(Func - /// The for is [L^-1][Θ]. + /// The for is L^-1Θ. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 0, 0, 0, 1, 0, 0); @@ -119,18 +118,22 @@ public static TemperatureGradientInfo CreateDefault(FuncAn of representing the default unit mappings for TemperatureGradient. public static IEnumerable> GetDefaultMappings() { - yield return new (TemperatureGradientUnit.DegreeCelsiusPerKilometer, "DegreeCelsiusPerKilometer", "DegreesCelsiusPerKilometer", new BaseUnits(length: LengthUnit.Kilometer, temperature: TemperatureUnit.DegreeCelsius)); - yield return new (TemperatureGradientUnit.DegreeCelsiusPerMeter, "DegreeCelsiusPerMeter", "DegreesCelsiusPerMeter", new BaseUnits(length: LengthUnit.Meter, temperature: TemperatureUnit.DegreeCelsius)); - yield return new (TemperatureGradientUnit.DegreeFahrenheitPerFoot, "DegreeFahrenheitPerFoot", "DegreesFahrenheitPerFoot", new BaseUnits(length: LengthUnit.Foot, temperature: TemperatureUnit.DegreeFahrenheit)); + yield return new (TemperatureGradientUnit.DegreeCelsiusPerKilometer, "DegreeCelsiusPerKilometer", "DegreesCelsiusPerKilometer", new BaseUnits(length: LengthUnit.Kilometer, temperature: TemperatureUnit.DegreeCelsius), + 1000 + ); + yield return new (TemperatureGradientUnit.DegreeCelsiusPerMeter, "DegreeCelsiusPerMeter", "DegreesCelsiusPerMeter", new BaseUnits(length: LengthUnit.Meter, temperature: TemperatureUnit.DegreeCelsius), + 1 + ); + yield return new (TemperatureGradientUnit.DegreeFahrenheitPerFoot, "DegreeFahrenheitPerFoot", "DegreesFahrenheitPerFoot", new BaseUnits(length: LengthUnit.Foot, temperature: TemperatureUnit.DegreeFahrenheit), + new QuantityValue(3429, 6250) + ); yield return new (TemperatureGradientUnit.KelvinPerMeter, "KelvinPerMeter", "KelvinsPerMeter", new BaseUnits(length: LengthUnit.Meter, temperature: TemperatureUnit.Kelvin)); } } static TemperatureGradient() { - Info = TemperatureGradientInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(TemperatureGradientInfo.CreateDefault); } /// @@ -138,7 +141,7 @@ static TemperatureGradient() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public TemperatureGradient(double value, TemperatureGradientUnit unit) + public TemperatureGradient(QuantityValue value, TemperatureGradientUnit unit) { _value = value; _unit = unit; @@ -152,7 +155,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -163,7 +166,8 @@ public TemperatureGradient(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -192,10 +196,8 @@ public TemperatureGradient(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public TemperatureGradientUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -234,49 +236,29 @@ public TemperatureGradient(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesCelsiusPerKilometer => As(TemperatureGradientUnit.DegreeCelsiusPerKilometer); + public QuantityValue DegreesCelsiusPerKilometer => this.As(TemperatureGradientUnit.DegreeCelsiusPerKilometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesCelsiusPerMeter => As(TemperatureGradientUnit.DegreeCelsiusPerMeter); + public QuantityValue DegreesCelsiusPerMeter => this.As(TemperatureGradientUnit.DegreeCelsiusPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesFahrenheitPerFoot => As(TemperatureGradientUnit.DegreeFahrenheitPerFoot); + public QuantityValue DegreesFahrenheitPerFoot => this.As(TemperatureGradientUnit.DegreeFahrenheitPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KelvinsPerMeter => As(TemperatureGradientUnit.KelvinPerMeter); + public QuantityValue KelvinsPerMeter => this.As(TemperatureGradientUnit.KelvinPerMeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: TemperatureGradientUnit -> BaseUnit - unitConverter.SetConversionFunction(TemperatureGradientUnit.DegreeCelsiusPerKilometer, TemperatureGradientUnit.KelvinPerMeter, quantity => quantity.ToUnit(TemperatureGradientUnit.KelvinPerMeter)); - unitConverter.SetConversionFunction(TemperatureGradientUnit.DegreeCelsiusPerMeter, TemperatureGradientUnit.KelvinPerMeter, quantity => quantity.ToUnit(TemperatureGradientUnit.KelvinPerMeter)); - unitConverter.SetConversionFunction(TemperatureGradientUnit.DegreeFahrenheitPerFoot, TemperatureGradientUnit.KelvinPerMeter, quantity => quantity.ToUnit(TemperatureGradientUnit.KelvinPerMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.KelvinPerMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> TemperatureGradientUnit - unitConverter.SetConversionFunction(TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeCelsiusPerKilometer, quantity => quantity.ToUnit(TemperatureGradientUnit.DegreeCelsiusPerKilometer)); - unitConverter.SetConversionFunction(TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeCelsiusPerMeter, quantity => quantity.ToUnit(TemperatureGradientUnit.DegreeCelsiusPerMeter)); - unitConverter.SetConversionFunction(TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeFahrenheitPerFoot, quantity => quantity.ToUnit(TemperatureGradientUnit.DegreeFahrenheitPerFoot)); - } - /// /// Get unit abbreviation string. /// @@ -305,7 +287,7 @@ public static string GetAbbreviation(TemperatureGradientUnit unit, IFormatProvid /// /// Creates a from . /// - public static TemperatureGradient FromDegreesCelsiusPerKilometer(double value) + public static TemperatureGradient FromDegreesCelsiusPerKilometer(QuantityValue value) { return new TemperatureGradient(value, TemperatureGradientUnit.DegreeCelsiusPerKilometer); } @@ -313,7 +295,7 @@ public static TemperatureGradient FromDegreesCelsiusPerKilometer(double value) /// /// Creates a from . /// - public static TemperatureGradient FromDegreesCelsiusPerMeter(double value) + public static TemperatureGradient FromDegreesCelsiusPerMeter(QuantityValue value) { return new TemperatureGradient(value, TemperatureGradientUnit.DegreeCelsiusPerMeter); } @@ -321,7 +303,7 @@ public static TemperatureGradient FromDegreesCelsiusPerMeter(double value) /// /// Creates a from . /// - public static TemperatureGradient FromDegreesFahrenheitPerFoot(double value) + public static TemperatureGradient FromDegreesFahrenheitPerFoot(QuantityValue value) { return new TemperatureGradient(value, TemperatureGradientUnit.DegreeFahrenheitPerFoot); } @@ -329,7 +311,7 @@ public static TemperatureGradient FromDegreesFahrenheitPerFoot(double value) /// /// Creates a from . /// - public static TemperatureGradient FromKelvinsPerMeter(double value) + public static TemperatureGradient FromKelvinsPerMeter(QuantityValue value) { return new TemperatureGradient(value, TemperatureGradientUnit.KelvinPerMeter); } @@ -340,7 +322,7 @@ public static TemperatureGradient FromKelvinsPerMeter(double value) /// Value to convert from. /// Unit to convert from. /// TemperatureGradient unit value. - public static TemperatureGradient From(double value, TemperatureGradientUnit fromUnit) + public static TemperatureGradient From(QuantityValue value, TemperatureGradientUnit fromUnit) { return new TemperatureGradient(value, fromUnit); } @@ -401,10 +383,7 @@ public static TemperatureGradient Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static TemperatureGradient Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -432,11 +411,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out TemperatureGradi /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out TemperatureGradient result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -457,7 +432,7 @@ public static TemperatureGradientUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -468,7 +443,7 @@ public static TemperatureGradientUnit ParseUnit(string str, IFormatProvider? pro return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out TemperatureGradientUnit unit) { return TryParseUnit(str, null, out unit); @@ -483,7 +458,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out TemperatureG /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out TemperatureGradientUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -502,35 +477,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static TemperatureGradient operator +(TemperatureGradient left, TemperatureGradient right) { - return new TemperatureGradient(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new TemperatureGradient(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static TemperatureGradient operator -(TemperatureGradient left, TemperatureGradient right) { - return new TemperatureGradient(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new TemperatureGradient(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -552,97 +527,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(TemperatureGradient left, TemperatureGradient right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(TemperatureGradient left, TemperatureGradient right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(TemperatureGradient left, TemperatureGradient right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(TemperatureGradient left, TemperatureGradient right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(TemperatureGradient other, TemperatureGradient tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(TemperatureGradient left, TemperatureGradient right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(TemperatureGradient other, TemperatureGradient tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(TemperatureGradient left, TemperatureGradient right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(TemperatureGradient other, TemperatureGradient tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is TemperatureGradient otherQuantity)) + if (obj is not TemperatureGradient otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(TemperatureGradient other, TemperatureGradient tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(TemperatureGradient other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current TemperatureGradient. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(TemperatureGradient), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is TemperatureGradient otherQuantity)) throw new ArgumentException("Expected type TemperatureGradient.", nameof(obj)); + if (obj is not TemperatureGradient otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -654,152 +614,24 @@ public int CompareTo(object? obj) /// public int CompareTo(TemperatureGradient other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TemperatureGradientUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this TemperatureGradient to another TemperatureGradient with the unit representation . - /// - /// The unit to convert to. - /// A TemperatureGradient with the specified unit. - public TemperatureGradient ToUnit(TemperatureGradientUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A TemperatureGradient with the specified unit. - public TemperatureGradient ToUnit(TemperatureGradientUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(TemperatureGradient), Unit, typeof(TemperatureGradient), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (TemperatureGradient)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(TemperatureGradientUnit unit, [NotNullWhen(true)] out TemperatureGradient? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - TemperatureGradient? convertedOrNull = (Unit, unit) switch - { - // TemperatureGradientUnit -> BaseUnit - (TemperatureGradientUnit.DegreeCelsiusPerKilometer, TemperatureGradientUnit.KelvinPerMeter) => new TemperatureGradient(_value / 1e3, TemperatureGradientUnit.KelvinPerMeter), - (TemperatureGradientUnit.DegreeCelsiusPerMeter, TemperatureGradientUnit.KelvinPerMeter) => new TemperatureGradient(_value, TemperatureGradientUnit.KelvinPerMeter), - (TemperatureGradientUnit.DegreeFahrenheitPerFoot, TemperatureGradientUnit.KelvinPerMeter) => new TemperatureGradient((_value / 0.3048) * 5 / 9, TemperatureGradientUnit.KelvinPerMeter), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> TemperatureGradientUnit - (TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeCelsiusPerKilometer) => new TemperatureGradient(_value * 1e3, TemperatureGradientUnit.DegreeCelsiusPerKilometer), - (TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeCelsiusPerMeter) => new TemperatureGradient(_value, TemperatureGradientUnit.DegreeCelsiusPerMeter), - (TemperatureGradientUnit.KelvinPerMeter, TemperatureGradientUnit.DegreeFahrenheitPerFoot) => new TemperatureGradient((_value * 0.3048) * 9 / 5, TemperatureGradientUnit.DegreeFahrenheitPerFoot), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public TemperatureGradient ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not TemperatureGradientUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureGradientUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is TemperatureGradientUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TemperatureGradientUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(TemperatureGradientUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(TemperatureGradientUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -814,7 +646,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs index b584b84bcd..e2c8958024 100644 --- a/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ThermalConductivity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Thermal_Conductivity /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ThermalConductivity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ThermalConductivityUnit? _unit; /// @@ -104,7 +103,7 @@ public static ThermalConductivityInfo CreateDefault(Func - /// The for is [T^-3][L][M][Θ^-1]. + /// The for is T^-3LMΘ^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 1, -3, 0, -1, 0, 0); @@ -119,16 +118,16 @@ public static ThermalConductivityInfo CreateDefault(FuncAn of representing the default unit mappings for ThermalConductivity. public static IEnumerable> GetDefaultMappings() { - yield return new (ThermalConductivityUnit.BtuPerHourFootFahrenheit, "BtuPerHourFootFahrenheit", "BtusPerHourFootFahrenheit", BaseUnits.Undefined); + yield return new (ThermalConductivityUnit.BtuPerHourFootFahrenheit, "BtuPerHourFootFahrenheit", "BtusPerHourFootFahrenheit", BaseUnits.Undefined, + new QuantityValue(30480000000, 52752792631) + ); yield return new (ThermalConductivityUnit.WattPerMeterKelvin, "WattPerMeterKelvin", "WattsPerMeterKelvin", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin)); } } static ThermalConductivity() { - Info = ThermalConductivityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ThermalConductivityInfo.CreateDefault); } /// @@ -136,7 +135,7 @@ static ThermalConductivity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ThermalConductivity(double value, ThermalConductivityUnit unit) + public ThermalConductivity(QuantityValue value, ThermalConductivityUnit unit) { _value = value; _unit = unit; @@ -150,7 +149,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -161,7 +160,8 @@ public ThermalConductivity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -190,10 +190,8 @@ public ThermalConductivity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ThermalConductivityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -232,35 +230,19 @@ public ThermalConductivity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BtusPerHourFootFahrenheit => As(ThermalConductivityUnit.BtuPerHourFootFahrenheit); + public QuantityValue BtusPerHourFootFahrenheit => this.As(ThermalConductivityUnit.BtuPerHourFootFahrenheit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double WattsPerMeterKelvin => As(ThermalConductivityUnit.WattPerMeterKelvin); + public QuantityValue WattsPerMeterKelvin => this.As(ThermalConductivityUnit.WattPerMeterKelvin); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ThermalConductivityUnit -> BaseUnit - unitConverter.SetConversionFunction(ThermalConductivityUnit.BtuPerHourFootFahrenheit, ThermalConductivityUnit.WattPerMeterKelvin, quantity => quantity.ToUnit(ThermalConductivityUnit.WattPerMeterKelvin)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ThermalConductivityUnit.WattPerMeterKelvin, ThermalConductivityUnit.WattPerMeterKelvin, quantity => quantity); - - // Register in unit converter: BaseUnit -> ThermalConductivityUnit - unitConverter.SetConversionFunction(ThermalConductivityUnit.WattPerMeterKelvin, ThermalConductivityUnit.BtuPerHourFootFahrenheit, quantity => quantity.ToUnit(ThermalConductivityUnit.BtuPerHourFootFahrenheit)); - } - /// /// Get unit abbreviation string. /// @@ -289,7 +271,7 @@ public static string GetAbbreviation(ThermalConductivityUnit unit, IFormatProvid /// /// Creates a from . /// - public static ThermalConductivity FromBtusPerHourFootFahrenheit(double value) + public static ThermalConductivity FromBtusPerHourFootFahrenheit(QuantityValue value) { return new ThermalConductivity(value, ThermalConductivityUnit.BtuPerHourFootFahrenheit); } @@ -297,7 +279,7 @@ public static ThermalConductivity FromBtusPerHourFootFahrenheit(double value) /// /// Creates a from . /// - public static ThermalConductivity FromWattsPerMeterKelvin(double value) + public static ThermalConductivity FromWattsPerMeterKelvin(QuantityValue value) { return new ThermalConductivity(value, ThermalConductivityUnit.WattPerMeterKelvin); } @@ -308,7 +290,7 @@ public static ThermalConductivity FromWattsPerMeterKelvin(double value) /// Value to convert from. /// Unit to convert from. /// ThermalConductivity unit value. - public static ThermalConductivity From(double value, ThermalConductivityUnit fromUnit) + public static ThermalConductivity From(QuantityValue value, ThermalConductivityUnit fromUnit) { return new ThermalConductivity(value, fromUnit); } @@ -369,10 +351,7 @@ public static ThermalConductivity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ThermalConductivity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -400,11 +379,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ThermalConductiv /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ThermalConductivity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -425,7 +400,7 @@ public static ThermalConductivityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -436,7 +411,7 @@ public static ThermalConductivityUnit ParseUnit(string str, IFormatProvider? pro return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ThermalConductivityUnit unit) { return TryParseUnit(str, null, out unit); @@ -451,7 +426,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ThermalCondu /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ThermalConductivityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -470,35 +445,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ThermalConductivity operator +(ThermalConductivity left, ThermalConductivity right) { - return new ThermalConductivity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ThermalConductivity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ThermalConductivity operator -(ThermalConductivity left, ThermalConductivity right) { - return new ThermalConductivity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ThermalConductivity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -510,97 +485,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ThermalConductivity left, ThermalConductivity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ThermalConductivity left, ThermalConductivity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ThermalConductivity left, ThermalConductivity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ThermalConductivity left, ThermalConductivity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ThermalConductivity other, ThermalConductivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ThermalConductivity left, ThermalConductivity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ThermalConductivity other, ThermalConductivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ThermalConductivity left, ThermalConductivity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ThermalConductivity other, ThermalConductivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ThermalConductivity otherQuantity)) + if (obj is not ThermalConductivity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ThermalConductivity other, ThermalConductivity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ThermalConductivity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ThermalConductivity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ThermalConductivity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ThermalConductivity otherQuantity)) throw new ArgumentException("Expected type ThermalConductivity.", nameof(obj)); + if (obj is not ThermalConductivity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -612,148 +572,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ThermalConductivity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ThermalConductivityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this ThermalConductivity to another ThermalConductivity with the unit representation . - /// - /// The unit to convert to. - /// A ThermalConductivity with the specified unit. - public ThermalConductivity ToUnit(ThermalConductivityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ThermalConductivity with the specified unit. - public ThermalConductivity ToUnit(ThermalConductivityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ThermalConductivity), Unit, typeof(ThermalConductivity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ThermalConductivity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ThermalConductivityUnit unit, [NotNullWhen(true)] out ThermalConductivity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ThermalConductivity? convertedOrNull = (Unit, unit) switch - { - // ThermalConductivityUnit -> BaseUnit - (ThermalConductivityUnit.BtuPerHourFootFahrenheit, ThermalConductivityUnit.WattPerMeterKelvin) => new ThermalConductivity(_value * ((1055.05585262 / (0.3048 * 3600)) * 1.8), ThermalConductivityUnit.WattPerMeterKelvin), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> ThermalConductivityUnit - (ThermalConductivityUnit.WattPerMeterKelvin, ThermalConductivityUnit.BtuPerHourFootFahrenheit) => new ThermalConductivity(_value / ((1055.05585262 / (0.3048 * 3600)) * 1.8), ThermalConductivityUnit.BtuPerHourFootFahrenheit), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ThermalConductivity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ThermalConductivityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalConductivityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ThermalConductivityUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalConductivityUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ThermalConductivityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(ThermalConductivityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -768,7 +604,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalInsulance.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalInsulance.g.cs index 7932ae77a2..0e46795d22 100644 --- a/UnitsNet/GeneratedCode/Quantities/ThermalInsulance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ThermalInsulance.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// Thermal insulance (R-value) is a measure of a material's resistance to the heat current. It quantifies how effectively a material can resist the transfer of heat through conduction, convection, and radiation. It has the units square metre kelvins per watt (m2⋅K/W) in SI units or square foot degree Fahrenheit–hours per British thermal unit (ft2⋅°F⋅h/Btu) in imperial units. The higher the thermal insulance, the better a material insulates against heat transfer. It is commonly used in construction to assess the insulation properties of materials such as walls, roofs, and insulation products. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ThermalInsulance : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ThermalInsulanceUnit? _unit; /// @@ -101,7 +100,7 @@ public static ThermalInsulanceInfo CreateDefault(Func - /// The for is [T^3][M^-1][Θ]. + /// The for is T^3M^-1Θ. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(0, -1, 3, 0, 1, 0, 0); @@ -116,21 +115,31 @@ public static ThermalInsulanceInfo CreateDefault(FuncAn of representing the default unit mappings for ThermalInsulance. public static IEnumerable> GetDefaultMappings() { - yield return new (ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, "HourSquareFeetDegreeFahrenheitPerBtu", "HourSquareFeetDegreesFahrenheitPerBtu", BaseUnits.Undefined); - yield return new (ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, "SquareCentimeterHourDegreeCelsiusPerKilocalorie", "SquareCentimeterHourDegreesCelsiusPerKilocalorie", BaseUnits.Undefined); - yield return new (ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt, "SquareCentimeterKelvinPerWatt", "SquareCentimeterKelvinsPerWatt", BaseUnits.Undefined); - yield return new (ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt, "SquareMeterDegreeCelsiusPerWatt", "SquareMeterDegreesCelsiusPerWatt", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius)); + yield return new (ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, "HourSquareFeetDegreeFahrenheitPerBtu", "HourSquareFeetDegreesFahrenheitPerBtu", BaseUnits.Undefined, + new QuantityValue(52752792631, 9290304000000) + ); + yield return new (ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, "SquareCentimeterHourDegreeCelsiusPerKilocalorie", "SquareCentimeterHourDegreesCelsiusPerKilocalorie", BaseUnits.Undefined, + new QuantityValue(523, 45) + ); + yield return new (ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt, "SquareCentimeterKelvinPerWatt", "SquareCentimeterKelvinsPerWatt", BaseUnits.Undefined, + 10 + ); + yield return new (ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt, "SquareMeterDegreeCelsiusPerWatt", "SquareMeterDegreesCelsiusPerWatt", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), + new QuantityValue(1, 1000) + ); yield return new (ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, "SquareMeterKelvinPerKilowatt", "SquareMeterKelvinsPerKilowatt", BaseUnits.Undefined); - yield return new (ThermalInsulanceUnit.SquareMeterKelvinPerWatt, "SquareMeterKelvinPerWatt", "SquareMeterKelvinsPerWatt", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin)); - yield return new (ThermalInsulanceUnit.SquareMillimeterKelvinPerWatt, "SquareMillimeterKelvinPerWatt", "SquareMillimeterKelvinsPerWatt", BaseUnits.Undefined); + yield return new (ThermalInsulanceUnit.SquareMeterKelvinPerWatt, "SquareMeterKelvinPerWatt", "SquareMeterKelvinsPerWatt", new BaseUnits(mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin), + new QuantityValue(1, 1000) + ); + yield return new (ThermalInsulanceUnit.SquareMillimeterKelvinPerWatt, "SquareMillimeterKelvinPerWatt", "SquareMillimeterKelvinsPerWatt", BaseUnits.Undefined, + 1000 + ); } } static ThermalInsulance() { - Info = ThermalInsulanceInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ThermalInsulanceInfo.CreateDefault); } /// @@ -138,7 +147,7 @@ static ThermalInsulance() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ThermalInsulance(double value, ThermalInsulanceUnit unit) + public ThermalInsulance(QuantityValue value, ThermalInsulanceUnit unit) { _value = value; _unit = unit; @@ -152,7 +161,7 @@ public ThermalInsulance(double value, ThermalInsulanceUnit unit) /// The unit system to create the quantity with. /// The given is null. /// No unit was found for the given . - public ThermalInsulance(double value, UnitSystem unitSystem) + public ThermalInsulance(QuantityValue value, UnitSystem unitSystem) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -163,7 +172,8 @@ public ThermalInsulance(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -192,10 +202,8 @@ public ThermalInsulance(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ThermalInsulanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -234,70 +242,44 @@ public ThermalInsulance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HourSquareFeetDegreesFahrenheitPerBtu => As(ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); + public QuantityValue HourSquareFeetDegreesFahrenheitPerBtu => this.As(ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareCentimeterHourDegreesCelsiusPerKilocalorie => As(ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); + public QuantityValue SquareCentimeterHourDegreesCelsiusPerKilocalorie => this.As(ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareCentimeterKelvinsPerWatt => As(ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt); + public QuantityValue SquareCentimeterKelvinsPerWatt => this.As(ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareMeterDegreesCelsiusPerWatt => As(ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt); + public QuantityValue SquareMeterDegreesCelsiusPerWatt => this.As(ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareMeterKelvinsPerKilowatt => As(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt); + public QuantityValue SquareMeterKelvinsPerKilowatt => this.As(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareMeterKelvinsPerWatt => As(ThermalInsulanceUnit.SquareMeterKelvinPerWatt); + public QuantityValue SquareMeterKelvinsPerWatt => this.As(ThermalInsulanceUnit.SquareMeterKelvinPerWatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double SquareMillimeterKelvinsPerWatt => As(ThermalInsulanceUnit.SquareMillimeterKelvinPerWatt); + public QuantityValue SquareMillimeterKelvinsPerWatt => this.As(ThermalInsulanceUnit.SquareMillimeterKelvinPerWatt); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ThermalInsulanceUnit -> BaseUnit - unitConverter.SetConversionFunction(ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity.ToUnit(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt)); - unitConverter.SetConversionFunction(ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity.ToUnit(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt)); - unitConverter.SetConversionFunction(ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity.ToUnit(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt)); - unitConverter.SetConversionFunction(ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity.ToUnit(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt)); - unitConverter.SetConversionFunction(ThermalInsulanceUnit.SquareMeterKelvinPerWatt, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity.ToUnit(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt)); - unitConverter.SetConversionFunction(ThermalInsulanceUnit.SquareMillimeterKelvinPerWatt, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity.ToUnit(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, quantity => quantity); - - // Register in unit converter: BaseUnit -> ThermalInsulanceUnit - unitConverter.SetConversionFunction(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, quantity => quantity.ToUnit(ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu)); - unitConverter.SetConversionFunction(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, quantity => quantity.ToUnit(ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie)); - unitConverter.SetConversionFunction(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt, quantity => quantity.ToUnit(ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt)); - unitConverter.SetConversionFunction(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt, quantity => quantity.ToUnit(ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt)); - unitConverter.SetConversionFunction(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, ThermalInsulanceUnit.SquareMeterKelvinPerWatt, quantity => quantity.ToUnit(ThermalInsulanceUnit.SquareMeterKelvinPerWatt)); - unitConverter.SetConversionFunction(ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, ThermalInsulanceUnit.SquareMillimeterKelvinPerWatt, quantity => quantity.ToUnit(ThermalInsulanceUnit.SquareMillimeterKelvinPerWatt)); - } - /// /// Get unit abbreviation string. /// @@ -326,7 +308,7 @@ public static string GetAbbreviation(ThermalInsulanceUnit unit, IFormatProvider? /// /// Creates a from . /// - public static ThermalInsulance FromHourSquareFeetDegreesFahrenheitPerBtu(double value) + public static ThermalInsulance FromHourSquareFeetDegreesFahrenheitPerBtu(QuantityValue value) { return new ThermalInsulance(value, ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu); } @@ -334,7 +316,7 @@ public static ThermalInsulance FromHourSquareFeetDegreesFahrenheitPerBtu(double /// /// Creates a from . /// - public static ThermalInsulance FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(double value) + public static ThermalInsulance FromSquareCentimeterHourDegreesCelsiusPerKilocalorie(QuantityValue value) { return new ThermalInsulance(value, ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie); } @@ -342,7 +324,7 @@ public static ThermalInsulance FromSquareCentimeterHourDegreesCelsiusPerKilocalo /// /// Creates a from . /// - public static ThermalInsulance FromSquareCentimeterKelvinsPerWatt(double value) + public static ThermalInsulance FromSquareCentimeterKelvinsPerWatt(QuantityValue value) { return new ThermalInsulance(value, ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt); } @@ -350,7 +332,7 @@ public static ThermalInsulance FromSquareCentimeterKelvinsPerWatt(double value) /// /// Creates a from . /// - public static ThermalInsulance FromSquareMeterDegreesCelsiusPerWatt(double value) + public static ThermalInsulance FromSquareMeterDegreesCelsiusPerWatt(QuantityValue value) { return new ThermalInsulance(value, ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt); } @@ -358,7 +340,7 @@ public static ThermalInsulance FromSquareMeterDegreesCelsiusPerWatt(double value /// /// Creates a from . /// - public static ThermalInsulance FromSquareMeterKelvinsPerKilowatt(double value) + public static ThermalInsulance FromSquareMeterKelvinsPerKilowatt(QuantityValue value) { return new ThermalInsulance(value, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt); } @@ -366,7 +348,7 @@ public static ThermalInsulance FromSquareMeterKelvinsPerKilowatt(double value) /// /// Creates a from . /// - public static ThermalInsulance FromSquareMeterKelvinsPerWatt(double value) + public static ThermalInsulance FromSquareMeterKelvinsPerWatt(QuantityValue value) { return new ThermalInsulance(value, ThermalInsulanceUnit.SquareMeterKelvinPerWatt); } @@ -374,7 +356,7 @@ public static ThermalInsulance FromSquareMeterKelvinsPerWatt(double value) /// /// Creates a from . /// - public static ThermalInsulance FromSquareMillimeterKelvinsPerWatt(double value) + public static ThermalInsulance FromSquareMillimeterKelvinsPerWatt(QuantityValue value) { return new ThermalInsulance(value, ThermalInsulanceUnit.SquareMillimeterKelvinPerWatt); } @@ -385,7 +367,7 @@ public static ThermalInsulance FromSquareMillimeterKelvinsPerWatt(double value) /// Value to convert from. /// Unit to convert from. /// ThermalInsulance unit value. - public static ThermalInsulance From(double value, ThermalInsulanceUnit fromUnit) + public static ThermalInsulance From(QuantityValue value, ThermalInsulanceUnit fromUnit) { return new ThermalInsulance(value, fromUnit); } @@ -446,10 +428,7 @@ public static ThermalInsulance Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ThermalInsulance Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -477,11 +456,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ThermalInsulance /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ThermalInsulance result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -502,7 +477,7 @@ public static ThermalInsulanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -513,7 +488,7 @@ public static ThermalInsulanceUnit ParseUnit(string str, IFormatProvider? provid return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ThermalInsulanceUnit unit) { return TryParseUnit(str, null, out unit); @@ -528,7 +503,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ThermalInsul /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ThermalInsulanceUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -547,35 +522,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ThermalInsulance operator +(ThermalInsulance left, ThermalInsulance right) { - return new ThermalInsulance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ThermalInsulance(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ThermalInsulance operator -(ThermalInsulance left, ThermalInsulance right) { - return new ThermalInsulance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ThermalInsulance(left.Value - right.As(left.Unit), left.Unit); } /// Get from multiplying value and . - public static ThermalInsulance operator *(double left, ThermalInsulance right) + public static ThermalInsulance operator *(QuantityValue left, ThermalInsulance right) { return new ThermalInsulance(left * right.Value, right.Unit); } /// Get from multiplying value and . - public static ThermalInsulance operator *(ThermalInsulance left, double right) + public static ThermalInsulance operator *(ThermalInsulance left, QuantityValue right) { return new ThermalInsulance(left.Value * right, left.Unit); } /// Get from dividing by value. - public static ThermalInsulance operator /(ThermalInsulance left, double right) + public static ThermalInsulance operator /(ThermalInsulance left, QuantityValue right) { return new ThermalInsulance(left.Value / right, left.Unit); } /// Get ratio value from dividing by . - public static double operator /(ThermalInsulance left, ThermalInsulance right) + public static QuantityValue operator /(ThermalInsulance left, ThermalInsulance right) { return left.SquareMeterKelvinsPerKilowatt / right.SquareMeterKelvinsPerKilowatt; } @@ -587,97 +562,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ThermalInsulance left, ThermalInsulance right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ThermalInsulance left, ThermalInsulance right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ThermalInsulance left, ThermalInsulance right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ThermalInsulance left, ThermalInsulance right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ThermalInsulance other, ThermalInsulance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ThermalInsulance left, ThermalInsulance right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ThermalInsulance other, ThermalInsulance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ThermalInsulance left, ThermalInsulance right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ThermalInsulance other, ThermalInsulance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ThermalInsulance otherQuantity)) + if (obj is not ThermalInsulance otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ThermalInsulance other, ThermalInsulance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ThermalInsulance other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ThermalInsulance. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ThermalInsulance), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ThermalInsulance otherQuantity)) throw new ArgumentException("Expected type ThermalInsulance.", nameof(obj)); + if (obj is not ThermalInsulance otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -689,158 +649,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ThermalInsulance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ThermalInsulanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this ThermalInsulance to another ThermalInsulance with the unit representation . - /// - /// The unit to convert to. - /// A ThermalInsulance with the specified unit. - public ThermalInsulance ToUnit(ThermalInsulanceUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ThermalInsulance with the specified unit. - public ThermalInsulance ToUnit(ThermalInsulanceUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ThermalInsulance), Unit, typeof(ThermalInsulance), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ThermalInsulance)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ThermalInsulanceUnit unit, [NotNullWhen(true)] out ThermalInsulance? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ThermalInsulance? convertedOrNull = (Unit, unit) switch - { - // ThermalInsulanceUnit -> BaseUnit - (ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt) => new ThermalInsulance(_value * (1000 * 0.3048 * 0.3048 * 3600) / (1055.05585262 * 1.8), ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt), - (ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt) => new ThermalInsulance(_value * (0.0001 * 3600) / 4.184, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt), - (ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt) => new ThermalInsulance(_value * 0.1, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt), - (ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt) => new ThermalInsulance(_value * 1000.0, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt), - (ThermalInsulanceUnit.SquareMeterKelvinPerWatt, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt) => new ThermalInsulance(_value * 1000, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt), - (ThermalInsulanceUnit.SquareMillimeterKelvinPerWatt, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt) => new ThermalInsulance(_value * 0.001, ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt), - - // BaseUnit -> ThermalInsulanceUnit - (ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu) => new ThermalInsulance(_value * (1055.05585262 * 1.8) / (1000 * 0.3048 * 0.3048 * 3600), ThermalInsulanceUnit.HourSquareFeetDegreeFahrenheitPerBtu), - (ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie) => new ThermalInsulance(_value * 4.184 / (0.0001 * 3600), ThermalInsulanceUnit.SquareCentimeterHourDegreeCelsiusPerKilocalorie), - (ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt) => new ThermalInsulance(_value / 0.1, ThermalInsulanceUnit.SquareCentimeterKelvinPerWatt), - (ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt) => new ThermalInsulance(_value / 1000.0, ThermalInsulanceUnit.SquareMeterDegreeCelsiusPerWatt), - (ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, ThermalInsulanceUnit.SquareMeterKelvinPerWatt) => new ThermalInsulance(_value / 1000, ThermalInsulanceUnit.SquareMeterKelvinPerWatt), - (ThermalInsulanceUnit.SquareMeterKelvinPerKilowatt, ThermalInsulanceUnit.SquareMillimeterKelvinPerWatt) => new ThermalInsulance(_value / 0.001, ThermalInsulanceUnit.SquareMillimeterKelvinPerWatt), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ThermalInsulance ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ThermalInsulanceUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalInsulanceUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ThermalInsulanceUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalInsulanceUnit)} is supported.", nameof(unit)); - - return ToUnit(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(ThermalInsulanceUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ThermalInsulanceUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -855,7 +681,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs b/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs index a3964742d8..4872577cd8 100644 --- a/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/ThermalResistance.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// Thermal resistance (R) measures the opposition to the heat current in a material or system. It is measured in units of kelvins per watt (K/W) and indicates how much temperature difference (in kelvins) is required to transfer a unit of heat current (in watts) through the material or object. It is essential to optimize the building insulation, evaluate the efficiency of electronic devices, and enhance the performance of heat sinks in various applications. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct ThermalResistance : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly ThermalResistanceUnit? _unit; /// @@ -101,7 +100,7 @@ public static ThermalResistanceInfo CreateDefault(Func - /// The for is [T^3][L^-2][M^-1][Θ]. + /// The for is T^3L^-2M^-1Θ. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-2, -1, 3, 0, 1, 0, 0); @@ -116,16 +115,16 @@ public static ThermalResistanceInfo CreateDefault(FuncAn of representing the default unit mappings for ThermalResistance. public static IEnumerable> GetDefaultMappings() { - yield return new (ThermalResistanceUnit.DegreeCelsiusPerWatt, "DegreeCelsiusPerWatt", "DegreesCelsiusPerWatt", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius)); + yield return new (ThermalResistanceUnit.DegreeCelsiusPerWatt, "DegreeCelsiusPerWatt", "DegreesCelsiusPerWatt", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), + 1 + ); yield return new (ThermalResistanceUnit.KelvinPerWatt, "KelvinPerWatt", "KelvinsPerWatt", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin)); } } static ThermalResistance() { - Info = ThermalResistanceInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(ThermalResistanceInfo.CreateDefault); } /// @@ -133,7 +132,7 @@ static ThermalResistance() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public ThermalResistance(double value, ThermalResistanceUnit unit) + public ThermalResistance(QuantityValue value, ThermalResistanceUnit unit) { _value = value; _unit = unit; @@ -147,7 +146,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -158,7 +157,8 @@ public ThermalResistance(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -187,10 +187,8 @@ public ThermalResistance(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public ThermalResistanceUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -229,35 +227,19 @@ public ThermalResistance(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DegreesCelsiusPerWatt => As(ThermalResistanceUnit.DegreeCelsiusPerWatt); + public QuantityValue DegreesCelsiusPerWatt => this.As(ThermalResistanceUnit.DegreeCelsiusPerWatt); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KelvinsPerWatt => As(ThermalResistanceUnit.KelvinPerWatt); + public QuantityValue KelvinsPerWatt => this.As(ThermalResistanceUnit.KelvinPerWatt); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: ThermalResistanceUnit -> BaseUnit - unitConverter.SetConversionFunction(ThermalResistanceUnit.DegreeCelsiusPerWatt, ThermalResistanceUnit.KelvinPerWatt, quantity => quantity.ToUnit(ThermalResistanceUnit.KelvinPerWatt)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(ThermalResistanceUnit.KelvinPerWatt, ThermalResistanceUnit.KelvinPerWatt, quantity => quantity); - - // Register in unit converter: BaseUnit -> ThermalResistanceUnit - unitConverter.SetConversionFunction(ThermalResistanceUnit.KelvinPerWatt, ThermalResistanceUnit.DegreeCelsiusPerWatt, quantity => quantity.ToUnit(ThermalResistanceUnit.DegreeCelsiusPerWatt)); - } - /// /// Get unit abbreviation string. /// @@ -286,7 +268,7 @@ public static string GetAbbreviation(ThermalResistanceUnit unit, IFormatProvider /// /// Creates a from . /// - public static ThermalResistance FromDegreesCelsiusPerWatt(double value) + public static ThermalResistance FromDegreesCelsiusPerWatt(QuantityValue value) { return new ThermalResistance(value, ThermalResistanceUnit.DegreeCelsiusPerWatt); } @@ -294,7 +276,7 @@ public static ThermalResistance FromDegreesCelsiusPerWatt(double value) /// /// Creates a from . /// - public static ThermalResistance FromKelvinsPerWatt(double value) + public static ThermalResistance FromKelvinsPerWatt(QuantityValue value) { return new ThermalResistance(value, ThermalResistanceUnit.KelvinPerWatt); } @@ -305,7 +287,7 @@ public static ThermalResistance FromKelvinsPerWatt(double value) /// Value to convert from. /// Unit to convert from. /// ThermalResistance unit value. - public static ThermalResistance From(double value, ThermalResistanceUnit fromUnit) + public static ThermalResistance From(QuantityValue value, ThermalResistanceUnit fromUnit) { return new ThermalResistance(value, fromUnit); } @@ -366,10 +348,7 @@ public static ThermalResistance Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static ThermalResistance Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -397,11 +376,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out ThermalResistanc /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out ThermalResistance result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -422,7 +397,7 @@ public static ThermalResistanceUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -433,7 +408,7 @@ public static ThermalResistanceUnit ParseUnit(string str, IFormatProvider? provi return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out ThermalResistanceUnit unit) { return TryParseUnit(str, null, out unit); @@ -448,7 +423,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out ThermalResis /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out ThermalResistanceUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -467,35 +442,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static ThermalResistance operator +(ThermalResistance left, ThermalResistance right) { - return new ThermalResistance(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new ThermalResistance(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static ThermalResistance operator -(ThermalResistance left, ThermalResistance right) { - return new ThermalResistance(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new ThermalResistance(left.Value - right.As(left.Unit), left.Unit); } /// 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.KelvinsPerWatt / right.KelvinsPerWatt; } @@ -507,97 +482,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(ThermalResistance left, ThermalResistance right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(ThermalResistance left, ThermalResistance right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(ThermalResistance left, ThermalResistance right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(ThermalResistance left, ThermalResistance right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ThermalResistance other, ThermalResistance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(ThermalResistance left, ThermalResistance right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(ThermalResistance other, ThermalResistance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(ThermalResistance left, ThermalResistance right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ThermalResistance other, ThermalResistance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is ThermalResistance otherQuantity)) + if (obj is not ThermalResistance otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(ThermalResistance other, ThermalResistance tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(ThermalResistance other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current ThermalResistance. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(ThermalResistance), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is ThermalResistance otherQuantity)) throw new ArgumentException("Expected type ThermalResistance.", nameof(obj)); + if (obj is not ThermalResistance otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -609,148 +569,24 @@ public int CompareTo(object? obj) /// public int CompareTo(ThermalResistance other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(ThermalResistanceUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this ThermalResistance to another ThermalResistance with the unit representation . - /// - /// The unit to convert to. - /// A ThermalResistance with the specified unit. - public ThermalResistance ToUnit(ThermalResistanceUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A ThermalResistance with the specified unit. - public ThermalResistance ToUnit(ThermalResistanceUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(ThermalResistance), Unit, typeof(ThermalResistance), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (ThermalResistance)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(ThermalResistanceUnit unit, [NotNullWhen(true)] out ThermalResistance? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - ThermalResistance? convertedOrNull = (Unit, unit) switch - { - // ThermalResistanceUnit -> BaseUnit - (ThermalResistanceUnit.DegreeCelsiusPerWatt, ThermalResistanceUnit.KelvinPerWatt) => new ThermalResistance(_value, ThermalResistanceUnit.KelvinPerWatt), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> ThermalResistanceUnit - (ThermalResistanceUnit.KelvinPerWatt, ThermalResistanceUnit.DegreeCelsiusPerWatt) => new ThermalResistance(_value, ThermalResistanceUnit.DegreeCelsiusPerWatt), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public ThermalResistance ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not ThermalResistanceUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalResistanceUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is ThermalResistanceUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ThermalResistanceUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(ThermalResistanceUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(ThermalResistanceUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -765,7 +601,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Torque.g.cs b/UnitsNet/GeneratedCode/Quantities/Torque.g.cs index e0b2e3a3ac..62e4ad56bf 100644 --- a/UnitsNet/GeneratedCode/Quantities/Torque.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Torque.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Torque : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -59,13 +58,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly TorqueUnit? _unit; /// @@ -110,7 +109,7 @@ public static TorqueInfo CreateDefault(Func - /// The for is [T^-2][L^2][M]. + /// The for is T^-2L^2M. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 1, -2, 0, 0, 0, 0); @@ -125,39 +124,85 @@ public static TorqueInfo CreateDefault(FuncAn of representing the default unit mappings for Torque. public static IEnumerable> GetDefaultMappings() { - yield return new (TorqueUnit.GramForceCentimeter, "GramForceCentimeter", "GramForceCentimeters", BaseUnits.Undefined); - yield return new (TorqueUnit.GramForceMeter, "GramForceMeter", "GramForceMeters", BaseUnits.Undefined); - yield return new (TorqueUnit.GramForceMillimeter, "GramForceMillimeter", "GramForceMillimeters", BaseUnits.Undefined); - yield return new (TorqueUnit.KilogramForceCentimeter, "KilogramForceCentimeter", "KilogramForceCentimeters", BaseUnits.Undefined); - yield return new (TorqueUnit.KilogramForceMeter, "KilogramForceMeter", "KilogramForceMeters", BaseUnits.Undefined); - yield return new (TorqueUnit.KilogramForceMillimeter, "KilogramForceMillimeter", "KilogramForceMillimeters", BaseUnits.Undefined); - yield return new (TorqueUnit.KilonewtonCentimeter, "KilonewtonCentimeter", "KilonewtonCentimeters", BaseUnits.Undefined); - yield return new (TorqueUnit.KilonewtonMeter, "KilonewtonMeter", "KilonewtonMeters", BaseUnits.Undefined); - yield return new (TorqueUnit.KilonewtonMillimeter, "KilonewtonMillimeter", "KilonewtonMillimeters", BaseUnits.Undefined); - yield return new (TorqueUnit.KilopoundForceFoot, "KilopoundForceFoot", "KilopoundForceFeet", BaseUnits.Undefined); - yield return new (TorqueUnit.KilopoundForceInch, "KilopoundForceInch", "KilopoundForceInches", BaseUnits.Undefined); - yield return new (TorqueUnit.MeganewtonCentimeter, "MeganewtonCentimeter", "MeganewtonCentimeters", BaseUnits.Undefined); - yield return new (TorqueUnit.MeganewtonMeter, "MeganewtonMeter", "MeganewtonMeters", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (TorqueUnit.MeganewtonMillimeter, "MeganewtonMillimeter", "MeganewtonMillimeters", BaseUnits.Undefined); - yield return new (TorqueUnit.MegapoundForceFoot, "MegapoundForceFoot", "MegapoundForceFeet", BaseUnits.Undefined); - yield return new (TorqueUnit.MegapoundForceInch, "MegapoundForceInch", "MegapoundForceInches", BaseUnits.Undefined); - yield return new (TorqueUnit.NewtonCentimeter, "NewtonCentimeter", "NewtonCentimeters", BaseUnits.Undefined); + yield return new (TorqueUnit.GramForceCentimeter, "GramForceCentimeter", "GramForceCentimeters", BaseUnits.Undefined, + new QuantityValue(2000000000, 196133) + ); + yield return new (TorqueUnit.GramForceMeter, "GramForceMeter", "GramForceMeters", BaseUnits.Undefined, + new QuantityValue(20000000, 196133) + ); + yield return new (TorqueUnit.GramForceMillimeter, "GramForceMillimeter", "GramForceMillimeters", BaseUnits.Undefined, + new QuantityValue(20000000000, 196133) + ); + yield return new (TorqueUnit.KilogramForceCentimeter, "KilogramForceCentimeter", "KilogramForceCentimeters", BaseUnits.Undefined, + new QuantityValue(2000000, 196133) + ); + yield return new (TorqueUnit.KilogramForceMeter, "KilogramForceMeter", "KilogramForceMeters", BaseUnits.Undefined, + new QuantityValue(20000, 196133) + ); + yield return new (TorqueUnit.KilogramForceMillimeter, "KilogramForceMillimeter", "KilogramForceMillimeters", BaseUnits.Undefined, + new QuantityValue(20000000, 196133) + ); + yield return new (TorqueUnit.KilonewtonCentimeter, "KilonewtonCentimeter", "KilonewtonCentimeters", BaseUnits.Undefined, + new QuantityValue(1, 10) + ); + yield return new (TorqueUnit.KilonewtonMeter, "KilonewtonMeter", "KilonewtonMeters", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (TorqueUnit.KilonewtonMillimeter, "KilonewtonMillimeter", "KilonewtonMillimeters", BaseUnits.Undefined, + 1 + ); + yield return new (TorqueUnit.KilopoundForceFoot, "KilopoundForceFoot", "KilopoundForceFeet", BaseUnits.Undefined, + new QuantityValue(2500000000000, 3389544870828501) + ); + yield return new (TorqueUnit.KilopoundForceInch, "KilopoundForceInch", "KilopoundForceInches", BaseUnits.Undefined, + new QuantityValue(10000000000000, 1129848290276167) + ); + yield return new (TorqueUnit.MeganewtonCentimeter, "MeganewtonCentimeter", "MeganewtonCentimeters", BaseUnits.Undefined, + new QuantityValue(1, 10000) + ); + yield return new (TorqueUnit.MeganewtonMeter, "MeganewtonMeter", "MeganewtonMeters", new BaseUnits(length: LengthUnit.Kilometer, mass: MassUnit.Kilogram, time: DurationUnit.Second), + new QuantityValue(1, 1000000) + ); + yield return new (TorqueUnit.MeganewtonMillimeter, "MeganewtonMillimeter", "MeganewtonMillimeters", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (TorqueUnit.MegapoundForceFoot, "MegapoundForceFoot", "MegapoundForceFeet", BaseUnits.Undefined, + new QuantityValue(2500000000, 3389544870828501) + ); + yield return new (TorqueUnit.MegapoundForceInch, "MegapoundForceInch", "MegapoundForceInches", BaseUnits.Undefined, + new QuantityValue(10000000000, 1129848290276167) + ); + yield return new (TorqueUnit.NewtonCentimeter, "NewtonCentimeter", "NewtonCentimeters", BaseUnits.Undefined, + 100 + ); yield return new (TorqueUnit.NewtonMeter, "NewtonMeter", "NewtonMeters", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second)); - yield return new (TorqueUnit.NewtonMillimeter, "NewtonMillimeter", "NewtonMillimeters", BaseUnits.Undefined); - yield return new (TorqueUnit.PoundalFoot, "PoundalFoot", "PoundalFeet", BaseUnits.Undefined); - yield return new (TorqueUnit.PoundForceFoot, "PoundForceFoot", "PoundForceFeet", BaseUnits.Undefined); - yield return new (TorqueUnit.PoundForceInch, "PoundForceInch", "PoundForceInches", BaseUnits.Undefined); - yield return new (TorqueUnit.TonneForceCentimeter, "TonneForceCentimeter", "TonneForceCentimeters", BaseUnits.Undefined); - yield return new (TorqueUnit.TonneForceMeter, "TonneForceMeter", "TonneForceMeters", BaseUnits.Undefined); - yield return new (TorqueUnit.TonneForceMillimeter, "TonneForceMillimeter", "TonneForceMillimeters", BaseUnits.Undefined); + yield return new (TorqueUnit.NewtonMillimeter, "NewtonMillimeter", "NewtonMillimeters", BaseUnits.Undefined, + 1000 + ); + yield return new (TorqueUnit.PoundalFoot, "PoundalFoot", "PoundalFeet", BaseUnits.Undefined, + new QuantityValue(156250000000000, 6584392202157) + ); + yield return new (TorqueUnit.PoundForceFoot, "PoundForceFoot", "PoundForceFeet", BaseUnits.Undefined, + new QuantityValue(2500000000000000, 3389544870828501) + ); + yield return new (TorqueUnit.PoundForceInch, "PoundForceInch", "PoundForceInches", BaseUnits.Undefined, + new QuantityValue(10000000000000000, 1129848290276167) + ); + yield return new (TorqueUnit.TonneForceCentimeter, "TonneForceCentimeter", "TonneForceCentimeters", BaseUnits.Undefined, + new QuantityValue(2000, 196133) + ); + yield return new (TorqueUnit.TonneForceMeter, "TonneForceMeter", "TonneForceMeters", BaseUnits.Undefined, + new QuantityValue(20, 196133) + ); + yield return new (TorqueUnit.TonneForceMillimeter, "TonneForceMillimeter", "TonneForceMillimeters", BaseUnits.Undefined, + new QuantityValue(20000, 196133) + ); } } static Torque() { - Info = TorqueInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(TorqueInfo.CreateDefault); } /// @@ -165,7 +210,7 @@ static Torque() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Torque(double value, TorqueUnit unit) + public Torque(QuantityValue value, TorqueUnit unit) { _value = value; _unit = unit; @@ -179,7 +224,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -190,7 +235,8 @@ public Torque(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -219,10 +265,8 @@ public Torque(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public TorqueUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -261,196 +305,134 @@ public Torque(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramForceCentimeters => As(TorqueUnit.GramForceCentimeter); + public QuantityValue GramForceCentimeters => this.As(TorqueUnit.GramForceCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramForceMeters => As(TorqueUnit.GramForceMeter); + public QuantityValue GramForceMeters => this.As(TorqueUnit.GramForceMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double GramForceMillimeters => As(TorqueUnit.GramForceMillimeter); + public QuantityValue GramForceMillimeters => this.As(TorqueUnit.GramForceMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramForceCentimeters => As(TorqueUnit.KilogramForceCentimeter); + public QuantityValue KilogramForceCentimeters => this.As(TorqueUnit.KilogramForceCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramForceMeters => As(TorqueUnit.KilogramForceMeter); + public QuantityValue KilogramForceMeters => this.As(TorqueUnit.KilogramForceMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilogramForceMillimeters => As(TorqueUnit.KilogramForceMillimeter); + public QuantityValue KilogramForceMillimeters => this.As(TorqueUnit.KilogramForceMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonCentimeters => As(TorqueUnit.KilonewtonCentimeter); + public QuantityValue KilonewtonCentimeters => this.As(TorqueUnit.KilonewtonCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonMeters => As(TorqueUnit.KilonewtonMeter); + public QuantityValue KilonewtonMeters => this.As(TorqueUnit.KilonewtonMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilonewtonMillimeters => As(TorqueUnit.KilonewtonMillimeter); + public QuantityValue KilonewtonMillimeters => this.As(TorqueUnit.KilonewtonMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundForceFeet => As(TorqueUnit.KilopoundForceFoot); + public QuantityValue KilopoundForceFeet => this.As(TorqueUnit.KilopoundForceFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilopoundForceInches => As(TorqueUnit.KilopoundForceInch); + public QuantityValue KilopoundForceInches => this.As(TorqueUnit.KilopoundForceInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MeganewtonCentimeters => As(TorqueUnit.MeganewtonCentimeter); + public QuantityValue MeganewtonCentimeters => this.As(TorqueUnit.MeganewtonCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MeganewtonMeters => As(TorqueUnit.MeganewtonMeter); + public QuantityValue MeganewtonMeters => this.As(TorqueUnit.MeganewtonMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MeganewtonMillimeters => As(TorqueUnit.MeganewtonMillimeter); + public QuantityValue MeganewtonMillimeters => this.As(TorqueUnit.MeganewtonMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegapoundForceFeet => As(TorqueUnit.MegapoundForceFoot); + public QuantityValue MegapoundForceFeet => this.As(TorqueUnit.MegapoundForceFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegapoundForceInches => As(TorqueUnit.MegapoundForceInch); + public QuantityValue MegapoundForceInches => this.As(TorqueUnit.MegapoundForceInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonCentimeters => As(TorqueUnit.NewtonCentimeter); + public QuantityValue NewtonCentimeters => this.As(TorqueUnit.NewtonCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonMeters => As(TorqueUnit.NewtonMeter); + public QuantityValue NewtonMeters => this.As(TorqueUnit.NewtonMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NewtonMillimeters => As(TorqueUnit.NewtonMillimeter); + public QuantityValue NewtonMillimeters => this.As(TorqueUnit.NewtonMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundalFeet => As(TorqueUnit.PoundalFoot); + public QuantityValue PoundalFeet => this.As(TorqueUnit.PoundalFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundForceFeet => As(TorqueUnit.PoundForceFoot); + public QuantityValue PoundForceFeet => this.As(TorqueUnit.PoundForceFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PoundForceInches => As(TorqueUnit.PoundForceInch); + public QuantityValue PoundForceInches => this.As(TorqueUnit.PoundForceInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonneForceCentimeters => As(TorqueUnit.TonneForceCentimeter); + public QuantityValue TonneForceCentimeters => this.As(TorqueUnit.TonneForceCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonneForceMeters => As(TorqueUnit.TonneForceMeter); + public QuantityValue TonneForceMeters => this.As(TorqueUnit.TonneForceMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double TonneForceMillimeters => As(TorqueUnit.TonneForceMillimeter); + public QuantityValue TonneForceMillimeters => this.As(TorqueUnit.TonneForceMillimeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: TorqueUnit -> BaseUnit - unitConverter.SetConversionFunction(TorqueUnit.GramForceCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.GramForceMeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.GramForceMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.KilogramForceCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.KilogramForceMeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.KilogramForceMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.KilonewtonCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.KilonewtonMeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.KilonewtonMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.KilopoundForceFoot, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.KilopoundForceInch, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.MeganewtonCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.MeganewtonMeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.MeganewtonMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.MegapoundForceFoot, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.MegapoundForceInch, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.PoundalFoot, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.PoundForceFoot, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.PoundForceInch, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.TonneForceCentimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.TonneForceMeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.TonneForceMillimeter, TorqueUnit.NewtonMeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.NewtonMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> TorqueUnit - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.GramForceCentimeter, quantity => quantity.ToUnit(TorqueUnit.GramForceCentimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.GramForceMeter, quantity => quantity.ToUnit(TorqueUnit.GramForceMeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.GramForceMillimeter, quantity => quantity.ToUnit(TorqueUnit.GramForceMillimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceCentimeter, quantity => quantity.ToUnit(TorqueUnit.KilogramForceCentimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceMeter, quantity => quantity.ToUnit(TorqueUnit.KilogramForceMeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceMillimeter, quantity => quantity.ToUnit(TorqueUnit.KilogramForceMillimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonCentimeter, quantity => quantity.ToUnit(TorqueUnit.KilonewtonCentimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonMeter, quantity => quantity.ToUnit(TorqueUnit.KilonewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonMillimeter, quantity => quantity.ToUnit(TorqueUnit.KilonewtonMillimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilopoundForceFoot, quantity => quantity.ToUnit(TorqueUnit.KilopoundForceFoot)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.KilopoundForceInch, quantity => quantity.ToUnit(TorqueUnit.KilopoundForceInch)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonCentimeter, quantity => quantity.ToUnit(TorqueUnit.MeganewtonCentimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonMeter, quantity => quantity.ToUnit(TorqueUnit.MeganewtonMeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonMillimeter, quantity => quantity.ToUnit(TorqueUnit.MeganewtonMillimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.MegapoundForceFoot, quantity => quantity.ToUnit(TorqueUnit.MegapoundForceFoot)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.MegapoundForceInch, quantity => quantity.ToUnit(TorqueUnit.MegapoundForceInch)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.NewtonCentimeter, quantity => quantity.ToUnit(TorqueUnit.NewtonCentimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.NewtonMillimeter, quantity => quantity.ToUnit(TorqueUnit.NewtonMillimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.PoundalFoot, quantity => quantity.ToUnit(TorqueUnit.PoundalFoot)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.PoundForceFoot, quantity => quantity.ToUnit(TorqueUnit.PoundForceFoot)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.PoundForceInch, quantity => quantity.ToUnit(TorqueUnit.PoundForceInch)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.TonneForceCentimeter, quantity => quantity.ToUnit(TorqueUnit.TonneForceCentimeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.TonneForceMeter, quantity => quantity.ToUnit(TorqueUnit.TonneForceMeter)); - unitConverter.SetConversionFunction(TorqueUnit.NewtonMeter, TorqueUnit.TonneForceMillimeter, quantity => quantity.ToUnit(TorqueUnit.TonneForceMillimeter)); - } - /// /// Get unit abbreviation string. /// @@ -479,7 +461,7 @@ public static string GetAbbreviation(TorqueUnit unit, IFormatProvider? provider) /// /// Creates a from . /// - public static Torque FromGramForceCentimeters(double value) + public static Torque FromGramForceCentimeters(QuantityValue value) { return new Torque(value, TorqueUnit.GramForceCentimeter); } @@ -487,7 +469,7 @@ public static Torque FromGramForceCentimeters(double value) /// /// Creates a from . /// - public static Torque FromGramForceMeters(double value) + public static Torque FromGramForceMeters(QuantityValue value) { return new Torque(value, TorqueUnit.GramForceMeter); } @@ -495,7 +477,7 @@ public static Torque FromGramForceMeters(double value) /// /// Creates a from . /// - public static Torque FromGramForceMillimeters(double value) + public static Torque FromGramForceMillimeters(QuantityValue value) { return new Torque(value, TorqueUnit.GramForceMillimeter); } @@ -503,7 +485,7 @@ public static Torque FromGramForceMillimeters(double value) /// /// Creates a from . /// - public static Torque FromKilogramForceCentimeters(double value) + public static Torque FromKilogramForceCentimeters(QuantityValue value) { return new Torque(value, TorqueUnit.KilogramForceCentimeter); } @@ -511,7 +493,7 @@ public static Torque FromKilogramForceCentimeters(double value) /// /// Creates a from . /// - public static Torque FromKilogramForceMeters(double value) + public static Torque FromKilogramForceMeters(QuantityValue value) { return new Torque(value, TorqueUnit.KilogramForceMeter); } @@ -519,7 +501,7 @@ public static Torque FromKilogramForceMeters(double value) /// /// Creates a from . /// - public static Torque FromKilogramForceMillimeters(double value) + public static Torque FromKilogramForceMillimeters(QuantityValue value) { return new Torque(value, TorqueUnit.KilogramForceMillimeter); } @@ -527,7 +509,7 @@ public static Torque FromKilogramForceMillimeters(double value) /// /// Creates a from . /// - public static Torque FromKilonewtonCentimeters(double value) + public static Torque FromKilonewtonCentimeters(QuantityValue value) { return new Torque(value, TorqueUnit.KilonewtonCentimeter); } @@ -535,7 +517,7 @@ public static Torque FromKilonewtonCentimeters(double value) /// /// Creates a from . /// - public static Torque FromKilonewtonMeters(double value) + public static Torque FromKilonewtonMeters(QuantityValue value) { return new Torque(value, TorqueUnit.KilonewtonMeter); } @@ -543,7 +525,7 @@ public static Torque FromKilonewtonMeters(double value) /// /// Creates a from . /// - public static Torque FromKilonewtonMillimeters(double value) + public static Torque FromKilonewtonMillimeters(QuantityValue value) { return new Torque(value, TorqueUnit.KilonewtonMillimeter); } @@ -551,7 +533,7 @@ public static Torque FromKilonewtonMillimeters(double value) /// /// Creates a from . /// - public static Torque FromKilopoundForceFeet(double value) + public static Torque FromKilopoundForceFeet(QuantityValue value) { return new Torque(value, TorqueUnit.KilopoundForceFoot); } @@ -559,7 +541,7 @@ public static Torque FromKilopoundForceFeet(double value) /// /// Creates a from . /// - public static Torque FromKilopoundForceInches(double value) + public static Torque FromKilopoundForceInches(QuantityValue value) { return new Torque(value, TorqueUnit.KilopoundForceInch); } @@ -567,7 +549,7 @@ public static Torque FromKilopoundForceInches(double value) /// /// Creates a from . /// - public static Torque FromMeganewtonCentimeters(double value) + public static Torque FromMeganewtonCentimeters(QuantityValue value) { return new Torque(value, TorqueUnit.MeganewtonCentimeter); } @@ -575,7 +557,7 @@ public static Torque FromMeganewtonCentimeters(double value) /// /// Creates a from . /// - public static Torque FromMeganewtonMeters(double value) + public static Torque FromMeganewtonMeters(QuantityValue value) { return new Torque(value, TorqueUnit.MeganewtonMeter); } @@ -583,7 +565,7 @@ public static Torque FromMeganewtonMeters(double value) /// /// Creates a from . /// - public static Torque FromMeganewtonMillimeters(double value) + public static Torque FromMeganewtonMillimeters(QuantityValue value) { return new Torque(value, TorqueUnit.MeganewtonMillimeter); } @@ -591,7 +573,7 @@ public static Torque FromMeganewtonMillimeters(double value) /// /// Creates a from . /// - public static Torque FromMegapoundForceFeet(double value) + public static Torque FromMegapoundForceFeet(QuantityValue value) { return new Torque(value, TorqueUnit.MegapoundForceFoot); } @@ -599,7 +581,7 @@ public static Torque FromMegapoundForceFeet(double value) /// /// Creates a from . /// - public static Torque FromMegapoundForceInches(double value) + public static Torque FromMegapoundForceInches(QuantityValue value) { return new Torque(value, TorqueUnit.MegapoundForceInch); } @@ -607,7 +589,7 @@ public static Torque FromMegapoundForceInches(double value) /// /// Creates a from . /// - public static Torque FromNewtonCentimeters(double value) + public static Torque FromNewtonCentimeters(QuantityValue value) { return new Torque(value, TorqueUnit.NewtonCentimeter); } @@ -615,7 +597,7 @@ public static Torque FromNewtonCentimeters(double value) /// /// Creates a from . /// - public static Torque FromNewtonMeters(double value) + public static Torque FromNewtonMeters(QuantityValue value) { return new Torque(value, TorqueUnit.NewtonMeter); } @@ -623,7 +605,7 @@ public static Torque FromNewtonMeters(double value) /// /// Creates a from . /// - public static Torque FromNewtonMillimeters(double value) + public static Torque FromNewtonMillimeters(QuantityValue value) { return new Torque(value, TorqueUnit.NewtonMillimeter); } @@ -631,7 +613,7 @@ public static Torque FromNewtonMillimeters(double value) /// /// Creates a from . /// - public static Torque FromPoundalFeet(double value) + public static Torque FromPoundalFeet(QuantityValue value) { return new Torque(value, TorqueUnit.PoundalFoot); } @@ -639,7 +621,7 @@ public static Torque FromPoundalFeet(double value) /// /// Creates a from . /// - public static Torque FromPoundForceFeet(double value) + public static Torque FromPoundForceFeet(QuantityValue value) { return new Torque(value, TorqueUnit.PoundForceFoot); } @@ -647,7 +629,7 @@ public static Torque FromPoundForceFeet(double value) /// /// Creates a from . /// - public static Torque FromPoundForceInches(double value) + public static Torque FromPoundForceInches(QuantityValue value) { return new Torque(value, TorqueUnit.PoundForceInch); } @@ -655,7 +637,7 @@ public static Torque FromPoundForceInches(double value) /// /// Creates a from . /// - public static Torque FromTonneForceCentimeters(double value) + public static Torque FromTonneForceCentimeters(QuantityValue value) { return new Torque(value, TorqueUnit.TonneForceCentimeter); } @@ -663,7 +645,7 @@ public static Torque FromTonneForceCentimeters(double value) /// /// Creates a from . /// - public static Torque FromTonneForceMeters(double value) + public static Torque FromTonneForceMeters(QuantityValue value) { return new Torque(value, TorqueUnit.TonneForceMeter); } @@ -671,7 +653,7 @@ public static Torque FromTonneForceMeters(double value) /// /// Creates a from . /// - public static Torque FromTonneForceMillimeters(double value) + public static Torque FromTonneForceMillimeters(QuantityValue value) { return new Torque(value, TorqueUnit.TonneForceMillimeter); } @@ -682,7 +664,7 @@ public static Torque FromTonneForceMillimeters(double value) /// Value to convert from. /// Unit to convert from. /// Torque unit value. - public static Torque From(double value, TorqueUnit fromUnit) + public static Torque From(QuantityValue value, TorqueUnit fromUnit) { return new Torque(value, fromUnit); } @@ -743,10 +725,7 @@ public static Torque Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Torque Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -774,11 +753,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Torque result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Torque result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -799,7 +774,7 @@ public static TorqueUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -810,7 +785,7 @@ public static TorqueUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out TorqueUnit unit) { return TryParseUnit(str, null, out unit); @@ -825,7 +800,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out TorqueUnit u /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out TorqueUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -844,35 +819,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Torque operator +(Torque left, Torque right) { - return new Torque(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Torque(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Torque operator -(Torque left, Torque right) { - return new Torque(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Torque(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -930,97 +905,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Torque left, Torque right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Torque left, Torque right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Torque left, Torque right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Torque left, Torque right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Torque other, Torque tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Torque left, Torque right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Torque other, Torque tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Torque left, Torque right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Torque other, Torque tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Torque otherQuantity)) + if (obj is not Torque otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Torque other, Torque tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Torque other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Torque. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Torque), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Torque otherQuantity)) throw new ArgumentException("Expected type Torque.", nameof(obj)); + if (obj is not Torque otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1032,194 +992,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Torque other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TorqueUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Torque to another Torque with the unit representation . - /// - /// The unit to convert to. - /// A Torque with the specified unit. - public Torque ToUnit(TorqueUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Torque with the specified unit. - public Torque ToUnit(TorqueUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Torque), Unit, typeof(Torque), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Torque)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(TorqueUnit unit, [NotNullWhen(true)] out Torque? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Torque? convertedOrNull = (Unit, unit) switch - { - // TorqueUnit -> BaseUnit - (TorqueUnit.GramForceCentimeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665e-5, TorqueUnit.NewtonMeter), - (TorqueUnit.GramForceMeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665e-3, TorqueUnit.NewtonMeter), - (TorqueUnit.GramForceMillimeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665e-6, TorqueUnit.NewtonMeter), - (TorqueUnit.KilogramForceCentimeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665e-2, TorqueUnit.NewtonMeter), - (TorqueUnit.KilogramForceMeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665, TorqueUnit.NewtonMeter), - (TorqueUnit.KilogramForceMillimeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665e-3, TorqueUnit.NewtonMeter), - (TorqueUnit.KilonewtonCentimeter, TorqueUnit.NewtonMeter) => new Torque((_value * 0.01) * 1e3d, TorqueUnit.NewtonMeter), - (TorqueUnit.KilonewtonMeter, TorqueUnit.NewtonMeter) => new Torque((_value) * 1e3d, TorqueUnit.NewtonMeter), - (TorqueUnit.KilonewtonMillimeter, TorqueUnit.NewtonMeter) => new Torque((_value * 0.001) * 1e3d, TorqueUnit.NewtonMeter), - (TorqueUnit.KilopoundForceFoot, TorqueUnit.NewtonMeter) => new Torque((_value * 4.4482216152605 * 0.3048) * 1e3d, TorqueUnit.NewtonMeter), - (TorqueUnit.KilopoundForceInch, TorqueUnit.NewtonMeter) => new Torque((_value * 4.4482216152605 * 2.54e-2) * 1e3d, TorqueUnit.NewtonMeter), - (TorqueUnit.MeganewtonCentimeter, TorqueUnit.NewtonMeter) => new Torque((_value * 0.01) * 1e6d, TorqueUnit.NewtonMeter), - (TorqueUnit.MeganewtonMeter, TorqueUnit.NewtonMeter) => new Torque((_value) * 1e6d, TorqueUnit.NewtonMeter), - (TorqueUnit.MeganewtonMillimeter, TorqueUnit.NewtonMeter) => new Torque((_value * 0.001) * 1e6d, TorqueUnit.NewtonMeter), - (TorqueUnit.MegapoundForceFoot, TorqueUnit.NewtonMeter) => new Torque((_value * 4.4482216152605 * 0.3048) * 1e6d, TorqueUnit.NewtonMeter), - (TorqueUnit.MegapoundForceInch, TorqueUnit.NewtonMeter) => new Torque((_value * 4.4482216152605 * 2.54e-2) * 1e6d, TorqueUnit.NewtonMeter), - (TorqueUnit.NewtonCentimeter, TorqueUnit.NewtonMeter) => new Torque(_value * 0.01, TorqueUnit.NewtonMeter), - (TorqueUnit.NewtonMillimeter, TorqueUnit.NewtonMeter) => new Torque(_value * 0.001, TorqueUnit.NewtonMeter), - (TorqueUnit.PoundalFoot, TorqueUnit.NewtonMeter) => new Torque(_value * 0.138254954376 * 0.3048, TorqueUnit.NewtonMeter), - (TorqueUnit.PoundForceFoot, TorqueUnit.NewtonMeter) => new Torque(_value * 4.4482216152605 * 0.3048, TorqueUnit.NewtonMeter), - (TorqueUnit.PoundForceInch, TorqueUnit.NewtonMeter) => new Torque(_value * 4.4482216152605 * 2.54e-2, TorqueUnit.NewtonMeter), - (TorqueUnit.TonneForceCentimeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665e1, TorqueUnit.NewtonMeter), - (TorqueUnit.TonneForceMeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665e3, TorqueUnit.NewtonMeter), - (TorqueUnit.TonneForceMillimeter, TorqueUnit.NewtonMeter) => new Torque(_value * 9.80665, TorqueUnit.NewtonMeter), - - // BaseUnit -> TorqueUnit - (TorqueUnit.NewtonMeter, TorqueUnit.GramForceCentimeter) => new Torque(_value / 9.80665e-5, TorqueUnit.GramForceCentimeter), - (TorqueUnit.NewtonMeter, TorqueUnit.GramForceMeter) => new Torque(_value / 9.80665e-3, TorqueUnit.GramForceMeter), - (TorqueUnit.NewtonMeter, TorqueUnit.GramForceMillimeter) => new Torque(_value / 9.80665e-6, TorqueUnit.GramForceMillimeter), - (TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceCentimeter) => new Torque(_value / 9.80665e-2, TorqueUnit.KilogramForceCentimeter), - (TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceMeter) => new Torque(_value / 9.80665, TorqueUnit.KilogramForceMeter), - (TorqueUnit.NewtonMeter, TorqueUnit.KilogramForceMillimeter) => new Torque(_value / 9.80665e-3, TorqueUnit.KilogramForceMillimeter), - (TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonCentimeter) => new Torque((_value * 100) / 1e3d, TorqueUnit.KilonewtonCentimeter), - (TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonMeter) => new Torque((_value) / 1e3d, TorqueUnit.KilonewtonMeter), - (TorqueUnit.NewtonMeter, TorqueUnit.KilonewtonMillimeter) => new Torque((_value * 1000) / 1e3d, TorqueUnit.KilonewtonMillimeter), - (TorqueUnit.NewtonMeter, TorqueUnit.KilopoundForceFoot) => new Torque((_value / (4.4482216152605 * 0.3048)) / 1e3d, TorqueUnit.KilopoundForceFoot), - (TorqueUnit.NewtonMeter, TorqueUnit.KilopoundForceInch) => new Torque((_value / (4.4482216152605 * 2.54e-2)) / 1e3d, TorqueUnit.KilopoundForceInch), - (TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonCentimeter) => new Torque((_value * 100) / 1e6d, TorqueUnit.MeganewtonCentimeter), - (TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonMeter) => new Torque((_value) / 1e6d, TorqueUnit.MeganewtonMeter), - (TorqueUnit.NewtonMeter, TorqueUnit.MeganewtonMillimeter) => new Torque((_value * 1000) / 1e6d, TorqueUnit.MeganewtonMillimeter), - (TorqueUnit.NewtonMeter, TorqueUnit.MegapoundForceFoot) => new Torque((_value / (4.4482216152605 * 0.3048)) / 1e6d, TorqueUnit.MegapoundForceFoot), - (TorqueUnit.NewtonMeter, TorqueUnit.MegapoundForceInch) => new Torque((_value / (4.4482216152605 * 2.54e-2)) / 1e6d, TorqueUnit.MegapoundForceInch), - (TorqueUnit.NewtonMeter, TorqueUnit.NewtonCentimeter) => new Torque(_value * 100, TorqueUnit.NewtonCentimeter), - (TorqueUnit.NewtonMeter, TorqueUnit.NewtonMillimeter) => new Torque(_value * 1000, TorqueUnit.NewtonMillimeter), - (TorqueUnit.NewtonMeter, TorqueUnit.PoundalFoot) => new Torque(_value / (0.138254954376 * 0.3048), TorqueUnit.PoundalFoot), - (TorqueUnit.NewtonMeter, TorqueUnit.PoundForceFoot) => new Torque(_value / (4.4482216152605 * 0.3048), TorqueUnit.PoundForceFoot), - (TorqueUnit.NewtonMeter, TorqueUnit.PoundForceInch) => new Torque(_value / (4.4482216152605 * 2.54e-2), TorqueUnit.PoundForceInch), - (TorqueUnit.NewtonMeter, TorqueUnit.TonneForceCentimeter) => new Torque(_value / 9.80665e1, TorqueUnit.TonneForceCentimeter), - (TorqueUnit.NewtonMeter, TorqueUnit.TonneForceMeter) => new Torque(_value / 9.80665e3, TorqueUnit.TonneForceMeter), - (TorqueUnit.NewtonMeter, TorqueUnit.TonneForceMillimeter) => new Torque(_value / 9.80665, TorqueUnit.TonneForceMillimeter), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Torque ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not TorqueUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TorqueUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(TorqueUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(TorqueUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1234,7 +1024,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs b/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs index b200c36028..ae973e4c1f 100644 --- a/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Turbidity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Turbidity /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Turbidity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly TurbidityUnit? _unit; /// @@ -125,9 +124,7 @@ public static IEnumerable> GetDefaultMappings() static Turbidity() { - Info = TurbidityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(TurbidityInfo.CreateDefault); } /// @@ -135,7 +132,7 @@ static Turbidity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Turbidity(double value, TurbidityUnit unit) + public Turbidity(QuantityValue value, TurbidityUnit unit) { _value = value; _unit = unit; @@ -146,7 +143,8 @@ public Turbidity(double value, TurbidityUnit unit) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -175,10 +173,8 @@ public Turbidity(double value, TurbidityUnit unit) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public TurbidityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -217,28 +213,14 @@ public Turbidity(double value, TurbidityUnit unit) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NTU => As(TurbidityUnit.NTU); + public QuantityValue NTU => this.As(TurbidityUnit.NTU); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: TurbidityUnit -> BaseUnit - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(TurbidityUnit.NTU, TurbidityUnit.NTU, quantity => quantity); - - // Register in unit converter: BaseUnit -> TurbidityUnit - } - /// /// Get unit abbreviation string. /// @@ -267,7 +249,7 @@ public static string GetAbbreviation(TurbidityUnit unit, IFormatProvider? provid /// /// Creates a from . /// - public static Turbidity FromNTU(double value) + public static Turbidity FromNTU(QuantityValue value) { return new Turbidity(value, TurbidityUnit.NTU); } @@ -278,7 +260,7 @@ public static Turbidity FromNTU(double value) /// Value to convert from. /// Unit to convert from. /// Turbidity unit value. - public static Turbidity From(double value, TurbidityUnit fromUnit) + public static Turbidity From(QuantityValue value, TurbidityUnit fromUnit) { return new Turbidity(value, fromUnit); } @@ -339,10 +321,7 @@ public static Turbidity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Turbidity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -370,11 +349,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Turbidity result /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Turbidity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -395,7 +370,7 @@ public static TurbidityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -406,7 +381,7 @@ public static TurbidityUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out TurbidityUnit unit) { return TryParseUnit(str, null, out unit); @@ -421,7 +396,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out TurbidityUni /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out TurbidityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -440,35 +415,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Turbidity operator +(Turbidity left, Turbidity right) { - return new Turbidity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Turbidity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Turbidity operator -(Turbidity left, Turbidity right) { - return new Turbidity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Turbidity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -480,97 +455,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Turbidity left, Turbidity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Turbidity left, Turbidity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Turbidity left, Turbidity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Turbidity left, Turbidity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Turbidity other, Turbidity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Turbidity left, Turbidity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Turbidity other, Turbidity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Turbidity left, Turbidity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Turbidity other, Turbidity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Turbidity otherQuantity)) + if (obj is not Turbidity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Turbidity other, Turbidity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Turbidity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Turbidity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Turbidity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Turbidity otherQuantity)) throw new ArgumentException("Expected type Turbidity.", nameof(obj)); + if (obj is not Turbidity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -582,146 +542,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Turbidity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(TurbidityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this Turbidity to another Turbidity with the unit representation . - /// - /// The unit to convert to. - /// A Turbidity with the specified unit. - public Turbidity ToUnit(TurbidityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Turbidity with the specified unit. - public Turbidity ToUnit(TurbidityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Turbidity), Unit, typeof(Turbidity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Turbidity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(TurbidityUnit unit, [NotNullWhen(true)] out Turbidity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Turbidity? convertedOrNull = (Unit, unit) switch - { - // TurbidityUnit -> BaseUnit + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> TurbidityUnit - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Turbidity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not TurbidityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TurbidityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is TurbidityUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(TurbidityUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(TurbidityUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(TurbidityUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -736,7 +574,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs b/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs index fdb0ba3fa4..8ff5a60187 100644 --- a/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VitaminA.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// Vitamin A: 1 IU is the biological equivalent of 0.3 µg retinol, or of 0.6 µg beta-carotene. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct VitaminA : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly VitaminAUnit? _unit; /// @@ -122,9 +121,7 @@ public static IEnumerable> GetDefaultMappings() static VitaminA() { - Info = VitaminAInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(VitaminAInfo.CreateDefault); } /// @@ -132,7 +129,7 @@ static VitaminA() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public VitaminA(double value, VitaminAUnit unit) + public VitaminA(QuantityValue value, VitaminAUnit unit) { _value = value; _unit = unit; @@ -143,7 +140,8 @@ public VitaminA(double value, VitaminAUnit unit) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -172,10 +170,8 @@ public VitaminA(double value, VitaminAUnit unit) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public VitaminAUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -214,28 +210,14 @@ public VitaminA(double value, VitaminAUnit unit) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InternationalUnits => As(VitaminAUnit.InternationalUnit); + public QuantityValue InternationalUnits => this.As(VitaminAUnit.InternationalUnit); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: VitaminAUnit -> BaseUnit - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(VitaminAUnit.InternationalUnit, VitaminAUnit.InternationalUnit, quantity => quantity); - - // Register in unit converter: BaseUnit -> VitaminAUnit - } - /// /// Get unit abbreviation string. /// @@ -264,7 +246,7 @@ public static string GetAbbreviation(VitaminAUnit unit, IFormatProvider? provide /// /// Creates a from . /// - public static VitaminA FromInternationalUnits(double value) + public static VitaminA FromInternationalUnits(QuantityValue value) { return new VitaminA(value, VitaminAUnit.InternationalUnit); } @@ -275,7 +257,7 @@ public static VitaminA FromInternationalUnits(double value) /// Value to convert from. /// Unit to convert from. /// VitaminA unit value. - public static VitaminA From(double value, VitaminAUnit fromUnit) + public static VitaminA From(QuantityValue value, VitaminAUnit fromUnit) { return new VitaminA(value, fromUnit); } @@ -336,10 +318,7 @@ public static VitaminA Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static VitaminA Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -367,11 +346,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out VitaminA result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out VitaminA result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -392,7 +367,7 @@ public static VitaminAUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -403,7 +378,7 @@ public static VitaminAUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out VitaminAUnit unit) { return TryParseUnit(str, null, out unit); @@ -418,7 +393,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out VitaminAUnit /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out VitaminAUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -437,35 +412,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static VitaminA operator +(VitaminA left, VitaminA right) { - return new VitaminA(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new VitaminA(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static VitaminA operator -(VitaminA left, VitaminA right) { - return new VitaminA(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new VitaminA(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -477,97 +452,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(VitaminA left, VitaminA right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(VitaminA left, VitaminA right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(VitaminA left, VitaminA right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(VitaminA left, VitaminA right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(VitaminA other, VitaminA tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(VitaminA left, VitaminA right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(VitaminA other, VitaminA tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(VitaminA left, VitaminA right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(VitaminA other, VitaminA tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is VitaminA otherQuantity)) + if (obj is not VitaminA otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(VitaminA other, VitaminA tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(VitaminA other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current VitaminA. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(VitaminA), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is VitaminA otherQuantity)) throw new ArgumentException("Expected type VitaminA.", nameof(obj)); + if (obj is not VitaminA otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -579,146 +539,24 @@ public int CompareTo(object? obj) /// public int CompareTo(VitaminA other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VitaminAUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this VitaminA to another VitaminA with the unit representation . - /// - /// The unit to convert to. - /// A VitaminA with the specified unit. - public VitaminA ToUnit(VitaminAUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A VitaminA with the specified unit. - public VitaminA ToUnit(VitaminAUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(VitaminA), Unit, typeof(VitaminA), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (VitaminA)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(VitaminAUnit unit, [NotNullWhen(true)] out VitaminA? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - VitaminA? convertedOrNull = (Unit, unit) switch - { - // VitaminAUnit -> BaseUnit + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> VitaminAUnit - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public VitaminA ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not VitaminAUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VitaminAUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is VitaminAUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VitaminAUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(VitaminAUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(VitaminAUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -733,7 +571,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/Volume.g.cs b/UnitsNet/GeneratedCode/Quantities/Volume.g.cs index 5d02cc4e84..9f8b0214fc 100644 --- a/UnitsNet/GeneratedCode/Quantities/Volume.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/Volume.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct Volume : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -65,13 +64,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly VolumeUnit? _unit; /// @@ -116,7 +115,7 @@ public static VolumeInfo CreateDefault(Func - /// The for is [L^3]. + /// The for is L^3. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(3, 0, 0, 0, 0, 0, 0); @@ -131,68 +130,172 @@ public static VolumeInfo CreateDefault(FuncAn of representing the default unit mappings for Volume. public static IEnumerable> GetDefaultMappings() { - yield return new (VolumeUnit.AcreFoot, "AcreFoot", "AcreFeet", BaseUnits.Undefined); - yield return new (VolumeUnit.AuTablespoon, "AuTablespoon", "AuTablespoons", BaseUnits.Undefined); - yield return new (VolumeUnit.BoardFoot, "BoardFoot", "BoardFeet", BaseUnits.Undefined); - yield return new (VolumeUnit.Centiliter, "Centiliter", "Centiliters", BaseUnits.Undefined); - yield return new (VolumeUnit.CubicCentimeter, "CubicCentimeter", "CubicCentimeters", new BaseUnits(length: LengthUnit.Centimeter)); - yield return new (VolumeUnit.CubicDecimeter, "CubicDecimeter", "CubicDecimeters", new BaseUnits(length: LengthUnit.Decimeter)); - yield return new (VolumeUnit.CubicFoot, "CubicFoot", "CubicFeet", new BaseUnits(length: LengthUnit.Foot)); - yield return new (VolumeUnit.CubicHectometer, "CubicHectometer", "CubicHectometers", new BaseUnits(length: LengthUnit.Hectometer)); - yield return new (VolumeUnit.CubicInch, "CubicInch", "CubicInches", new BaseUnits(length: LengthUnit.Inch)); - yield return new (VolumeUnit.CubicKilometer, "CubicKilometer", "CubicKilometers", new BaseUnits(length: LengthUnit.Kilometer)); + yield return new (VolumeUnit.AcreFoot, "AcreFoot", "AcreFeet", BaseUnits.Undefined, + new QuantityValue(48828125, 60228605349) + ); + yield return new (VolumeUnit.AuTablespoon, "AuTablespoon", "AuTablespoons", BaseUnits.Undefined, + 50000 + ); + yield return new (VolumeUnit.BoardFoot, "BoardFoot", "BoardFeet", BaseUnits.Undefined, + new QuantityValue(7812500000, 18435447) + ); + yield return new (VolumeUnit.Centiliter, "Centiliter", "Centiliters", BaseUnits.Undefined, + 100000 + ); + yield return new (VolumeUnit.CubicCentimeter, "CubicCentimeter", "CubicCentimeters", new BaseUnits(length: LengthUnit.Centimeter), + 1000000 + ); + yield return new (VolumeUnit.CubicDecimeter, "CubicDecimeter", "CubicDecimeters", new BaseUnits(length: LengthUnit.Decimeter), + 1000 + ); + yield return new (VolumeUnit.CubicFoot, "CubicFoot", "CubicFeet", new BaseUnits(length: LengthUnit.Foot), + new QuantityValue(1953125000, 55306341) + ); + yield return new (VolumeUnit.CubicHectometer, "CubicHectometer", "CubicHectometers", new BaseUnits(length: LengthUnit.Hectometer), + new QuantityValue(1, 1000000) + ); + yield return new (VolumeUnit.CubicInch, "CubicInch", "CubicInches", new BaseUnits(length: LengthUnit.Inch), + new QuantityValue(125000000000, 2048383) + ); + yield return new (VolumeUnit.CubicKilometer, "CubicKilometer", "CubicKilometers", new BaseUnits(length: LengthUnit.Kilometer), + new QuantityValue(1, 1000000000) + ); yield return new (VolumeUnit.CubicMeter, "CubicMeter", "CubicMeters", new BaseUnits(length: LengthUnit.Meter)); - yield return new (VolumeUnit.CubicMicrometer, "CubicMicrometer", "CubicMicrometers", new BaseUnits(length: LengthUnit.Micrometer)); - yield return new (VolumeUnit.CubicMile, "CubicMile", "CubicMiles", new BaseUnits(length: LengthUnit.Mile)); - yield return new (VolumeUnit.CubicMillimeter, "CubicMillimeter", "CubicMillimeters", new BaseUnits(length: LengthUnit.Millimeter)); - yield return new (VolumeUnit.CubicYard, "CubicYard", "CubicYards", new BaseUnits(length: LengthUnit.Yard)); - yield return new (VolumeUnit.Decaliter, "Decaliter", "Decaliters", BaseUnits.Undefined); - yield return new (VolumeUnit.DecausGallon, "DecausGallon", "DecausGallons", BaseUnits.Undefined); - yield return new (VolumeUnit.Deciliter, "Deciliter", "Deciliters", BaseUnits.Undefined); - yield return new (VolumeUnit.DeciusGallon, "DeciusGallon", "DeciusGallons", BaseUnits.Undefined); - yield return new (VolumeUnit.HectocubicFoot, "HectocubicFoot", "HectocubicFeet", BaseUnits.Undefined); - yield return new (VolumeUnit.HectocubicMeter, "HectocubicMeter", "HectocubicMeters", BaseUnits.Undefined); - yield return new (VolumeUnit.Hectoliter, "Hectoliter", "Hectoliters", BaseUnits.Undefined); - yield return new (VolumeUnit.HectousGallon, "HectousGallon", "HectousGallons", BaseUnits.Undefined); - yield return new (VolumeUnit.ImperialBeerBarrel, "ImperialBeerBarrel", "ImperialBeerBarrels", BaseUnits.Undefined); - yield return new (VolumeUnit.ImperialGallon, "ImperialGallon", "ImperialGallons", BaseUnits.Undefined); - yield return new (VolumeUnit.ImperialOunce, "ImperialOunce", "ImperialOunces", BaseUnits.Undefined); - yield return new (VolumeUnit.ImperialPint, "ImperialPint", "ImperialPints", BaseUnits.Undefined); - yield return new (VolumeUnit.ImperialQuart, "ImperialQuart", "ImperialQuarts", BaseUnits.Undefined); - yield return new (VolumeUnit.KilocubicFoot, "KilocubicFoot", "KilocubicFeet", BaseUnits.Undefined); - yield return new (VolumeUnit.KilocubicMeter, "KilocubicMeter", "KilocubicMeters", new BaseUnits(length: LengthUnit.Decameter)); - yield return new (VolumeUnit.KiloimperialGallon, "KiloimperialGallon", "KiloimperialGallons", BaseUnits.Undefined); - yield return new (VolumeUnit.Kiloliter, "Kiloliter", "Kiloliters", new BaseUnits(length: LengthUnit.Meter)); - yield return new (VolumeUnit.KilousGallon, "KilousGallon", "KilousGallons", BaseUnits.Undefined); - yield return new (VolumeUnit.Liter, "Liter", "Liters", new BaseUnits(length: LengthUnit.Decimeter)); - yield return new (VolumeUnit.MegacubicFoot, "MegacubicFoot", "MegacubicFeet", BaseUnits.Undefined); - yield return new (VolumeUnit.MegaimperialGallon, "MegaimperialGallon", "MegaimperialGallons", BaseUnits.Undefined); - yield return new (VolumeUnit.Megaliter, "Megaliter", "Megaliters", new BaseUnits(length: LengthUnit.Decameter)); - yield return new (VolumeUnit.MegausGallon, "MegausGallon", "MegausGallons", BaseUnits.Undefined); - yield return new (VolumeUnit.MetricCup, "MetricCup", "MetricCups", BaseUnits.Undefined); - yield return new (VolumeUnit.MetricTeaspoon, "MetricTeaspoon", "MetricTeaspoons", BaseUnits.Undefined); - yield return new (VolumeUnit.Microliter, "Microliter", "Microliters", new BaseUnits(length: LengthUnit.Millimeter)); - yield return new (VolumeUnit.Milliliter, "Milliliter", "Milliliters", new BaseUnits(length: LengthUnit.Centimeter)); - yield return new (VolumeUnit.Nanoliter, "Nanoliter", "Nanoliters", BaseUnits.Undefined); - yield return new (VolumeUnit.OilBarrel, "OilBarrel", "OilBarrels", BaseUnits.Undefined); - yield return new (VolumeUnit.UkTablespoon, "UkTablespoon", "UkTablespoons", BaseUnits.Undefined); - yield return new (VolumeUnit.UsBeerBarrel, "UsBeerBarrel", "UsBeerBarrels", BaseUnits.Undefined); - yield return new (VolumeUnit.UsCustomaryCup, "UsCustomaryCup", "UsCustomaryCups", BaseUnits.Undefined); - yield return new (VolumeUnit.UsGallon, "UsGallon", "UsGallons", BaseUnits.Undefined); - yield return new (VolumeUnit.UsLegalCup, "UsLegalCup", "UsLegalCups", BaseUnits.Undefined); - yield return new (VolumeUnit.UsOunce, "UsOunce", "UsOunces", BaseUnits.Undefined); - yield return new (VolumeUnit.UsPint, "UsPint", "UsPints", BaseUnits.Undefined); - yield return new (VolumeUnit.UsQuart, "UsQuart", "UsQuarts", BaseUnits.Undefined); - yield return new (VolumeUnit.UsTablespoon, "UsTablespoon", "UsTablespoons", BaseUnits.Undefined); - yield return new (VolumeUnit.UsTeaspoon, "UsTeaspoon", "UsTeaspoons", BaseUnits.Undefined); + yield return new (VolumeUnit.CubicMicrometer, "CubicMicrometer", "CubicMicrometers", new BaseUnits(length: LengthUnit.Micrometer), + 1000000000000000000 + ); + yield return new (VolumeUnit.CubicMile, "CubicMile", "CubicMiles", new BaseUnits(length: LengthUnit.Mile), + new QuantityValue(1953125, 8140980127813632) + ); + yield return new (VolumeUnit.CubicMillimeter, "CubicMillimeter", "CubicMillimeters", new BaseUnits(length: LengthUnit.Millimeter), + 1000000000 + ); + yield return new (VolumeUnit.CubicYard, "CubicYard", "CubicYards", new BaseUnits(length: LengthUnit.Yard), + new QuantityValue(1953125000, 1493271207) + ); + yield return new (VolumeUnit.Decaliter, "Decaliter", "Decaliters", BaseUnits.Undefined, + 100 + ); + yield return new (VolumeUnit.DecausGallon, "DecausGallon", "DecausGallons", BaseUnits.Undefined, + new QuantityValue(12500000000, 473176473) + ); + yield return new (VolumeUnit.Deciliter, "Deciliter", "Deciliters", BaseUnits.Undefined, + 10000 + ); + yield return new (VolumeUnit.DeciusGallon, "DeciusGallon", "DeciusGallons", BaseUnits.Undefined, + new QuantityValue(1250000000000, 473176473) + ); + yield return new (VolumeUnit.HectocubicFoot, "HectocubicFoot", "HectocubicFeet", BaseUnits.Undefined, + new QuantityValue(19531250, 55306341) + ); + yield return new (VolumeUnit.HectocubicMeter, "HectocubicMeter", "HectocubicMeters", BaseUnits.Undefined, + new QuantityValue(1, 100) + ); + yield return new (VolumeUnit.Hectoliter, "Hectoliter", "Hectoliters", BaseUnits.Undefined, + 10 + ); + yield return new (VolumeUnit.HectousGallon, "HectousGallon", "HectousGallons", BaseUnits.Undefined, + new QuantityValue(1250000000, 473176473) + ); + yield return new (VolumeUnit.ImperialBeerBarrel, "ImperialBeerBarrel", "ImperialBeerBarrels", BaseUnits.Undefined, + new QuantityValue(25000000, 4091481) + ); + yield return new (VolumeUnit.ImperialGallon, "ImperialGallon", "ImperialGallons", BaseUnits.Undefined, + new QuantityValue(100000000, 454609) + ); + yield return new (VolumeUnit.ImperialOunce, "ImperialOunce", "ImperialOunces", BaseUnits.Undefined, + new QuantityValue(16000000000, 454609) + ); + yield return new (VolumeUnit.ImperialPint, "ImperialPint", "ImperialPints", BaseUnits.Undefined, + new QuantityValue(800000000, 454609) + ); + yield return new (VolumeUnit.ImperialQuart, "ImperialQuart", "ImperialQuarts", BaseUnits.Undefined, + new QuantityValue(400000000, 454609) + ); + yield return new (VolumeUnit.KilocubicFoot, "KilocubicFoot", "KilocubicFeet", BaseUnits.Undefined, + new QuantityValue(1953125, 55306341) + ); + yield return new (VolumeUnit.KilocubicMeter, "KilocubicMeter", "KilocubicMeters", new BaseUnits(length: LengthUnit.Decameter), + new QuantityValue(1, 1000) + ); + yield return new (VolumeUnit.KiloimperialGallon, "KiloimperialGallon", "KiloimperialGallons", BaseUnits.Undefined, + new QuantityValue(100000, 454609) + ); + yield return new (VolumeUnit.Kiloliter, "Kiloliter", "Kiloliters", new BaseUnits(length: LengthUnit.Meter), + 1 + ); + yield return new (VolumeUnit.KilousGallon, "KilousGallon", "KilousGallons", BaseUnits.Undefined, + new QuantityValue(125000000, 473176473) + ); + yield return new (VolumeUnit.Liter, "Liter", "Liters", new BaseUnits(length: LengthUnit.Decimeter), + 1000 + ); + yield return new (VolumeUnit.MegacubicFoot, "MegacubicFoot", "MegacubicFeet", BaseUnits.Undefined, + new QuantityValue(15625, 442450728) + ); + yield return new (VolumeUnit.MegaimperialGallon, "MegaimperialGallon", "MegaimperialGallons", BaseUnits.Undefined, + new QuantityValue(100, 454609) + ); + yield return new (VolumeUnit.Megaliter, "Megaliter", "Megaliters", new BaseUnits(length: LengthUnit.Decameter), + new QuantityValue(1, 1000) + ); + yield return new (VolumeUnit.MegausGallon, "MegausGallon", "MegausGallons", BaseUnits.Undefined, + new QuantityValue(125000, 473176473) + ); + yield return new (VolumeUnit.MetricCup, "MetricCup", "MetricCups", BaseUnits.Undefined, + 4000 + ); + yield return new (VolumeUnit.MetricTeaspoon, "MetricTeaspoon", "MetricTeaspoons", BaseUnits.Undefined, + 200000 + ); + yield return new (VolumeUnit.Microliter, "Microliter", "Microliters", new BaseUnits(length: LengthUnit.Millimeter), + 1000000000 + ); + yield return new (VolumeUnit.Milliliter, "Milliliter", "Milliliters", new BaseUnits(length: LengthUnit.Centimeter), + 1000000 + ); + yield return new (VolumeUnit.Nanoliter, "Nanoliter", "Nanoliters", BaseUnits.Undefined, + 1000000000000 + ); + yield return new (VolumeUnit.OilBarrel, "OilBarrel", "OilBarrels", BaseUnits.Undefined, + new QuantityValue(62500000000, 9936705933) + ); + yield return new (VolumeUnit.UkTablespoon, "UkTablespoon", "UkTablespoons", BaseUnits.Undefined, + new QuantityValue(200000, 3) + ); + yield return new (VolumeUnit.UsBeerBarrel, "UsBeerBarrel", "UsBeerBarrels", BaseUnits.Undefined, + new QuantityValue(125000000000, 14668470663) + ); + yield return new (VolumeUnit.UsCustomaryCup, "UsCustomaryCup", "UsCustomaryCups", BaseUnits.Undefined, + new QuantityValue(2000000000000, 473176473) + ); + yield return new (VolumeUnit.UsGallon, "UsGallon", "UsGallons", BaseUnits.Undefined, + new QuantityValue(125000000000, 473176473) + ); + yield return new (VolumeUnit.UsLegalCup, "UsLegalCup", "UsLegalCups", BaseUnits.Undefined, + new QuantityValue(12500, 3) + ); + yield return new (VolumeUnit.UsOunce, "UsOunce", "UsOunces", BaseUnits.Undefined, + new QuantityValue(16000000000000, 473176473) + ); + yield return new (VolumeUnit.UsPint, "UsPint", "UsPints", BaseUnits.Undefined, + new QuantityValue(1000000000000, 473176473) + ); + yield return new (VolumeUnit.UsQuart, "UsQuart", "UsQuarts", BaseUnits.Undefined, + new QuantityValue(500000000000, 473176473) + ); + yield return new (VolumeUnit.UsTablespoon, "UsTablespoon", "UsTablespoons", BaseUnits.Undefined, + new QuantityValue(32000000000000, 473176473) + ); + yield return new (VolumeUnit.UsTeaspoon, "UsTeaspoon", "UsTeaspoons", BaseUnits.Undefined, + new QuantityValue(32000000000000, 157725491) + ); } } static Volume() { - Info = VolumeInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(VolumeInfo.CreateDefault); } /// @@ -200,7 +303,7 @@ static Volume() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public Volume(double value, VolumeUnit unit) + public Volume(QuantityValue value, VolumeUnit unit) { _value = value; _unit = unit; @@ -214,7 +317,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -225,7 +328,8 @@ public Volume(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -254,10 +358,8 @@ public Volume(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public VolumeUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -296,399 +398,279 @@ public Volume(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AcreFeet => As(VolumeUnit.AcreFoot); + public QuantityValue AcreFeet => this.As(VolumeUnit.AcreFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AuTablespoons => As(VolumeUnit.AuTablespoon); + public QuantityValue AuTablespoons => this.As(VolumeUnit.AuTablespoon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BoardFeet => As(VolumeUnit.BoardFoot); + public QuantityValue BoardFeet => this.As(VolumeUnit.BoardFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Centiliters => As(VolumeUnit.Centiliter); + public QuantityValue Centiliters => this.As(VolumeUnit.Centiliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicCentimeters => As(VolumeUnit.CubicCentimeter); + public QuantityValue CubicCentimeters => this.As(VolumeUnit.CubicCentimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicDecimeters => As(VolumeUnit.CubicDecimeter); + public QuantityValue CubicDecimeters => this.As(VolumeUnit.CubicDecimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicFeet => As(VolumeUnit.CubicFoot); + public QuantityValue CubicFeet => this.As(VolumeUnit.CubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicHectometers => As(VolumeUnit.CubicHectometer); + public QuantityValue CubicHectometers => this.As(VolumeUnit.CubicHectometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicInches => As(VolumeUnit.CubicInch); + public QuantityValue CubicInches => this.As(VolumeUnit.CubicInch); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicKilometers => As(VolumeUnit.CubicKilometer); + public QuantityValue CubicKilometers => this.As(VolumeUnit.CubicKilometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicMeters => As(VolumeUnit.CubicMeter); + public QuantityValue CubicMeters => this.As(VolumeUnit.CubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicMicrometers => As(VolumeUnit.CubicMicrometer); + public QuantityValue CubicMicrometers => this.As(VolumeUnit.CubicMicrometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicMiles => As(VolumeUnit.CubicMile); + public QuantityValue CubicMiles => this.As(VolumeUnit.CubicMile); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicMillimeters => As(VolumeUnit.CubicMillimeter); + public QuantityValue CubicMillimeters => this.As(VolumeUnit.CubicMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicYards => As(VolumeUnit.CubicYard); + public QuantityValue CubicYards => this.As(VolumeUnit.CubicYard); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Decaliters => As(VolumeUnit.Decaliter); + public QuantityValue Decaliters => this.As(VolumeUnit.Decaliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecausGallons => As(VolumeUnit.DecausGallon); + public QuantityValue DecausGallons => this.As(VolumeUnit.DecausGallon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Deciliters => As(VolumeUnit.Deciliter); + public QuantityValue Deciliters => this.As(VolumeUnit.Deciliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DeciusGallons => As(VolumeUnit.DeciusGallon); + public QuantityValue DeciusGallons => this.As(VolumeUnit.DeciusGallon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HectocubicFeet => As(VolumeUnit.HectocubicFoot); + public QuantityValue HectocubicFeet => this.As(VolumeUnit.HectocubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HectocubicMeters => As(VolumeUnit.HectocubicMeter); + public QuantityValue HectocubicMeters => this.As(VolumeUnit.HectocubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Hectoliters => As(VolumeUnit.Hectoliter); + public QuantityValue Hectoliters => this.As(VolumeUnit.Hectoliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HectousGallons => As(VolumeUnit.HectousGallon); + public QuantityValue HectousGallons => this.As(VolumeUnit.HectousGallon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ImperialBeerBarrels => As(VolumeUnit.ImperialBeerBarrel); + public QuantityValue ImperialBeerBarrels => this.As(VolumeUnit.ImperialBeerBarrel); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ImperialGallons => As(VolumeUnit.ImperialGallon); + public QuantityValue ImperialGallons => this.As(VolumeUnit.ImperialGallon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ImperialOunces => As(VolumeUnit.ImperialOunce); + public QuantityValue ImperialOunces => this.As(VolumeUnit.ImperialOunce); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ImperialPints => As(VolumeUnit.ImperialPint); + public QuantityValue ImperialPints => this.As(VolumeUnit.ImperialPint); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ImperialQuarts => As(VolumeUnit.ImperialQuart); + public QuantityValue ImperialQuarts => this.As(VolumeUnit.ImperialQuart); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilocubicFeet => As(VolumeUnit.KilocubicFoot); + public QuantityValue KilocubicFeet => this.As(VolumeUnit.KilocubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilocubicMeters => As(VolumeUnit.KilocubicMeter); + public QuantityValue KilocubicMeters => this.As(VolumeUnit.KilocubicMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KiloimperialGallons => As(VolumeUnit.KiloimperialGallon); + public QuantityValue KiloimperialGallons => this.As(VolumeUnit.KiloimperialGallon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Kiloliters => As(VolumeUnit.Kiloliter); + public QuantityValue Kiloliters => this.As(VolumeUnit.Kiloliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilousGallons => As(VolumeUnit.KilousGallon); + public QuantityValue KilousGallons => this.As(VolumeUnit.KilousGallon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Liters => As(VolumeUnit.Liter); + public QuantityValue Liters => this.As(VolumeUnit.Liter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegacubicFeet => As(VolumeUnit.MegacubicFoot); + public QuantityValue MegacubicFeet => this.As(VolumeUnit.MegacubicFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegaimperialGallons => As(VolumeUnit.MegaimperialGallon); + public QuantityValue MegaimperialGallons => this.As(VolumeUnit.MegaimperialGallon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Megaliters => As(VolumeUnit.Megaliter); + public QuantityValue Megaliters => this.As(VolumeUnit.Megaliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegausGallons => As(VolumeUnit.MegausGallon); + public QuantityValue MegausGallons => this.As(VolumeUnit.MegausGallon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MetricCups => As(VolumeUnit.MetricCup); + public QuantityValue MetricCups => this.As(VolumeUnit.MetricCup); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MetricTeaspoons => As(VolumeUnit.MetricTeaspoon); + public QuantityValue MetricTeaspoons => this.As(VolumeUnit.MetricTeaspoon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Microliters => As(VolumeUnit.Microliter); + public QuantityValue Microliters => this.As(VolumeUnit.Microliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Milliliters => As(VolumeUnit.Milliliter); + public QuantityValue Milliliters => this.As(VolumeUnit.Milliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Nanoliters => As(VolumeUnit.Nanoliter); + public QuantityValue Nanoliters => this.As(VolumeUnit.Nanoliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double OilBarrels => As(VolumeUnit.OilBarrel); + public QuantityValue OilBarrels => this.As(VolumeUnit.OilBarrel); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UkTablespoons => As(VolumeUnit.UkTablespoon); + public QuantityValue UkTablespoons => this.As(VolumeUnit.UkTablespoon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsBeerBarrels => As(VolumeUnit.UsBeerBarrel); + public QuantityValue UsBeerBarrels => this.As(VolumeUnit.UsBeerBarrel); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsCustomaryCups => As(VolumeUnit.UsCustomaryCup); + public QuantityValue UsCustomaryCups => this.As(VolumeUnit.UsCustomaryCup); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsGallons => As(VolumeUnit.UsGallon); + public QuantityValue UsGallons => this.As(VolumeUnit.UsGallon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsLegalCups => As(VolumeUnit.UsLegalCup); + public QuantityValue UsLegalCups => this.As(VolumeUnit.UsLegalCup); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsOunces => As(VolumeUnit.UsOunce); + public QuantityValue UsOunces => this.As(VolumeUnit.UsOunce); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsPints => As(VolumeUnit.UsPint); + public QuantityValue UsPints => this.As(VolumeUnit.UsPint); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsQuarts => As(VolumeUnit.UsQuart); + public QuantityValue UsQuarts => this.As(VolumeUnit.UsQuart); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsTablespoons => As(VolumeUnit.UsTablespoon); + public QuantityValue UsTablespoons => this.As(VolumeUnit.UsTablespoon); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsTeaspoons => As(VolumeUnit.UsTeaspoon); + public QuantityValue UsTeaspoons => this.As(VolumeUnit.UsTeaspoon); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: VolumeUnit -> BaseUnit - unitConverter.SetConversionFunction(VolumeUnit.AcreFoot, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.AuTablespoon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.BoardFoot, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.Centiliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicCentimeter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicDecimeter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicFoot, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicHectometer, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicInch, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicKilometer, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMicrometer, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMile, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMillimeter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicYard, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.Decaliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.DecausGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.Deciliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.DeciusGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.HectocubicFoot, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.HectocubicMeter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.Hectoliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.HectousGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.ImperialBeerBarrel, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.ImperialGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.ImperialOunce, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.ImperialPint, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.ImperialQuart, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.KilocubicFoot, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.KilocubicMeter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.KiloimperialGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.Kiloliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.KilousGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.Liter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.MegacubicFoot, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.MegaimperialGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.Megaliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.MegausGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.MetricCup, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.MetricTeaspoon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.Microliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.Milliliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.Nanoliter, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.OilBarrel, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.UkTablespoon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.UsBeerBarrel, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.UsCustomaryCup, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.UsGallon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.UsLegalCup, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.UsOunce, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.UsPint, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.UsQuart, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.UsTablespoon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.UsTeaspoon, VolumeUnit.CubicMeter, quantity => quantity.ToUnit(VolumeUnit.CubicMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> VolumeUnit - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.AcreFoot, quantity => quantity.ToUnit(VolumeUnit.AcreFoot)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.AuTablespoon, quantity => quantity.ToUnit(VolumeUnit.AuTablespoon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.BoardFoot, quantity => quantity.ToUnit(VolumeUnit.BoardFoot)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Centiliter, quantity => quantity.ToUnit(VolumeUnit.Centiliter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicCentimeter, quantity => quantity.ToUnit(VolumeUnit.CubicCentimeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicDecimeter, quantity => quantity.ToUnit(VolumeUnit.CubicDecimeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicFoot, quantity => quantity.ToUnit(VolumeUnit.CubicFoot)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicHectometer, quantity => quantity.ToUnit(VolumeUnit.CubicHectometer)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicInch, quantity => quantity.ToUnit(VolumeUnit.CubicInch)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicKilometer, quantity => quantity.ToUnit(VolumeUnit.CubicKilometer)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicMicrometer, quantity => quantity.ToUnit(VolumeUnit.CubicMicrometer)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicMile, quantity => quantity.ToUnit(VolumeUnit.CubicMile)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicMillimeter, quantity => quantity.ToUnit(VolumeUnit.CubicMillimeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.CubicYard, quantity => quantity.ToUnit(VolumeUnit.CubicYard)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Decaliter, quantity => quantity.ToUnit(VolumeUnit.Decaliter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.DecausGallon, quantity => quantity.ToUnit(VolumeUnit.DecausGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Deciliter, quantity => quantity.ToUnit(VolumeUnit.Deciliter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.DeciusGallon, quantity => quantity.ToUnit(VolumeUnit.DeciusGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.HectocubicFoot, quantity => quantity.ToUnit(VolumeUnit.HectocubicFoot)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.HectocubicMeter, quantity => quantity.ToUnit(VolumeUnit.HectocubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Hectoliter, quantity => quantity.ToUnit(VolumeUnit.Hectoliter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.HectousGallon, quantity => quantity.ToUnit(VolumeUnit.HectousGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.ImperialBeerBarrel, quantity => quantity.ToUnit(VolumeUnit.ImperialBeerBarrel)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.ImperialGallon, quantity => quantity.ToUnit(VolumeUnit.ImperialGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.ImperialOunce, quantity => quantity.ToUnit(VolumeUnit.ImperialOunce)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.ImperialPint, quantity => quantity.ToUnit(VolumeUnit.ImperialPint)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.ImperialQuart, quantity => quantity.ToUnit(VolumeUnit.ImperialQuart)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.KilocubicFoot, quantity => quantity.ToUnit(VolumeUnit.KilocubicFoot)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.KilocubicMeter, quantity => quantity.ToUnit(VolumeUnit.KilocubicMeter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.KiloimperialGallon, quantity => quantity.ToUnit(VolumeUnit.KiloimperialGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Kiloliter, quantity => quantity.ToUnit(VolumeUnit.Kiloliter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.KilousGallon, quantity => quantity.ToUnit(VolumeUnit.KilousGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Liter, quantity => quantity.ToUnit(VolumeUnit.Liter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.MegacubicFoot, quantity => quantity.ToUnit(VolumeUnit.MegacubicFoot)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.MegaimperialGallon, quantity => quantity.ToUnit(VolumeUnit.MegaimperialGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Megaliter, quantity => quantity.ToUnit(VolumeUnit.Megaliter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.MegausGallon, quantity => quantity.ToUnit(VolumeUnit.MegausGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.MetricCup, quantity => quantity.ToUnit(VolumeUnit.MetricCup)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.MetricTeaspoon, quantity => quantity.ToUnit(VolumeUnit.MetricTeaspoon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Microliter, quantity => quantity.ToUnit(VolumeUnit.Microliter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Milliliter, quantity => quantity.ToUnit(VolumeUnit.Milliliter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.Nanoliter, quantity => quantity.ToUnit(VolumeUnit.Nanoliter)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.OilBarrel, quantity => quantity.ToUnit(VolumeUnit.OilBarrel)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UkTablespoon, quantity => quantity.ToUnit(VolumeUnit.UkTablespoon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsBeerBarrel, quantity => quantity.ToUnit(VolumeUnit.UsBeerBarrel)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsCustomaryCup, quantity => quantity.ToUnit(VolumeUnit.UsCustomaryCup)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsGallon, quantity => quantity.ToUnit(VolumeUnit.UsGallon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsLegalCup, quantity => quantity.ToUnit(VolumeUnit.UsLegalCup)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsOunce, quantity => quantity.ToUnit(VolumeUnit.UsOunce)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsPint, quantity => quantity.ToUnit(VolumeUnit.UsPint)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsQuart, quantity => quantity.ToUnit(VolumeUnit.UsQuart)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsTablespoon, quantity => quantity.ToUnit(VolumeUnit.UsTablespoon)); - unitConverter.SetConversionFunction(VolumeUnit.CubicMeter, VolumeUnit.UsTeaspoon, quantity => quantity.ToUnit(VolumeUnit.UsTeaspoon)); - } - /// /// Get unit abbreviation string. /// @@ -717,7 +699,7 @@ public static string GetAbbreviation(VolumeUnit unit, IFormatProvider? provider) /// /// Creates a from . /// - public static Volume FromAcreFeet(double value) + public static Volume FromAcreFeet(QuantityValue value) { return new Volume(value, VolumeUnit.AcreFoot); } @@ -725,7 +707,7 @@ public static Volume FromAcreFeet(double value) /// /// Creates a from . /// - public static Volume FromAuTablespoons(double value) + public static Volume FromAuTablespoons(QuantityValue value) { return new Volume(value, VolumeUnit.AuTablespoon); } @@ -733,7 +715,7 @@ public static Volume FromAuTablespoons(double value) /// /// Creates a from . /// - public static Volume FromBoardFeet(double value) + public static Volume FromBoardFeet(QuantityValue value) { return new Volume(value, VolumeUnit.BoardFoot); } @@ -741,7 +723,7 @@ public static Volume FromBoardFeet(double value) /// /// Creates a from . /// - public static Volume FromCentiliters(double value) + public static Volume FromCentiliters(QuantityValue value) { return new Volume(value, VolumeUnit.Centiliter); } @@ -749,7 +731,7 @@ public static Volume FromCentiliters(double value) /// /// Creates a from . /// - public static Volume FromCubicCentimeters(double value) + public static Volume FromCubicCentimeters(QuantityValue value) { return new Volume(value, VolumeUnit.CubicCentimeter); } @@ -757,7 +739,7 @@ public static Volume FromCubicCentimeters(double value) /// /// Creates a from . /// - public static Volume FromCubicDecimeters(double value) + public static Volume FromCubicDecimeters(QuantityValue value) { return new Volume(value, VolumeUnit.CubicDecimeter); } @@ -765,7 +747,7 @@ public static Volume FromCubicDecimeters(double value) /// /// Creates a from . /// - public static Volume FromCubicFeet(double value) + public static Volume FromCubicFeet(QuantityValue value) { return new Volume(value, VolumeUnit.CubicFoot); } @@ -773,7 +755,7 @@ public static Volume FromCubicFeet(double value) /// /// Creates a from . /// - public static Volume FromCubicHectometers(double value) + public static Volume FromCubicHectometers(QuantityValue value) { return new Volume(value, VolumeUnit.CubicHectometer); } @@ -781,7 +763,7 @@ public static Volume FromCubicHectometers(double value) /// /// Creates a from . /// - public static Volume FromCubicInches(double value) + public static Volume FromCubicInches(QuantityValue value) { return new Volume(value, VolumeUnit.CubicInch); } @@ -789,7 +771,7 @@ public static Volume FromCubicInches(double value) /// /// Creates a from . /// - public static Volume FromCubicKilometers(double value) + public static Volume FromCubicKilometers(QuantityValue value) { return new Volume(value, VolumeUnit.CubicKilometer); } @@ -797,7 +779,7 @@ public static Volume FromCubicKilometers(double value) /// /// Creates a from . /// - public static Volume FromCubicMeters(double value) + public static Volume FromCubicMeters(QuantityValue value) { return new Volume(value, VolumeUnit.CubicMeter); } @@ -805,7 +787,7 @@ public static Volume FromCubicMeters(double value) /// /// Creates a from . /// - public static Volume FromCubicMicrometers(double value) + public static Volume FromCubicMicrometers(QuantityValue value) { return new Volume(value, VolumeUnit.CubicMicrometer); } @@ -813,7 +795,7 @@ public static Volume FromCubicMicrometers(double value) /// /// Creates a from . /// - public static Volume FromCubicMiles(double value) + public static Volume FromCubicMiles(QuantityValue value) { return new Volume(value, VolumeUnit.CubicMile); } @@ -821,7 +803,7 @@ public static Volume FromCubicMiles(double value) /// /// Creates a from . /// - public static Volume FromCubicMillimeters(double value) + public static Volume FromCubicMillimeters(QuantityValue value) { return new Volume(value, VolumeUnit.CubicMillimeter); } @@ -829,7 +811,7 @@ public static Volume FromCubicMillimeters(double value) /// /// Creates a from . /// - public static Volume FromCubicYards(double value) + public static Volume FromCubicYards(QuantityValue value) { return new Volume(value, VolumeUnit.CubicYard); } @@ -837,7 +819,7 @@ public static Volume FromCubicYards(double value) /// /// Creates a from . /// - public static Volume FromDecaliters(double value) + public static Volume FromDecaliters(QuantityValue value) { return new Volume(value, VolumeUnit.Decaliter); } @@ -845,7 +827,7 @@ public static Volume FromDecaliters(double value) /// /// Creates a from . /// - public static Volume FromDecausGallons(double value) + public static Volume FromDecausGallons(QuantityValue value) { return new Volume(value, VolumeUnit.DecausGallon); } @@ -853,7 +835,7 @@ public static Volume FromDecausGallons(double value) /// /// Creates a from . /// - public static Volume FromDeciliters(double value) + public static Volume FromDeciliters(QuantityValue value) { return new Volume(value, VolumeUnit.Deciliter); } @@ -861,7 +843,7 @@ public static Volume FromDeciliters(double value) /// /// Creates a from . /// - public static Volume FromDeciusGallons(double value) + public static Volume FromDeciusGallons(QuantityValue value) { return new Volume(value, VolumeUnit.DeciusGallon); } @@ -869,7 +851,7 @@ public static Volume FromDeciusGallons(double value) /// /// Creates a from . /// - public static Volume FromHectocubicFeet(double value) + public static Volume FromHectocubicFeet(QuantityValue value) { return new Volume(value, VolumeUnit.HectocubicFoot); } @@ -877,7 +859,7 @@ public static Volume FromHectocubicFeet(double value) /// /// Creates a from . /// - public static Volume FromHectocubicMeters(double value) + public static Volume FromHectocubicMeters(QuantityValue value) { return new Volume(value, VolumeUnit.HectocubicMeter); } @@ -885,7 +867,7 @@ public static Volume FromHectocubicMeters(double value) /// /// Creates a from . /// - public static Volume FromHectoliters(double value) + public static Volume FromHectoliters(QuantityValue value) { return new Volume(value, VolumeUnit.Hectoliter); } @@ -893,7 +875,7 @@ public static Volume FromHectoliters(double value) /// /// Creates a from . /// - public static Volume FromHectousGallons(double value) + public static Volume FromHectousGallons(QuantityValue value) { return new Volume(value, VolumeUnit.HectousGallon); } @@ -901,7 +883,7 @@ public static Volume FromHectousGallons(double value) /// /// Creates a from . /// - public static Volume FromImperialBeerBarrels(double value) + public static Volume FromImperialBeerBarrels(QuantityValue value) { return new Volume(value, VolumeUnit.ImperialBeerBarrel); } @@ -909,7 +891,7 @@ public static Volume FromImperialBeerBarrels(double value) /// /// Creates a from . /// - public static Volume FromImperialGallons(double value) + public static Volume FromImperialGallons(QuantityValue value) { return new Volume(value, VolumeUnit.ImperialGallon); } @@ -917,7 +899,7 @@ public static Volume FromImperialGallons(double value) /// /// Creates a from . /// - public static Volume FromImperialOunces(double value) + public static Volume FromImperialOunces(QuantityValue value) { return new Volume(value, VolumeUnit.ImperialOunce); } @@ -925,7 +907,7 @@ public static Volume FromImperialOunces(double value) /// /// Creates a from . /// - public static Volume FromImperialPints(double value) + public static Volume FromImperialPints(QuantityValue value) { return new Volume(value, VolumeUnit.ImperialPint); } @@ -933,7 +915,7 @@ public static Volume FromImperialPints(double value) /// /// Creates a from . /// - public static Volume FromImperialQuarts(double value) + public static Volume FromImperialQuarts(QuantityValue value) { return new Volume(value, VolumeUnit.ImperialQuart); } @@ -941,7 +923,7 @@ public static Volume FromImperialQuarts(double value) /// /// Creates a from . /// - public static Volume FromKilocubicFeet(double value) + public static Volume FromKilocubicFeet(QuantityValue value) { return new Volume(value, VolumeUnit.KilocubicFoot); } @@ -949,7 +931,7 @@ public static Volume FromKilocubicFeet(double value) /// /// Creates a from . /// - public static Volume FromKilocubicMeters(double value) + public static Volume FromKilocubicMeters(QuantityValue value) { return new Volume(value, VolumeUnit.KilocubicMeter); } @@ -957,7 +939,7 @@ public static Volume FromKilocubicMeters(double value) /// /// Creates a from . /// - public static Volume FromKiloimperialGallons(double value) + public static Volume FromKiloimperialGallons(QuantityValue value) { return new Volume(value, VolumeUnit.KiloimperialGallon); } @@ -965,7 +947,7 @@ public static Volume FromKiloimperialGallons(double value) /// /// Creates a from . /// - public static Volume FromKiloliters(double value) + public static Volume FromKiloliters(QuantityValue value) { return new Volume(value, VolumeUnit.Kiloliter); } @@ -973,7 +955,7 @@ public static Volume FromKiloliters(double value) /// /// Creates a from . /// - public static Volume FromKilousGallons(double value) + public static Volume FromKilousGallons(QuantityValue value) { return new Volume(value, VolumeUnit.KilousGallon); } @@ -981,7 +963,7 @@ public static Volume FromKilousGallons(double value) /// /// Creates a from . /// - public static Volume FromLiters(double value) + public static Volume FromLiters(QuantityValue value) { return new Volume(value, VolumeUnit.Liter); } @@ -989,7 +971,7 @@ public static Volume FromLiters(double value) /// /// Creates a from . /// - public static Volume FromMegacubicFeet(double value) + public static Volume FromMegacubicFeet(QuantityValue value) { return new Volume(value, VolumeUnit.MegacubicFoot); } @@ -997,7 +979,7 @@ public static Volume FromMegacubicFeet(double value) /// /// Creates a from . /// - public static Volume FromMegaimperialGallons(double value) + public static Volume FromMegaimperialGallons(QuantityValue value) { return new Volume(value, VolumeUnit.MegaimperialGallon); } @@ -1005,7 +987,7 @@ public static Volume FromMegaimperialGallons(double value) /// /// Creates a from . /// - public static Volume FromMegaliters(double value) + public static Volume FromMegaliters(QuantityValue value) { return new Volume(value, VolumeUnit.Megaliter); } @@ -1013,7 +995,7 @@ public static Volume FromMegaliters(double value) /// /// Creates a from . /// - public static Volume FromMegausGallons(double value) + public static Volume FromMegausGallons(QuantityValue value) { return new Volume(value, VolumeUnit.MegausGallon); } @@ -1021,7 +1003,7 @@ public static Volume FromMegausGallons(double value) /// /// Creates a from . /// - public static Volume FromMetricCups(double value) + public static Volume FromMetricCups(QuantityValue value) { return new Volume(value, VolumeUnit.MetricCup); } @@ -1029,7 +1011,7 @@ public static Volume FromMetricCups(double value) /// /// Creates a from . /// - public static Volume FromMetricTeaspoons(double value) + public static Volume FromMetricTeaspoons(QuantityValue value) { return new Volume(value, VolumeUnit.MetricTeaspoon); } @@ -1037,7 +1019,7 @@ public static Volume FromMetricTeaspoons(double value) /// /// Creates a from . /// - public static Volume FromMicroliters(double value) + public static Volume FromMicroliters(QuantityValue value) { return new Volume(value, VolumeUnit.Microliter); } @@ -1045,7 +1027,7 @@ public static Volume FromMicroliters(double value) /// /// Creates a from . /// - public static Volume FromMilliliters(double value) + public static Volume FromMilliliters(QuantityValue value) { return new Volume(value, VolumeUnit.Milliliter); } @@ -1053,7 +1035,7 @@ public static Volume FromMilliliters(double value) /// /// Creates a from . /// - public static Volume FromNanoliters(double value) + public static Volume FromNanoliters(QuantityValue value) { return new Volume(value, VolumeUnit.Nanoliter); } @@ -1061,7 +1043,7 @@ public static Volume FromNanoliters(double value) /// /// Creates a from . /// - public static Volume FromOilBarrels(double value) + public static Volume FromOilBarrels(QuantityValue value) { return new Volume(value, VolumeUnit.OilBarrel); } @@ -1069,7 +1051,7 @@ public static Volume FromOilBarrels(double value) /// /// Creates a from . /// - public static Volume FromUkTablespoons(double value) + public static Volume FromUkTablespoons(QuantityValue value) { return new Volume(value, VolumeUnit.UkTablespoon); } @@ -1077,7 +1059,7 @@ public static Volume FromUkTablespoons(double value) /// /// Creates a from . /// - public static Volume FromUsBeerBarrels(double value) + public static Volume FromUsBeerBarrels(QuantityValue value) { return new Volume(value, VolumeUnit.UsBeerBarrel); } @@ -1085,7 +1067,7 @@ public static Volume FromUsBeerBarrels(double value) /// /// Creates a from . /// - public static Volume FromUsCustomaryCups(double value) + public static Volume FromUsCustomaryCups(QuantityValue value) { return new Volume(value, VolumeUnit.UsCustomaryCup); } @@ -1093,7 +1075,7 @@ public static Volume FromUsCustomaryCups(double value) /// /// Creates a from . /// - public static Volume FromUsGallons(double value) + public static Volume FromUsGallons(QuantityValue value) { return new Volume(value, VolumeUnit.UsGallon); } @@ -1101,7 +1083,7 @@ public static Volume FromUsGallons(double value) /// /// Creates a from . /// - public static Volume FromUsLegalCups(double value) + public static Volume FromUsLegalCups(QuantityValue value) { return new Volume(value, VolumeUnit.UsLegalCup); } @@ -1109,7 +1091,7 @@ public static Volume FromUsLegalCups(double value) /// /// Creates a from . /// - public static Volume FromUsOunces(double value) + public static Volume FromUsOunces(QuantityValue value) { return new Volume(value, VolumeUnit.UsOunce); } @@ -1117,7 +1099,7 @@ public static Volume FromUsOunces(double value) /// /// Creates a from . /// - public static Volume FromUsPints(double value) + public static Volume FromUsPints(QuantityValue value) { return new Volume(value, VolumeUnit.UsPint); } @@ -1125,7 +1107,7 @@ public static Volume FromUsPints(double value) /// /// Creates a from . /// - public static Volume FromUsQuarts(double value) + public static Volume FromUsQuarts(QuantityValue value) { return new Volume(value, VolumeUnit.UsQuart); } @@ -1133,7 +1115,7 @@ public static Volume FromUsQuarts(double value) /// /// Creates a from . /// - public static Volume FromUsTablespoons(double value) + public static Volume FromUsTablespoons(QuantityValue value) { return new Volume(value, VolumeUnit.UsTablespoon); } @@ -1141,7 +1123,7 @@ public static Volume FromUsTablespoons(double value) /// /// Creates a from . /// - public static Volume FromUsTeaspoons(double value) + public static Volume FromUsTeaspoons(QuantityValue value) { return new Volume(value, VolumeUnit.UsTeaspoon); } @@ -1152,7 +1134,7 @@ public static Volume FromUsTeaspoons(double value) /// Value to convert from. /// Unit to convert from. /// Volume unit value. - public static Volume From(double value, VolumeUnit fromUnit) + public static Volume From(QuantityValue value, VolumeUnit fromUnit) { return new Volume(value, fromUnit); } @@ -1213,10 +1195,7 @@ public static Volume Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static Volume Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -1244,11 +1223,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out Volume result) /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out Volume result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -1269,7 +1244,7 @@ public static VolumeUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -1280,7 +1255,7 @@ public static VolumeUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out VolumeUnit unit) { return TryParseUnit(str, null, out unit); @@ -1295,7 +1270,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out VolumeUnit u /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out VolumeUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -1314,35 +1289,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static Volume operator +(Volume left, Volume right) { - return new Volume(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new Volume(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static Volume operator -(Volume left, Volume right) { - return new Volume(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new Volume(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -1436,97 +1411,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(Volume left, Volume right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(Volume left, Volume right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(Volume left, Volume right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(Volume left, Volume right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Volume other, Volume tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(Volume left, Volume right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(Volume other, Volume tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(Volume left, Volume right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Volume other, Volume tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is Volume otherQuantity)) + if (obj is not Volume otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(Volume other, Volume tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(Volume other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current Volume. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(Volume), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is Volume otherQuantity)) throw new ArgumentException("Expected type Volume.", nameof(obj)); + if (obj is not Volume otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1538,252 +1498,24 @@ public int CompareTo(object? obj) /// public int CompareTo(Volume other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumeUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this Volume to another Volume with the unit representation . - /// - /// The unit to convert to. - /// A Volume with the specified unit. - public Volume ToUnit(VolumeUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A Volume with the specified unit. - public Volume ToUnit(VolumeUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(Volume), Unit, typeof(Volume), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (Volume)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(VolumeUnit unit, [NotNullWhen(true)] out Volume? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - Volume? convertedOrNull = (Unit, unit) switch - { - // VolumeUnit -> BaseUnit - (VolumeUnit.AcreFoot, VolumeUnit.CubicMeter) => new Volume(_value * 1233.48183754752, VolumeUnit.CubicMeter), - (VolumeUnit.AuTablespoon, VolumeUnit.CubicMeter) => new Volume(_value * 2e-5, VolumeUnit.CubicMeter), - (VolumeUnit.BoardFoot, VolumeUnit.CubicMeter) => new Volume(_value * (0.028316846592 / 12), VolumeUnit.CubicMeter), - (VolumeUnit.Centiliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e-2d, VolumeUnit.CubicMeter), - (VolumeUnit.CubicCentimeter, VolumeUnit.CubicMeter) => new Volume(_value / 1e6, VolumeUnit.CubicMeter), - (VolumeUnit.CubicDecimeter, VolumeUnit.CubicMeter) => new Volume(_value / 1e3, VolumeUnit.CubicMeter), - (VolumeUnit.CubicFoot, VolumeUnit.CubicMeter) => new Volume(_value * 0.028316846592, VolumeUnit.CubicMeter), - (VolumeUnit.CubicHectometer, VolumeUnit.CubicMeter) => new Volume(_value * 1e6, VolumeUnit.CubicMeter), - (VolumeUnit.CubicInch, VolumeUnit.CubicMeter) => new Volume(_value * 1.6387064e-5, VolumeUnit.CubicMeter), - (VolumeUnit.CubicKilometer, VolumeUnit.CubicMeter) => new Volume(_value * 1e9, VolumeUnit.CubicMeter), - (VolumeUnit.CubicMicrometer, VolumeUnit.CubicMeter) => new Volume(_value / 1e18, VolumeUnit.CubicMeter), - (VolumeUnit.CubicMile, VolumeUnit.CubicMeter) => new Volume(_value * 4.168181825440579584e9, VolumeUnit.CubicMeter), - (VolumeUnit.CubicMillimeter, VolumeUnit.CubicMeter) => new Volume(_value / 1e9, VolumeUnit.CubicMeter), - (VolumeUnit.CubicYard, VolumeUnit.CubicMeter) => new Volume(_value * 0.764554857984, VolumeUnit.CubicMeter), - (VolumeUnit.Decaliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e1d, VolumeUnit.CubicMeter), - (VolumeUnit.DecausGallon, VolumeUnit.CubicMeter) => new Volume((_value * 0.003785411784) * 1e1d, VolumeUnit.CubicMeter), - (VolumeUnit.Deciliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e-1d, VolumeUnit.CubicMeter), - (VolumeUnit.DeciusGallon, VolumeUnit.CubicMeter) => new Volume((_value * 0.003785411784) * 1e-1d, VolumeUnit.CubicMeter), - (VolumeUnit.HectocubicFoot, VolumeUnit.CubicMeter) => new Volume((_value * 0.028316846592) * 1e2d, VolumeUnit.CubicMeter), - (VolumeUnit.HectocubicMeter, VolumeUnit.CubicMeter) => new Volume((_value) * 1e2d, VolumeUnit.CubicMeter), - (VolumeUnit.Hectoliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e2d, VolumeUnit.CubicMeter), - (VolumeUnit.HectousGallon, VolumeUnit.CubicMeter) => new Volume((_value * 0.003785411784) * 1e2d, VolumeUnit.CubicMeter), - (VolumeUnit.ImperialBeerBarrel, VolumeUnit.CubicMeter) => new Volume(_value * 0.16365924, VolumeUnit.CubicMeter), - (VolumeUnit.ImperialGallon, VolumeUnit.CubicMeter) => new Volume(_value * 0.00454609, VolumeUnit.CubicMeter), - (VolumeUnit.ImperialOunce, VolumeUnit.CubicMeter) => new Volume(_value * 2.84130625e-5, VolumeUnit.CubicMeter), - (VolumeUnit.ImperialPint, VolumeUnit.CubicMeter) => new Volume(_value * 5.6826125e-4, VolumeUnit.CubicMeter), - (VolumeUnit.ImperialQuart, VolumeUnit.CubicMeter) => new Volume(_value * 1.1365225e-3, VolumeUnit.CubicMeter), - (VolumeUnit.KilocubicFoot, VolumeUnit.CubicMeter) => new Volume((_value * 0.028316846592) * 1e3d, VolumeUnit.CubicMeter), - (VolumeUnit.KilocubicMeter, VolumeUnit.CubicMeter) => new Volume((_value) * 1e3d, VolumeUnit.CubicMeter), - (VolumeUnit.KiloimperialGallon, VolumeUnit.CubicMeter) => new Volume((_value * 0.00454609) * 1e3d, VolumeUnit.CubicMeter), - (VolumeUnit.Kiloliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e3d, VolumeUnit.CubicMeter), - (VolumeUnit.KilousGallon, VolumeUnit.CubicMeter) => new Volume((_value * 0.003785411784) * 1e3d, VolumeUnit.CubicMeter), - (VolumeUnit.Liter, VolumeUnit.CubicMeter) => new Volume(_value / 1e3, VolumeUnit.CubicMeter), - (VolumeUnit.MegacubicFoot, VolumeUnit.CubicMeter) => new Volume((_value * 0.028316846592) * 1e6d, VolumeUnit.CubicMeter), - (VolumeUnit.MegaimperialGallon, VolumeUnit.CubicMeter) => new Volume((_value * 0.00454609) * 1e6d, VolumeUnit.CubicMeter), - (VolumeUnit.Megaliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e6d, VolumeUnit.CubicMeter), - (VolumeUnit.MegausGallon, VolumeUnit.CubicMeter) => new Volume((_value * 0.003785411784) * 1e6d, VolumeUnit.CubicMeter), - (VolumeUnit.MetricCup, VolumeUnit.CubicMeter) => new Volume(_value * 0.00025, VolumeUnit.CubicMeter), - (VolumeUnit.MetricTeaspoon, VolumeUnit.CubicMeter) => new Volume(_value * 0.5e-5, VolumeUnit.CubicMeter), - (VolumeUnit.Microliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e-6d, VolumeUnit.CubicMeter), - (VolumeUnit.Milliliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e-3d, VolumeUnit.CubicMeter), - (VolumeUnit.Nanoliter, VolumeUnit.CubicMeter) => new Volume((_value / 1e3) * 1e-9d, VolumeUnit.CubicMeter), - (VolumeUnit.OilBarrel, VolumeUnit.CubicMeter) => new Volume(_value * 0.158987294928, VolumeUnit.CubicMeter), - (VolumeUnit.UkTablespoon, VolumeUnit.CubicMeter) => new Volume(_value * 1.5e-5, VolumeUnit.CubicMeter), - (VolumeUnit.UsBeerBarrel, VolumeUnit.CubicMeter) => new Volume(_value * 0.117347765304, VolumeUnit.CubicMeter), - (VolumeUnit.UsCustomaryCup, VolumeUnit.CubicMeter) => new Volume(_value * 0.0002365882365, VolumeUnit.CubicMeter), - (VolumeUnit.UsGallon, VolumeUnit.CubicMeter) => new Volume(_value * 0.003785411784, VolumeUnit.CubicMeter), - (VolumeUnit.UsLegalCup, VolumeUnit.CubicMeter) => new Volume(_value * 0.00024, VolumeUnit.CubicMeter), - (VolumeUnit.UsOunce, VolumeUnit.CubicMeter) => new Volume(_value * 2.95735295625e-5, VolumeUnit.CubicMeter), - (VolumeUnit.UsPint, VolumeUnit.CubicMeter) => new Volume(_value * 4.73176473e-4, VolumeUnit.CubicMeter), - (VolumeUnit.UsQuart, VolumeUnit.CubicMeter) => new Volume(_value * 9.46352946e-4, VolumeUnit.CubicMeter), - (VolumeUnit.UsTablespoon, VolumeUnit.CubicMeter) => new Volume(_value * 1.478676478125e-5, VolumeUnit.CubicMeter), - (VolumeUnit.UsTeaspoon, VolumeUnit.CubicMeter) => new Volume(_value * 4.92892159375e-6, VolumeUnit.CubicMeter), - - // BaseUnit -> VolumeUnit - (VolumeUnit.CubicMeter, VolumeUnit.AcreFoot) => new Volume(_value / 1233.48183754752, VolumeUnit.AcreFoot), - (VolumeUnit.CubicMeter, VolumeUnit.AuTablespoon) => new Volume(_value / 2e-5, VolumeUnit.AuTablespoon), - (VolumeUnit.CubicMeter, VolumeUnit.BoardFoot) => new Volume(_value / (0.028316846592 / 12), VolumeUnit.BoardFoot), - (VolumeUnit.CubicMeter, VolumeUnit.Centiliter) => new Volume((_value * 1e3) / 1e-2d, VolumeUnit.Centiliter), - (VolumeUnit.CubicMeter, VolumeUnit.CubicCentimeter) => new Volume(_value * 1e6, VolumeUnit.CubicCentimeter), - (VolumeUnit.CubicMeter, VolumeUnit.CubicDecimeter) => new Volume(_value * 1e3, VolumeUnit.CubicDecimeter), - (VolumeUnit.CubicMeter, VolumeUnit.CubicFoot) => new Volume(_value / 0.028316846592, VolumeUnit.CubicFoot), - (VolumeUnit.CubicMeter, VolumeUnit.CubicHectometer) => new Volume(_value / 1e6, VolumeUnit.CubicHectometer), - (VolumeUnit.CubicMeter, VolumeUnit.CubicInch) => new Volume(_value / 1.6387064e-5, VolumeUnit.CubicInch), - (VolumeUnit.CubicMeter, VolumeUnit.CubicKilometer) => new Volume(_value / 1e9, VolumeUnit.CubicKilometer), - (VolumeUnit.CubicMeter, VolumeUnit.CubicMicrometer) => new Volume(_value * 1e18, VolumeUnit.CubicMicrometer), - (VolumeUnit.CubicMeter, VolumeUnit.CubicMile) => new Volume(_value / 4.168181825440579584e9, VolumeUnit.CubicMile), - (VolumeUnit.CubicMeter, VolumeUnit.CubicMillimeter) => new Volume(_value * 1e9, VolumeUnit.CubicMillimeter), - (VolumeUnit.CubicMeter, VolumeUnit.CubicYard) => new Volume(_value / 0.764554857984, VolumeUnit.CubicYard), - (VolumeUnit.CubicMeter, VolumeUnit.Decaliter) => new Volume((_value * 1e3) / 1e1d, VolumeUnit.Decaliter), - (VolumeUnit.CubicMeter, VolumeUnit.DecausGallon) => new Volume((_value / 0.003785411784) / 1e1d, VolumeUnit.DecausGallon), - (VolumeUnit.CubicMeter, VolumeUnit.Deciliter) => new Volume((_value * 1e3) / 1e-1d, VolumeUnit.Deciliter), - (VolumeUnit.CubicMeter, VolumeUnit.DeciusGallon) => new Volume((_value / 0.003785411784) / 1e-1d, VolumeUnit.DeciusGallon), - (VolumeUnit.CubicMeter, VolumeUnit.HectocubicFoot) => new Volume((_value / 0.028316846592) / 1e2d, VolumeUnit.HectocubicFoot), - (VolumeUnit.CubicMeter, VolumeUnit.HectocubicMeter) => new Volume((_value) / 1e2d, VolumeUnit.HectocubicMeter), - (VolumeUnit.CubicMeter, VolumeUnit.Hectoliter) => new Volume((_value * 1e3) / 1e2d, VolumeUnit.Hectoliter), - (VolumeUnit.CubicMeter, VolumeUnit.HectousGallon) => new Volume((_value / 0.003785411784) / 1e2d, VolumeUnit.HectousGallon), - (VolumeUnit.CubicMeter, VolumeUnit.ImperialBeerBarrel) => new Volume(_value / 0.16365924, VolumeUnit.ImperialBeerBarrel), - (VolumeUnit.CubicMeter, VolumeUnit.ImperialGallon) => new Volume(_value / 0.00454609, VolumeUnit.ImperialGallon), - (VolumeUnit.CubicMeter, VolumeUnit.ImperialOunce) => new Volume(_value / 2.84130625e-5, VolumeUnit.ImperialOunce), - (VolumeUnit.CubicMeter, VolumeUnit.ImperialPint) => new Volume(_value / 5.6826125e-4, VolumeUnit.ImperialPint), - (VolumeUnit.CubicMeter, VolumeUnit.ImperialQuart) => new Volume(_value / 1.1365225e-3, VolumeUnit.ImperialQuart), - (VolumeUnit.CubicMeter, VolumeUnit.KilocubicFoot) => new Volume((_value / 0.028316846592) / 1e3d, VolumeUnit.KilocubicFoot), - (VolumeUnit.CubicMeter, VolumeUnit.KilocubicMeter) => new Volume((_value) / 1e3d, VolumeUnit.KilocubicMeter), - (VolumeUnit.CubicMeter, VolumeUnit.KiloimperialGallon) => new Volume((_value / 0.00454609) / 1e3d, VolumeUnit.KiloimperialGallon), - (VolumeUnit.CubicMeter, VolumeUnit.Kiloliter) => new Volume((_value * 1e3) / 1e3d, VolumeUnit.Kiloliter), - (VolumeUnit.CubicMeter, VolumeUnit.KilousGallon) => new Volume((_value / 0.003785411784) / 1e3d, VolumeUnit.KilousGallon), - (VolumeUnit.CubicMeter, VolumeUnit.Liter) => new Volume(_value * 1e3, VolumeUnit.Liter), - (VolumeUnit.CubicMeter, VolumeUnit.MegacubicFoot) => new Volume((_value / 0.028316846592) / 1e6d, VolumeUnit.MegacubicFoot), - (VolumeUnit.CubicMeter, VolumeUnit.MegaimperialGallon) => new Volume((_value / 0.00454609) / 1e6d, VolumeUnit.MegaimperialGallon), - (VolumeUnit.CubicMeter, VolumeUnit.Megaliter) => new Volume((_value * 1e3) / 1e6d, VolumeUnit.Megaliter), - (VolumeUnit.CubicMeter, VolumeUnit.MegausGallon) => new Volume((_value / 0.003785411784) / 1e6d, VolumeUnit.MegausGallon), - (VolumeUnit.CubicMeter, VolumeUnit.MetricCup) => new Volume(_value / 0.00025, VolumeUnit.MetricCup), - (VolumeUnit.CubicMeter, VolumeUnit.MetricTeaspoon) => new Volume(_value / 0.5e-5, VolumeUnit.MetricTeaspoon), - (VolumeUnit.CubicMeter, VolumeUnit.Microliter) => new Volume((_value * 1e3) / 1e-6d, VolumeUnit.Microliter), - (VolumeUnit.CubicMeter, VolumeUnit.Milliliter) => new Volume((_value * 1e3) / 1e-3d, VolumeUnit.Milliliter), - (VolumeUnit.CubicMeter, VolumeUnit.Nanoliter) => new Volume((_value * 1e3) / 1e-9d, VolumeUnit.Nanoliter), - (VolumeUnit.CubicMeter, VolumeUnit.OilBarrel) => new Volume(_value / 0.158987294928, VolumeUnit.OilBarrel), - (VolumeUnit.CubicMeter, VolumeUnit.UkTablespoon) => new Volume(_value / 1.5e-5, VolumeUnit.UkTablespoon), - (VolumeUnit.CubicMeter, VolumeUnit.UsBeerBarrel) => new Volume(_value / 0.117347765304, VolumeUnit.UsBeerBarrel), - (VolumeUnit.CubicMeter, VolumeUnit.UsCustomaryCup) => new Volume(_value / 0.0002365882365, VolumeUnit.UsCustomaryCup), - (VolumeUnit.CubicMeter, VolumeUnit.UsGallon) => new Volume(_value / 0.003785411784, VolumeUnit.UsGallon), - (VolumeUnit.CubicMeter, VolumeUnit.UsLegalCup) => new Volume(_value / 0.00024, VolumeUnit.UsLegalCup), - (VolumeUnit.CubicMeter, VolumeUnit.UsOunce) => new Volume(_value / 2.95735295625e-5, VolumeUnit.UsOunce), - (VolumeUnit.CubicMeter, VolumeUnit.UsPint) => new Volume(_value / 4.73176473e-4, VolumeUnit.UsPint), - (VolumeUnit.CubicMeter, VolumeUnit.UsQuart) => new Volume(_value / 9.46352946e-4, VolumeUnit.UsQuart), - (VolumeUnit.CubicMeter, VolumeUnit.UsTablespoon) => new Volume(_value / 1.478676478125e-5, VolumeUnit.UsTablespoon), - (VolumeUnit.CubicMeter, VolumeUnit.UsTeaspoon) => new Volume(_value / 4.92892159375e-6, VolumeUnit.UsTeaspoon), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public Volume ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not VolumeUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(VolumeUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(VolumeUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1798,7 +1530,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs index a59b8f8639..f4922f24bd 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeConcentration.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Concentration#Volume_concentration /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct VolumeConcentration : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -57,13 +56,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly VolumeConcentrationUnit? _unit; /// @@ -123,34 +122,70 @@ public static VolumeConcentrationInfo CreateDefault(FuncAn of representing the default unit mappings for VolumeConcentration. public static IEnumerable> GetDefaultMappings() { - yield return new (VolumeConcentrationUnit.CentiliterPerLiter, "CentiliterPerLiter", "CentilitersPerLiter", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.CentiliterPerMilliliter, "CentiliterPerMilliliter", "CentilitersPerMilliliter", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.DeciliterPerLiter, "DeciliterPerLiter", "DecilitersPerLiter", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.DeciliterPerMilliliter, "DeciliterPerMilliliter", "DecilitersPerMilliliter", BaseUnits.Undefined); + yield return new (VolumeConcentrationUnit.CentiliterPerLiter, "CentiliterPerLiter", "CentilitersPerLiter", BaseUnits.Undefined, + 100 + ); + yield return new (VolumeConcentrationUnit.CentiliterPerMilliliter, "CentiliterPerMilliliter", "CentilitersPerMilliliter", BaseUnits.Undefined, + new QuantityValue(1, 10) + ); + yield return new (VolumeConcentrationUnit.DeciliterPerLiter, "DeciliterPerLiter", "DecilitersPerLiter", BaseUnits.Undefined, + 10 + ); + yield return new (VolumeConcentrationUnit.DeciliterPerMilliliter, "DeciliterPerMilliliter", "DecilitersPerMilliliter", BaseUnits.Undefined, + new QuantityValue(1, 100) + ); yield return new (VolumeConcentrationUnit.DecimalFraction, "DecimalFraction", "DecimalFractions", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.LiterPerLiter, "LiterPerLiter", "LitersPerLiter", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.LiterPerMilliliter, "LiterPerMilliliter", "LitersPerMilliliter", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.MicroliterPerLiter, "MicroliterPerLiter", "MicrolitersPerLiter", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.MicroliterPerMilliliter, "MicroliterPerMilliliter", "MicrolitersPerMilliliter", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.MilliliterPerLiter, "MilliliterPerLiter", "MillilitersPerLiter", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.MilliliterPerMilliliter, "MilliliterPerMilliliter", "MillilitersPerMilliliter", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.NanoliterPerLiter, "NanoliterPerLiter", "NanolitersPerLiter", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.NanoliterPerMilliliter, "NanoliterPerMilliliter", "NanolitersPerMilliliter", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.PartPerBillion, "PartPerBillion", "PartsPerBillion", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.PartPerMillion, "PartPerMillion", "PartsPerMillion", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.PartPerThousand, "PartPerThousand", "PartsPerThousand", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.PartPerTrillion, "PartPerTrillion", "PartsPerTrillion", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.Percent, "Percent", "Percent", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.PicoliterPerLiter, "PicoliterPerLiter", "PicolitersPerLiter", BaseUnits.Undefined); - yield return new (VolumeConcentrationUnit.PicoliterPerMilliliter, "PicoliterPerMilliliter", "PicolitersPerMilliliter", BaseUnits.Undefined); + yield return new (VolumeConcentrationUnit.LiterPerLiter, "LiterPerLiter", "LitersPerLiter", BaseUnits.Undefined, + 1 + ); + yield return new (VolumeConcentrationUnit.LiterPerMilliliter, "LiterPerMilliliter", "LitersPerMilliliter", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (VolumeConcentrationUnit.MicroliterPerLiter, "MicroliterPerLiter", "MicrolitersPerLiter", BaseUnits.Undefined, + 1000000 + ); + yield return new (VolumeConcentrationUnit.MicroliterPerMilliliter, "MicroliterPerMilliliter", "MicrolitersPerMilliliter", BaseUnits.Undefined, + 1000 + ); + yield return new (VolumeConcentrationUnit.MilliliterPerLiter, "MilliliterPerLiter", "MillilitersPerLiter", BaseUnits.Undefined, + 1000 + ); + yield return new (VolumeConcentrationUnit.MilliliterPerMilliliter, "MilliliterPerMilliliter", "MillilitersPerMilliliter", BaseUnits.Undefined, + 1 + ); + yield return new (VolumeConcentrationUnit.NanoliterPerLiter, "NanoliterPerLiter", "NanolitersPerLiter", BaseUnits.Undefined, + 1000000000 + ); + yield return new (VolumeConcentrationUnit.NanoliterPerMilliliter, "NanoliterPerMilliliter", "NanolitersPerMilliliter", BaseUnits.Undefined, + 1000000 + ); + yield return new (VolumeConcentrationUnit.PartPerBillion, "PartPerBillion", "PartsPerBillion", BaseUnits.Undefined, + 1000000000 + ); + yield return new (VolumeConcentrationUnit.PartPerMillion, "PartPerMillion", "PartsPerMillion", BaseUnits.Undefined, + 1000000 + ); + yield return new (VolumeConcentrationUnit.PartPerThousand, "PartPerThousand", "PartsPerThousand", BaseUnits.Undefined, + 1000 + ); + yield return new (VolumeConcentrationUnit.PartPerTrillion, "PartPerTrillion", "PartsPerTrillion", BaseUnits.Undefined, + 1000000000000 + ); + yield return new (VolumeConcentrationUnit.Percent, "Percent", "Percent", BaseUnits.Undefined, + 100 + ); + yield return new (VolumeConcentrationUnit.PicoliterPerLiter, "PicoliterPerLiter", "PicolitersPerLiter", BaseUnits.Undefined, + 1000000000000 + ); + yield return new (VolumeConcentrationUnit.PicoliterPerMilliliter, "PicoliterPerMilliliter", "PicolitersPerMilliliter", BaseUnits.Undefined, + 1000000000 + ); } } static VolumeConcentration() { - Info = VolumeConcentrationInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(VolumeConcentrationInfo.CreateDefault); } /// @@ -158,7 +193,7 @@ static VolumeConcentration() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public VolumeConcentration(double value, VolumeConcentrationUnit unit) + public VolumeConcentration(QuantityValue value, VolumeConcentrationUnit unit) { _value = value; _unit = unit; @@ -169,7 +204,8 @@ public VolumeConcentration(double value, VolumeConcentrationUnit unit) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -198,10 +234,8 @@ public VolumeConcentration(double value, VolumeConcentrationUnit unit) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public VolumeConcentrationUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -240,161 +274,109 @@ public VolumeConcentration(double value, VolumeConcentrationUnit unit) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentilitersPerLiter => As(VolumeConcentrationUnit.CentiliterPerLiter); + public QuantityValue CentilitersPerLiter => this.As(VolumeConcentrationUnit.CentiliterPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentilitersPerMilliliter => As(VolumeConcentrationUnit.CentiliterPerMilliliter); + public QuantityValue CentilitersPerMilliliter => this.As(VolumeConcentrationUnit.CentiliterPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecilitersPerLiter => As(VolumeConcentrationUnit.DeciliterPerLiter); + public QuantityValue DecilitersPerLiter => this.As(VolumeConcentrationUnit.DeciliterPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecilitersPerMilliliter => As(VolumeConcentrationUnit.DeciliterPerMilliliter); + public QuantityValue DecilitersPerMilliliter => this.As(VolumeConcentrationUnit.DeciliterPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecimalFractions => As(VolumeConcentrationUnit.DecimalFraction); + public QuantityValue DecimalFractions => this.As(VolumeConcentrationUnit.DecimalFraction); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double LitersPerLiter => As(VolumeConcentrationUnit.LiterPerLiter); + public QuantityValue LitersPerLiter => this.As(VolumeConcentrationUnit.LiterPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double LitersPerMilliliter => As(VolumeConcentrationUnit.LiterPerMilliliter); + public QuantityValue LitersPerMilliliter => this.As(VolumeConcentrationUnit.LiterPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrolitersPerLiter => As(VolumeConcentrationUnit.MicroliterPerLiter); + public QuantityValue MicrolitersPerLiter => this.As(VolumeConcentrationUnit.MicroliterPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrolitersPerMilliliter => As(VolumeConcentrationUnit.MicroliterPerMilliliter); + public QuantityValue MicrolitersPerMilliliter => this.As(VolumeConcentrationUnit.MicroliterPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillilitersPerLiter => As(VolumeConcentrationUnit.MilliliterPerLiter); + public QuantityValue MillilitersPerLiter => this.As(VolumeConcentrationUnit.MilliliterPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillilitersPerMilliliter => As(VolumeConcentrationUnit.MilliliterPerMilliliter); + public QuantityValue MillilitersPerMilliliter => this.As(VolumeConcentrationUnit.MilliliterPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanolitersPerLiter => As(VolumeConcentrationUnit.NanoliterPerLiter); + public QuantityValue NanolitersPerLiter => this.As(VolumeConcentrationUnit.NanoliterPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanolitersPerMilliliter => As(VolumeConcentrationUnit.NanoliterPerMilliliter); + public QuantityValue NanolitersPerMilliliter => this.As(VolumeConcentrationUnit.NanoliterPerMilliliter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PartsPerBillion => As(VolumeConcentrationUnit.PartPerBillion); + public QuantityValue PartsPerBillion => this.As(VolumeConcentrationUnit.PartPerBillion); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PartsPerMillion => As(VolumeConcentrationUnit.PartPerMillion); + public QuantityValue PartsPerMillion => this.As(VolumeConcentrationUnit.PartPerMillion); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PartsPerThousand => As(VolumeConcentrationUnit.PartPerThousand); + public QuantityValue PartsPerThousand => this.As(VolumeConcentrationUnit.PartPerThousand); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PartsPerTrillion => As(VolumeConcentrationUnit.PartPerTrillion); + public QuantityValue PartsPerTrillion => this.As(VolumeConcentrationUnit.PartPerTrillion); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double Percent => As(VolumeConcentrationUnit.Percent); + public QuantityValue Percent => this.As(VolumeConcentrationUnit.Percent); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicolitersPerLiter => As(VolumeConcentrationUnit.PicoliterPerLiter); + public QuantityValue PicolitersPerLiter => this.As(VolumeConcentrationUnit.PicoliterPerLiter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double PicolitersPerMilliliter => As(VolumeConcentrationUnit.PicoliterPerMilliliter); + public QuantityValue PicolitersPerMilliliter => this.As(VolumeConcentrationUnit.PicoliterPerMilliliter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: VolumeConcentrationUnit -> BaseUnit - unitConverter.SetConversionFunction(VolumeConcentrationUnit.CentiliterPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.CentiliterPerMilliliter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DeciliterPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DeciliterPerMilliliter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.LiterPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.LiterPerMilliliter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.MicroliterPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.MicroliterPerMilliliter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.MilliliterPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.MilliliterPerMilliliter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.NanoliterPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.NanoliterPerMilliliter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.PartPerBillion, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.PartPerMillion, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.PartPerThousand, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.PartPerTrillion, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.Percent, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.PicoliterPerLiter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.PicoliterPerMilliliter, VolumeConcentrationUnit.DecimalFraction, quantity => quantity.ToUnit(VolumeConcentrationUnit.DecimalFraction)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.DecimalFraction, quantity => quantity); - - // Register in unit converter: BaseUnit -> VolumeConcentrationUnit - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.CentiliterPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.CentiliterPerLiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.CentiliterPerMilliliter, quantity => quantity.ToUnit(VolumeConcentrationUnit.CentiliterPerMilliliter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.DeciliterPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.DeciliterPerLiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.DeciliterPerMilliliter, quantity => quantity.ToUnit(VolumeConcentrationUnit.DeciliterPerMilliliter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.LiterPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.LiterPerLiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.LiterPerMilliliter, quantity => quantity.ToUnit(VolumeConcentrationUnit.LiterPerMilliliter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MicroliterPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.MicroliterPerLiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MicroliterPerMilliliter, quantity => quantity.ToUnit(VolumeConcentrationUnit.MicroliterPerMilliliter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MilliliterPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.MilliliterPerLiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MilliliterPerMilliliter, quantity => quantity.ToUnit(VolumeConcentrationUnit.MilliliterPerMilliliter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.NanoliterPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.NanoliterPerLiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.NanoliterPerMilliliter, quantity => quantity.ToUnit(VolumeConcentrationUnit.NanoliterPerMilliliter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerBillion, quantity => quantity.ToUnit(VolumeConcentrationUnit.PartPerBillion)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerMillion, quantity => quantity.ToUnit(VolumeConcentrationUnit.PartPerMillion)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerThousand, quantity => quantity.ToUnit(VolumeConcentrationUnit.PartPerThousand)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerTrillion, quantity => quantity.ToUnit(VolumeConcentrationUnit.PartPerTrillion)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.Percent, quantity => quantity.ToUnit(VolumeConcentrationUnit.Percent)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PicoliterPerLiter, quantity => quantity.ToUnit(VolumeConcentrationUnit.PicoliterPerLiter)); - unitConverter.SetConversionFunction(VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PicoliterPerMilliliter, quantity => quantity.ToUnit(VolumeConcentrationUnit.PicoliterPerMilliliter)); - } - /// /// Get unit abbreviation string. /// @@ -423,7 +405,7 @@ public static string GetAbbreviation(VolumeConcentrationUnit unit, IFormatProvid /// /// Creates a from . /// - public static VolumeConcentration FromCentilitersPerLiter(double value) + public static VolumeConcentration FromCentilitersPerLiter(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.CentiliterPerLiter); } @@ -431,7 +413,7 @@ public static VolumeConcentration FromCentilitersPerLiter(double value) /// /// Creates a from . /// - public static VolumeConcentration FromCentilitersPerMilliliter(double value) + public static VolumeConcentration FromCentilitersPerMilliliter(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.CentiliterPerMilliliter); } @@ -439,7 +421,7 @@ public static VolumeConcentration FromCentilitersPerMilliliter(double value) /// /// Creates a from . /// - public static VolumeConcentration FromDecilitersPerLiter(double value) + public static VolumeConcentration FromDecilitersPerLiter(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.DeciliterPerLiter); } @@ -447,7 +429,7 @@ public static VolumeConcentration FromDecilitersPerLiter(double value) /// /// Creates a from . /// - public static VolumeConcentration FromDecilitersPerMilliliter(double value) + public static VolumeConcentration FromDecilitersPerMilliliter(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.DeciliterPerMilliliter); } @@ -455,7 +437,7 @@ public static VolumeConcentration FromDecilitersPerMilliliter(double value) /// /// Creates a from . /// - public static VolumeConcentration FromDecimalFractions(double value) + public static VolumeConcentration FromDecimalFractions(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.DecimalFraction); } @@ -463,7 +445,7 @@ public static VolumeConcentration FromDecimalFractions(double value) /// /// Creates a from . /// - public static VolumeConcentration FromLitersPerLiter(double value) + public static VolumeConcentration FromLitersPerLiter(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.LiterPerLiter); } @@ -471,7 +453,7 @@ public static VolumeConcentration FromLitersPerLiter(double value) /// /// Creates a from . /// - public static VolumeConcentration FromLitersPerMilliliter(double value) + public static VolumeConcentration FromLitersPerMilliliter(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.LiterPerMilliliter); } @@ -479,7 +461,7 @@ public static VolumeConcentration FromLitersPerMilliliter(double value) /// /// Creates a from . /// - public static VolumeConcentration FromMicrolitersPerLiter(double value) + public static VolumeConcentration FromMicrolitersPerLiter(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.MicroliterPerLiter); } @@ -487,7 +469,7 @@ public static VolumeConcentration FromMicrolitersPerLiter(double value) /// /// Creates a from . /// - public static VolumeConcentration FromMicrolitersPerMilliliter(double value) + public static VolumeConcentration FromMicrolitersPerMilliliter(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.MicroliterPerMilliliter); } @@ -495,7 +477,7 @@ public static VolumeConcentration FromMicrolitersPerMilliliter(double value) /// /// Creates a from . /// - public static VolumeConcentration FromMillilitersPerLiter(double value) + public static VolumeConcentration FromMillilitersPerLiter(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.MilliliterPerLiter); } @@ -503,7 +485,7 @@ public static VolumeConcentration FromMillilitersPerLiter(double value) /// /// Creates a from . /// - public static VolumeConcentration FromMillilitersPerMilliliter(double value) + public static VolumeConcentration FromMillilitersPerMilliliter(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.MilliliterPerMilliliter); } @@ -511,7 +493,7 @@ public static VolumeConcentration FromMillilitersPerMilliliter(double value) /// /// Creates a from . /// - public static VolumeConcentration FromNanolitersPerLiter(double value) + public static VolumeConcentration FromNanolitersPerLiter(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.NanoliterPerLiter); } @@ -519,7 +501,7 @@ public static VolumeConcentration FromNanolitersPerLiter(double value) /// /// Creates a from . /// - public static VolumeConcentration FromNanolitersPerMilliliter(double value) + public static VolumeConcentration FromNanolitersPerMilliliter(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.NanoliterPerMilliliter); } @@ -527,7 +509,7 @@ public static VolumeConcentration FromNanolitersPerMilliliter(double value) /// /// Creates a from . /// - public static VolumeConcentration FromPartsPerBillion(double value) + public static VolumeConcentration FromPartsPerBillion(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.PartPerBillion); } @@ -535,7 +517,7 @@ public static VolumeConcentration FromPartsPerBillion(double value) /// /// Creates a from . /// - public static VolumeConcentration FromPartsPerMillion(double value) + public static VolumeConcentration FromPartsPerMillion(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.PartPerMillion); } @@ -543,7 +525,7 @@ public static VolumeConcentration FromPartsPerMillion(double value) /// /// Creates a from . /// - public static VolumeConcentration FromPartsPerThousand(double value) + public static VolumeConcentration FromPartsPerThousand(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.PartPerThousand); } @@ -551,7 +533,7 @@ public static VolumeConcentration FromPartsPerThousand(double value) /// /// Creates a from . /// - public static VolumeConcentration FromPartsPerTrillion(double value) + public static VolumeConcentration FromPartsPerTrillion(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.PartPerTrillion); } @@ -559,7 +541,7 @@ public static VolumeConcentration FromPartsPerTrillion(double value) /// /// Creates a from . /// - public static VolumeConcentration FromPercent(double value) + public static VolumeConcentration FromPercent(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.Percent); } @@ -567,7 +549,7 @@ public static VolumeConcentration FromPercent(double value) /// /// Creates a from . /// - public static VolumeConcentration FromPicolitersPerLiter(double value) + public static VolumeConcentration FromPicolitersPerLiter(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.PicoliterPerLiter); } @@ -575,7 +557,7 @@ public static VolumeConcentration FromPicolitersPerLiter(double value) /// /// Creates a from . /// - public static VolumeConcentration FromPicolitersPerMilliliter(double value) + public static VolumeConcentration FromPicolitersPerMilliliter(QuantityValue value) { return new VolumeConcentration(value, VolumeConcentrationUnit.PicoliterPerMilliliter); } @@ -586,7 +568,7 @@ public static VolumeConcentration FromPicolitersPerMilliliter(double value) /// Value to convert from. /// Unit to convert from. /// VolumeConcentration unit value. - public static VolumeConcentration From(double value, VolumeConcentrationUnit fromUnit) + public static VolumeConcentration From(QuantityValue value, VolumeConcentrationUnit fromUnit) { return new VolumeConcentration(value, fromUnit); } @@ -647,10 +629,7 @@ public static VolumeConcentration Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static VolumeConcentration Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -678,11 +657,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out VolumeConcentrat /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out VolumeConcentration result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -703,7 +678,7 @@ public static VolumeConcentrationUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -714,7 +689,7 @@ public static VolumeConcentrationUnit ParseUnit(string str, IFormatProvider? pro return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out VolumeConcentrationUnit unit) { return TryParseUnit(str, null, out unit); @@ -729,7 +704,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out VolumeConcen /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out VolumeConcentrationUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -748,35 +723,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static VolumeConcentration operator +(VolumeConcentration left, VolumeConcentration right) { - return new VolumeConcentration(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new VolumeConcentration(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static VolumeConcentration operator -(VolumeConcentration left, VolumeConcentration right) { - return new VolumeConcentration(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new VolumeConcentration(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -804,97 +779,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(VolumeConcentration left, VolumeConcentration right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(VolumeConcentration left, VolumeConcentration right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(VolumeConcentration left, VolumeConcentration right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(VolumeConcentration left, VolumeConcentration right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(VolumeConcentration other, VolumeConcentration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(VolumeConcentration left, VolumeConcentration right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(VolumeConcentration other, VolumeConcentration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(VolumeConcentration left, VolumeConcentration right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(VolumeConcentration other, VolumeConcentration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is VolumeConcentration otherQuantity)) + if (obj is not VolumeConcentration otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(VolumeConcentration other, VolumeConcentration tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(VolumeConcentration other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current VolumeConcentration. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(VolumeConcentration), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is VolumeConcentration otherQuantity)) throw new ArgumentException("Expected type VolumeConcentration.", nameof(obj)); + if (obj is not VolumeConcentration otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -906,184 +866,24 @@ public int CompareTo(object? obj) /// public int CompareTo(VolumeConcentration other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumeConcentrationUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this VolumeConcentration to another VolumeConcentration with the unit representation . - /// - /// The unit to convert to. - /// A VolumeConcentration with the specified unit. - public VolumeConcentration ToUnit(VolumeConcentrationUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A VolumeConcentration with the specified unit. - public VolumeConcentration ToUnit(VolumeConcentrationUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(VolumeConcentration), Unit, typeof(VolumeConcentration), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (VolumeConcentration)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(VolumeConcentrationUnit unit, [NotNullWhen(true)] out VolumeConcentration? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - VolumeConcentration? convertedOrNull = (Unit, unit) switch - { - // VolumeConcentrationUnit -> BaseUnit - (VolumeConcentrationUnit.CentiliterPerLiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value) * 1e-2d, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.CentiliterPerMilliliter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value / 1e-3) * 1e-2d, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.DeciliterPerLiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value) * 1e-1d, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.DeciliterPerMilliliter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value / 1e-3) * 1e-1d, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.LiterPerLiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration(_value, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.LiterPerMilliliter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration(_value / 1e-3, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.MicroliterPerLiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value) * 1e-6d, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.MicroliterPerMilliliter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value / 1e-3) * 1e-6d, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.MilliliterPerLiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value) * 1e-3d, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.MilliliterPerMilliliter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value / 1e-3) * 1e-3d, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.NanoliterPerLiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value) * 1e-9d, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.NanoliterPerMilliliter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value / 1e-3) * 1e-9d, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.PartPerBillion, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration(_value / 1e9, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.PartPerMillion, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration(_value / 1e6, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.PartPerThousand, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration(_value / 1e3, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.PartPerTrillion, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration(_value / 1e12, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.Percent, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration(_value / 1e2, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.PicoliterPerLiter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value) * 1e-12d, VolumeConcentrationUnit.DecimalFraction), - (VolumeConcentrationUnit.PicoliterPerMilliliter, VolumeConcentrationUnit.DecimalFraction) => new VolumeConcentration((_value / 1e-3) * 1e-12d, VolumeConcentrationUnit.DecimalFraction), - - // BaseUnit -> VolumeConcentrationUnit - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.CentiliterPerLiter) => new VolumeConcentration((_value) / 1e-2d, VolumeConcentrationUnit.CentiliterPerLiter), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.CentiliterPerMilliliter) => new VolumeConcentration((_value * 1e-3) / 1e-2d, VolumeConcentrationUnit.CentiliterPerMilliliter), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.DeciliterPerLiter) => new VolumeConcentration((_value) / 1e-1d, VolumeConcentrationUnit.DeciliterPerLiter), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.DeciliterPerMilliliter) => new VolumeConcentration((_value * 1e-3) / 1e-1d, VolumeConcentrationUnit.DeciliterPerMilliliter), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.LiterPerLiter) => new VolumeConcentration(_value, VolumeConcentrationUnit.LiterPerLiter), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.LiterPerMilliliter) => new VolumeConcentration(_value * 1e-3, VolumeConcentrationUnit.LiterPerMilliliter), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MicroliterPerLiter) => new VolumeConcentration((_value) / 1e-6d, VolumeConcentrationUnit.MicroliterPerLiter), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MicroliterPerMilliliter) => new VolumeConcentration((_value * 1e-3) / 1e-6d, VolumeConcentrationUnit.MicroliterPerMilliliter), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MilliliterPerLiter) => new VolumeConcentration((_value) / 1e-3d, VolumeConcentrationUnit.MilliliterPerLiter), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.MilliliterPerMilliliter) => new VolumeConcentration((_value * 1e-3) / 1e-3d, VolumeConcentrationUnit.MilliliterPerMilliliter), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.NanoliterPerLiter) => new VolumeConcentration((_value) / 1e-9d, VolumeConcentrationUnit.NanoliterPerLiter), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.NanoliterPerMilliliter) => new VolumeConcentration((_value * 1e-3) / 1e-9d, VolumeConcentrationUnit.NanoliterPerMilliliter), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerBillion) => new VolumeConcentration(_value * 1e9, VolumeConcentrationUnit.PartPerBillion), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerMillion) => new VolumeConcentration(_value * 1e6, VolumeConcentrationUnit.PartPerMillion), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerThousand) => new VolumeConcentration(_value * 1e3, VolumeConcentrationUnit.PartPerThousand), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PartPerTrillion) => new VolumeConcentration(_value * 1e12, VolumeConcentrationUnit.PartPerTrillion), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.Percent) => new VolumeConcentration(_value * 1e2, VolumeConcentrationUnit.Percent), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PicoliterPerLiter) => new VolumeConcentration((_value) / 1e-12d, VolumeConcentrationUnit.PicoliterPerLiter), - (VolumeConcentrationUnit.DecimalFraction, VolumeConcentrationUnit.PicoliterPerMilliliter) => new VolumeConcentration((_value * 1e-3) / 1e-12d, VolumeConcentrationUnit.PicoliterPerMilliliter), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public VolumeConcentration ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not VolumeConcentrationUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeConcentrationUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(VolumeConcentrationUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(VolumeConcentrationUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -1098,7 +898,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs index 97bdfe23d4..dd9585e08c 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeFlow.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ 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] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct VolumeFlow : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -57,13 +56,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly VolumeFlowUnit? _unit; /// @@ -108,7 +107,7 @@ public static VolumeFlowInfo CreateDefault(Func - /// The for is [T^-1][L^3]. + /// The for is T^-1L^3. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(3, 0, -1, 0, 0, 0, 0); @@ -123,89 +122,235 @@ public static VolumeFlowInfo CreateDefault(FuncAn of representing the default unit mappings for VolumeFlow. public static IEnumerable> GetDefaultMappings() { - yield return new (VolumeFlowUnit.AcreFootPerDay, "AcreFootPerDay", "AcreFeetPerDay", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.AcreFootPerHour, "AcreFootPerHour", "AcreFeetPerHour", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.AcreFootPerMinute, "AcreFootPerMinute", "AcreFeetPerMinute", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.AcreFootPerSecond, "AcreFootPerSecond", "AcreFeetPerSecond", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.CentiliterPerDay, "CentiliterPerDay", "CentilitersPerDay", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.CentiliterPerHour, "CentiliterPerHour", "CentilitersPerHour", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.CentiliterPerMinute, "CentiliterPerMinute", "CentilitersPerMinute", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.CentiliterPerSecond, "CentiliterPerSecond", "CentilitersPerSecond", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.CubicCentimeterPerMinute, "CubicCentimeterPerMinute", "CubicCentimetersPerMinute", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Minute)); - yield return new (VolumeFlowUnit.CubicDecimeterPerMinute, "CubicDecimeterPerMinute", "CubicDecimetersPerMinute", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Minute)); - yield return new (VolumeFlowUnit.CubicFootPerHour, "CubicFootPerHour", "CubicFeetPerHour", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Hour)); - yield return new (VolumeFlowUnit.CubicFootPerMinute, "CubicFootPerMinute", "CubicFeetPerMinute", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Minute)); - yield return new (VolumeFlowUnit.CubicFootPerSecond, "CubicFootPerSecond", "CubicFeetPerSecond", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second)); - yield return new (VolumeFlowUnit.CubicMeterPerDay, "CubicMeterPerDay", "CubicMetersPerDay", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Day)); - yield return new (VolumeFlowUnit.CubicMeterPerHour, "CubicMeterPerHour", "CubicMetersPerHour", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Hour)); - yield return new (VolumeFlowUnit.CubicMeterPerMinute, "CubicMeterPerMinute", "CubicMetersPerMinute", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Minute)); + yield return new (VolumeFlowUnit.AcreFootPerDay, "AcreFootPerDay", "AcreFeetPerDay", BaseUnits.Undefined, + new QuantityValue(156250000000, 2230689087) + ); + yield return new (VolumeFlowUnit.AcreFootPerHour, "AcreFootPerHour", "AcreFeetPerHour", BaseUnits.Undefined, + new QuantityValue(19531250000, 6692067261) + ); + yield return new (VolumeFlowUnit.AcreFootPerMinute, "AcreFootPerMinute", "AcreFeetPerMinute", BaseUnits.Undefined, + new QuantityValue(976562500, 20076201783) + ); + yield return new (VolumeFlowUnit.AcreFootPerSecond, "AcreFootPerSecond", "AcreFeetPerSecond", BaseUnits.Undefined, + new QuantityValue(48828125, 60228605349) + ); + yield return new (VolumeFlowUnit.CentiliterPerDay, "CentiliterPerDay", "CentilitersPerDay", BaseUnits.Undefined, + 8640000000 + ); + yield return new (VolumeFlowUnit.CentiliterPerHour, "CentiliterPerHour", "CentilitersPerHour", BaseUnits.Undefined, + 360000000 + ); + yield return new (VolumeFlowUnit.CentiliterPerMinute, "CentiliterPerMinute", "CentilitersPerMinute", BaseUnits.Undefined, + 6000000 + ); + yield return new (VolumeFlowUnit.CentiliterPerSecond, "CentiliterPerSecond", "CentilitersPerSecond", BaseUnits.Undefined, + 100000 + ); + yield return new (VolumeFlowUnit.CubicCentimeterPerMinute, "CubicCentimeterPerMinute", "CubicCentimetersPerMinute", new BaseUnits(length: LengthUnit.Centimeter, time: DurationUnit.Minute), + 60000000 + ); + yield return new (VolumeFlowUnit.CubicDecimeterPerMinute, "CubicDecimeterPerMinute", "CubicDecimetersPerMinute", new BaseUnits(length: LengthUnit.Decimeter, time: DurationUnit.Minute), + 60000 + ); + yield return new (VolumeFlowUnit.CubicFootPerHour, "CubicFootPerHour", "CubicFeetPerHour", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Hour), + new QuantityValue(781250000000, 6145149) + ); + yield return new (VolumeFlowUnit.CubicFootPerMinute, "CubicFootPerMinute", "CubicFeetPerMinute", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Minute), + new QuantityValue(39062500000, 18435447) + ); + yield return new (VolumeFlowUnit.CubicFootPerSecond, "CubicFootPerSecond", "CubicFeetPerSecond", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Second), + new QuantityValue(1953125000, 55306341) + ); + yield return new (VolumeFlowUnit.CubicMeterPerDay, "CubicMeterPerDay", "CubicMetersPerDay", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Day), + 86400 + ); + yield return new (VolumeFlowUnit.CubicMeterPerHour, "CubicMeterPerHour", "CubicMetersPerHour", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Hour), + 3600 + ); + yield return new (VolumeFlowUnit.CubicMeterPerMinute, "CubicMeterPerMinute", "CubicMetersPerMinute", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Minute), + 60 + ); yield return new (VolumeFlowUnit.CubicMeterPerSecond, "CubicMeterPerSecond", "CubicMetersPerSecond", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)); - yield return new (VolumeFlowUnit.CubicMillimeterPerSecond, "CubicMillimeterPerSecond", "CubicMillimetersPerSecond", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second)); - yield return new (VolumeFlowUnit.CubicYardPerDay, "CubicYardPerDay", "CubicYardsPerDay", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Day)); - yield return new (VolumeFlowUnit.CubicYardPerHour, "CubicYardPerHour", "CubicYardsPerHour", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Hour)); - yield return new (VolumeFlowUnit.CubicYardPerMinute, "CubicYardPerMinute", "CubicYardsPerMinute", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Minute)); - yield return new (VolumeFlowUnit.CubicYardPerSecond, "CubicYardPerSecond", "CubicYardsPerSecond", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.DecaliterPerDay, "DecaliterPerDay", "DecalitersPerDay", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.DecaliterPerHour, "DecaliterPerHour", "DecalitersPerHour", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.DecaliterPerMinute, "DecaliterPerMinute", "DecalitersPerMinute", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.DecaliterPerSecond, "DecaliterPerSecond", "DecalitersPerSecond", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.DeciliterPerDay, "DeciliterPerDay", "DecilitersPerDay", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.DeciliterPerHour, "DeciliterPerHour", "DecilitersPerHour", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.DeciliterPerMinute, "DeciliterPerMinute", "DecilitersPerMinute", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.DeciliterPerSecond, "DeciliterPerSecond", "DecilitersPerSecond", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.HectoliterPerDay, "HectoliterPerDay", "HectolitersPerDay", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.HectoliterPerHour, "HectoliterPerHour", "HectolitersPerHour", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.HectoliterPerMinute, "HectoliterPerMinute", "HectolitersPerMinute", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.HectoliterPerSecond, "HectoliterPerSecond", "HectolitersPerSecond", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.KiloliterPerDay, "KiloliterPerDay", "KilolitersPerDay", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.KiloliterPerHour, "KiloliterPerHour", "KilolitersPerHour", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.KiloliterPerMinute, "KiloliterPerMinute", "KilolitersPerMinute", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.KiloliterPerSecond, "KiloliterPerSecond", "KilolitersPerSecond", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.KilousGallonPerMinute, "KilousGallonPerMinute", "KilousGallonsPerMinute", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.LiterPerDay, "LiterPerDay", "LitersPerDay", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.LiterPerHour, "LiterPerHour", "LitersPerHour", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.LiterPerMinute, "LiterPerMinute", "LitersPerMinute", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.LiterPerSecond, "LiterPerSecond", "LitersPerSecond", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.MegaliterPerDay, "MegaliterPerDay", "MegalitersPerDay", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.MegaliterPerHour, "MegaliterPerHour", "MegalitersPerHour", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.MegaliterPerMinute, "MegaliterPerMinute", "MegalitersPerMinute", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.MegaliterPerSecond, "MegaliterPerSecond", "MegalitersPerSecond", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.MegaukGallonPerDay, "MegaukGallonPerDay", "MegaukGallonsPerDay", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.MegaukGallonPerSecond, "MegaukGallonPerSecond", "MegaukGallonsPerSecond", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.MegausGallonPerDay, "MegausGallonPerDay", "MegausGallonsPerDay", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.MicroliterPerDay, "MicroliterPerDay", "MicrolitersPerDay", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.MicroliterPerHour, "MicroliterPerHour", "MicrolitersPerHour", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.MicroliterPerMinute, "MicroliterPerMinute", "MicrolitersPerMinute", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.MicroliterPerSecond, "MicroliterPerSecond", "MicrolitersPerSecond", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.MilliliterPerDay, "MilliliterPerDay", "MillilitersPerDay", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.MilliliterPerHour, "MilliliterPerHour", "MillilitersPerHour", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.MilliliterPerMinute, "MilliliterPerMinute", "MillilitersPerMinute", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.MilliliterPerSecond, "MilliliterPerSecond", "MillilitersPerSecond", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.MillionUsGallonPerDay, "MillionUsGallonPerDay", "MillionUsGallonsPerDay", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.NanoliterPerDay, "NanoliterPerDay", "NanolitersPerDay", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.NanoliterPerHour, "NanoliterPerHour", "NanolitersPerHour", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.NanoliterPerMinute, "NanoliterPerMinute", "NanolitersPerMinute", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.NanoliterPerSecond, "NanoliterPerSecond", "NanolitersPerSecond", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.OilBarrelPerDay, "OilBarrelPerDay", "OilBarrelsPerDay", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.OilBarrelPerHour, "OilBarrelPerHour", "OilBarrelsPerHour", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.OilBarrelPerMinute, "OilBarrelPerMinute", "OilBarrelsPerMinute", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.OilBarrelPerSecond, "OilBarrelPerSecond", "OilBarrelsPerSecond", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.UkGallonPerDay, "UkGallonPerDay", "UkGallonsPerDay", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.UkGallonPerHour, "UkGallonPerHour", "UkGallonsPerHour", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.UkGallonPerMinute, "UkGallonPerMinute", "UkGallonsPerMinute", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.UkGallonPerSecond, "UkGallonPerSecond", "UkGallonsPerSecond", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.UsGallonPerDay, "UsGallonPerDay", "UsGallonsPerDay", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.UsGallonPerHour, "UsGallonPerHour", "UsGallonsPerHour", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.UsGallonPerMinute, "UsGallonPerMinute", "UsGallonsPerMinute", BaseUnits.Undefined); - yield return new (VolumeFlowUnit.UsGallonPerSecond, "UsGallonPerSecond", "UsGallonsPerSecond", BaseUnits.Undefined); + yield return new (VolumeFlowUnit.CubicMillimeterPerSecond, "CubicMillimeterPerSecond", "CubicMillimetersPerSecond", new BaseUnits(length: LengthUnit.Millimeter, time: DurationUnit.Second), + 1000000000 + ); + yield return new (VolumeFlowUnit.CubicYardPerDay, "CubicYardPerDay", "CubicYardsPerDay", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Day), + new QuantityValue(6250000000000, 55306341) + ); + yield return new (VolumeFlowUnit.CubicYardPerHour, "CubicYardPerHour", "CubicYardsPerHour", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Hour), + new QuantityValue(781250000000, 165919023) + ); + yield return new (VolumeFlowUnit.CubicYardPerMinute, "CubicYardPerMinute", "CubicYardsPerMinute", new BaseUnits(length: LengthUnit.Yard, time: DurationUnit.Minute), + new QuantityValue(39062500000, 497757069) + ); + yield return new (VolumeFlowUnit.CubicYardPerSecond, "CubicYardPerSecond", "CubicYardsPerSecond", BaseUnits.Undefined, + new QuantityValue(1953125000, 1493271207) + ); + yield return new (VolumeFlowUnit.DecaliterPerDay, "DecaliterPerDay", "DecalitersPerDay", BaseUnits.Undefined, + 8640000 + ); + yield return new (VolumeFlowUnit.DecaliterPerHour, "DecaliterPerHour", "DecalitersPerHour", BaseUnits.Undefined, + 360000 + ); + yield return new (VolumeFlowUnit.DecaliterPerMinute, "DecaliterPerMinute", "DecalitersPerMinute", BaseUnits.Undefined, + 6000 + ); + yield return new (VolumeFlowUnit.DecaliterPerSecond, "DecaliterPerSecond", "DecalitersPerSecond", BaseUnits.Undefined, + 100 + ); + yield return new (VolumeFlowUnit.DeciliterPerDay, "DeciliterPerDay", "DecilitersPerDay", BaseUnits.Undefined, + 864000000 + ); + yield return new (VolumeFlowUnit.DeciliterPerHour, "DeciliterPerHour", "DecilitersPerHour", BaseUnits.Undefined, + 36000000 + ); + yield return new (VolumeFlowUnit.DeciliterPerMinute, "DeciliterPerMinute", "DecilitersPerMinute", BaseUnits.Undefined, + 600000 + ); + yield return new (VolumeFlowUnit.DeciliterPerSecond, "DeciliterPerSecond", "DecilitersPerSecond", BaseUnits.Undefined, + 10000 + ); + yield return new (VolumeFlowUnit.HectoliterPerDay, "HectoliterPerDay", "HectolitersPerDay", BaseUnits.Undefined, + 864000 + ); + yield return new (VolumeFlowUnit.HectoliterPerHour, "HectoliterPerHour", "HectolitersPerHour", BaseUnits.Undefined, + 36000 + ); + yield return new (VolumeFlowUnit.HectoliterPerMinute, "HectoliterPerMinute", "HectolitersPerMinute", BaseUnits.Undefined, + 600 + ); + yield return new (VolumeFlowUnit.HectoliterPerSecond, "HectoliterPerSecond", "HectolitersPerSecond", BaseUnits.Undefined, + 10 + ); + yield return new (VolumeFlowUnit.KiloliterPerDay, "KiloliterPerDay", "KilolitersPerDay", BaseUnits.Undefined, + 86400 + ); + yield return new (VolumeFlowUnit.KiloliterPerHour, "KiloliterPerHour", "KilolitersPerHour", BaseUnits.Undefined, + 3600 + ); + yield return new (VolumeFlowUnit.KiloliterPerMinute, "KiloliterPerMinute", "KilolitersPerMinute", BaseUnits.Undefined, + 60 + ); + yield return new (VolumeFlowUnit.KiloliterPerSecond, "KiloliterPerSecond", "KilolitersPerSecond", BaseUnits.Undefined, + 1 + ); + yield return new (VolumeFlowUnit.KilousGallonPerMinute, "KilousGallonPerMinute", "KilousGallonsPerMinute", BaseUnits.Undefined, + new QuantityValue(2500000000, 157725491) + ); + yield return new (VolumeFlowUnit.LiterPerDay, "LiterPerDay", "LitersPerDay", BaseUnits.Undefined, + 86400000 + ); + yield return new (VolumeFlowUnit.LiterPerHour, "LiterPerHour", "LitersPerHour", BaseUnits.Undefined, + 3600000 + ); + yield return new (VolumeFlowUnit.LiterPerMinute, "LiterPerMinute", "LitersPerMinute", BaseUnits.Undefined, + 60000 + ); + yield return new (VolumeFlowUnit.LiterPerSecond, "LiterPerSecond", "LitersPerSecond", BaseUnits.Undefined, + 1000 + ); + yield return new (VolumeFlowUnit.MegaliterPerDay, "MegaliterPerDay", "MegalitersPerDay", BaseUnits.Undefined, + new QuantityValue(432, 5) + ); + yield return new (VolumeFlowUnit.MegaliterPerHour, "MegaliterPerHour", "MegalitersPerHour", BaseUnits.Undefined, + new QuantityValue(18, 5) + ); + yield return new (VolumeFlowUnit.MegaliterPerMinute, "MegaliterPerMinute", "MegalitersPerMinute", BaseUnits.Undefined, + new QuantityValue(3, 50) + ); + yield return new (VolumeFlowUnit.MegaliterPerSecond, "MegaliterPerSecond", "MegalitersPerSecond", BaseUnits.Undefined, + new QuantityValue(1, 1000) + ); + yield return new (VolumeFlowUnit.MegaukGallonPerDay, "MegaukGallonPerDay", "MegaukGallonsPerDay", BaseUnits.Undefined, + new QuantityValue(8640000, 454609) + ); + yield return new (VolumeFlowUnit.MegaukGallonPerSecond, "MegaukGallonPerSecond", "MegaukGallonsPerSecond", BaseUnits.Undefined, + new QuantityValue(100, 454609) + ); + yield return new (VolumeFlowUnit.MegausGallonPerDay, "MegausGallonPerDay", "MegausGallonsPerDay", BaseUnits.Undefined, + new QuantityValue(3600000000, 157725491) + ); + yield return new (VolumeFlowUnit.MicroliterPerDay, "MicroliterPerDay", "MicrolitersPerDay", BaseUnits.Undefined, + 86400000000000 + ); + yield return new (VolumeFlowUnit.MicroliterPerHour, "MicroliterPerHour", "MicrolitersPerHour", BaseUnits.Undefined, + 3600000000000 + ); + yield return new (VolumeFlowUnit.MicroliterPerMinute, "MicroliterPerMinute", "MicrolitersPerMinute", BaseUnits.Undefined, + 60000000000 + ); + yield return new (VolumeFlowUnit.MicroliterPerSecond, "MicroliterPerSecond", "MicrolitersPerSecond", BaseUnits.Undefined, + 1000000000 + ); + yield return new (VolumeFlowUnit.MilliliterPerDay, "MilliliterPerDay", "MillilitersPerDay", BaseUnits.Undefined, + 86400000000 + ); + yield return new (VolumeFlowUnit.MilliliterPerHour, "MilliliterPerHour", "MillilitersPerHour", BaseUnits.Undefined, + 3600000000 + ); + yield return new (VolumeFlowUnit.MilliliterPerMinute, "MilliliterPerMinute", "MillilitersPerMinute", BaseUnits.Undefined, + 60000000 + ); + yield return new (VolumeFlowUnit.MilliliterPerSecond, "MilliliterPerSecond", "MillilitersPerSecond", BaseUnits.Undefined, + 1000000 + ); + yield return new (VolumeFlowUnit.MillionUsGallonPerDay, "MillionUsGallonPerDay", "MillionUsGallonsPerDay", BaseUnits.Undefined, + new QuantityValue(3600000000, 157725491) + ); + yield return new (VolumeFlowUnit.NanoliterPerDay, "NanoliterPerDay", "NanolitersPerDay", BaseUnits.Undefined, + 86400000000000000 + ); + yield return new (VolumeFlowUnit.NanoliterPerHour, "NanoliterPerHour", "NanolitersPerHour", BaseUnits.Undefined, + 3600000000000000 + ); + yield return new (VolumeFlowUnit.NanoliterPerMinute, "NanoliterPerMinute", "NanolitersPerMinute", BaseUnits.Undefined, + 60000000000000 + ); + yield return new (VolumeFlowUnit.NanoliterPerSecond, "NanoliterPerSecond", "NanolitersPerSecond", BaseUnits.Undefined, + 1000000000000 + ); + yield return new (VolumeFlowUnit.OilBarrelPerDay, "OilBarrelPerDay", "OilBarrelsPerDay", BaseUnits.Undefined, + new QuantityValue(600000000000000, 1104078437) + ); + yield return new (VolumeFlowUnit.OilBarrelPerHour, "OilBarrelPerHour", "OilBarrelsPerHour", BaseUnits.Undefined, + new QuantityValue(25000000000000, 1104078437) + ); + yield return new (VolumeFlowUnit.OilBarrelPerMinute, "OilBarrelPerMinute", "OilBarrelsPerMinute", BaseUnits.Undefined, + new QuantityValue(1250000000000, 3312235311) + ); + yield return new (VolumeFlowUnit.OilBarrelPerSecond, "OilBarrelPerSecond", "OilBarrelsPerSecond", BaseUnits.Undefined, + new QuantityValue(62500000000, 9936705933) + ); + yield return new (VolumeFlowUnit.UkGallonPerDay, "UkGallonPerDay", "UkGallonsPerDay", BaseUnits.Undefined, + new QuantityValue(8640000000000, 454609) + ); + yield return new (VolumeFlowUnit.UkGallonPerHour, "UkGallonPerHour", "UkGallonsPerHour", BaseUnits.Undefined, + new QuantityValue(360000000000, 454609) + ); + yield return new (VolumeFlowUnit.UkGallonPerMinute, "UkGallonPerMinute", "UkGallonsPerMinute", BaseUnits.Undefined, + new QuantityValue(6000000000, 454609) + ); + yield return new (VolumeFlowUnit.UkGallonPerSecond, "UkGallonPerSecond", "UkGallonsPerSecond", BaseUnits.Undefined, + new QuantityValue(100000000, 454609) + ); + yield return new (VolumeFlowUnit.UsGallonPerDay, "UsGallonPerDay", "UsGallonsPerDay", BaseUnits.Undefined, + new QuantityValue(3600000000000000, 157725491) + ); + yield return new (VolumeFlowUnit.UsGallonPerHour, "UsGallonPerHour", "UsGallonsPerHour", BaseUnits.Undefined, + new QuantityValue(150000000000000, 157725491) + ); + yield return new (VolumeFlowUnit.UsGallonPerMinute, "UsGallonPerMinute", "UsGallonsPerMinute", BaseUnits.Undefined, + new QuantityValue(2500000000000, 157725491) + ); + yield return new (VolumeFlowUnit.UsGallonPerSecond, "UsGallonPerSecond", "UsGallonsPerSecond", BaseUnits.Undefined, + new QuantityValue(125000000000, 473176473) + ); } } static VolumeFlow() { - Info = VolumeFlowInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(VolumeFlowInfo.CreateDefault); } /// @@ -213,7 +358,7 @@ static VolumeFlow() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public VolumeFlow(double value, VolumeFlowUnit unit) + public VolumeFlow(QuantityValue value, VolumeFlowUnit unit) { _value = value; _unit = unit; @@ -227,7 +372,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -238,7 +383,8 @@ public VolumeFlow(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -267,10 +413,8 @@ public VolumeFlow(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public VolumeFlowUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -309,546 +453,384 @@ public VolumeFlow(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AcreFeetPerDay => As(VolumeFlowUnit.AcreFootPerDay); + public QuantityValue AcreFeetPerDay => this.As(VolumeFlowUnit.AcreFootPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AcreFeetPerHour => As(VolumeFlowUnit.AcreFootPerHour); + public QuantityValue AcreFeetPerHour => this.As(VolumeFlowUnit.AcreFootPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AcreFeetPerMinute => As(VolumeFlowUnit.AcreFootPerMinute); + public QuantityValue AcreFeetPerMinute => this.As(VolumeFlowUnit.AcreFootPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double AcreFeetPerSecond => As(VolumeFlowUnit.AcreFootPerSecond); + public QuantityValue AcreFeetPerSecond => this.As(VolumeFlowUnit.AcreFootPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentilitersPerDay => As(VolumeFlowUnit.CentiliterPerDay); + public QuantityValue CentilitersPerDay => this.As(VolumeFlowUnit.CentiliterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentilitersPerHour => As(VolumeFlowUnit.CentiliterPerHour); + public QuantityValue CentilitersPerHour => this.As(VolumeFlowUnit.CentiliterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentilitersPerMinute => As(VolumeFlowUnit.CentiliterPerMinute); + public QuantityValue CentilitersPerMinute => this.As(VolumeFlowUnit.CentiliterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentilitersPerSecond => As(VolumeFlowUnit.CentiliterPerSecond); + public QuantityValue CentilitersPerSecond => this.As(VolumeFlowUnit.CentiliterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicCentimetersPerMinute => As(VolumeFlowUnit.CubicCentimeterPerMinute); + public QuantityValue CubicCentimetersPerMinute => this.As(VolumeFlowUnit.CubicCentimeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicDecimetersPerMinute => As(VolumeFlowUnit.CubicDecimeterPerMinute); + public QuantityValue CubicDecimetersPerMinute => this.As(VolumeFlowUnit.CubicDecimeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicFeetPerHour => As(VolumeFlowUnit.CubicFootPerHour); + public QuantityValue CubicFeetPerHour => this.As(VolumeFlowUnit.CubicFootPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicFeetPerMinute => As(VolumeFlowUnit.CubicFootPerMinute); + public QuantityValue CubicFeetPerMinute => this.As(VolumeFlowUnit.CubicFootPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicFeetPerSecond => As(VolumeFlowUnit.CubicFootPerSecond); + public QuantityValue CubicFeetPerSecond => this.As(VolumeFlowUnit.CubicFootPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicMetersPerDay => As(VolumeFlowUnit.CubicMeterPerDay); + public QuantityValue CubicMetersPerDay => this.As(VolumeFlowUnit.CubicMeterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicMetersPerHour => As(VolumeFlowUnit.CubicMeterPerHour); + public QuantityValue CubicMetersPerHour => this.As(VolumeFlowUnit.CubicMeterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicMetersPerMinute => As(VolumeFlowUnit.CubicMeterPerMinute); + public QuantityValue CubicMetersPerMinute => this.As(VolumeFlowUnit.CubicMeterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicMetersPerSecond => As(VolumeFlowUnit.CubicMeterPerSecond); + public QuantityValue CubicMetersPerSecond => this.As(VolumeFlowUnit.CubicMeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicMillimetersPerSecond => As(VolumeFlowUnit.CubicMillimeterPerSecond); + public QuantityValue CubicMillimetersPerSecond => this.As(VolumeFlowUnit.CubicMillimeterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicYardsPerDay => As(VolumeFlowUnit.CubicYardPerDay); + public QuantityValue CubicYardsPerDay => this.As(VolumeFlowUnit.CubicYardPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicYardsPerHour => As(VolumeFlowUnit.CubicYardPerHour); + public QuantityValue CubicYardsPerHour => this.As(VolumeFlowUnit.CubicYardPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicYardsPerMinute => As(VolumeFlowUnit.CubicYardPerMinute); + public QuantityValue CubicYardsPerMinute => this.As(VolumeFlowUnit.CubicYardPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicYardsPerSecond => As(VolumeFlowUnit.CubicYardPerSecond); + public QuantityValue CubicYardsPerSecond => this.As(VolumeFlowUnit.CubicYardPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecalitersPerDay => As(VolumeFlowUnit.DecaliterPerDay); + public QuantityValue DecalitersPerDay => this.As(VolumeFlowUnit.DecaliterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecalitersPerHour => As(VolumeFlowUnit.DecaliterPerHour); + public QuantityValue DecalitersPerHour => this.As(VolumeFlowUnit.DecaliterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecalitersPerMinute => As(VolumeFlowUnit.DecaliterPerMinute); + public QuantityValue DecalitersPerMinute => this.As(VolumeFlowUnit.DecaliterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecalitersPerSecond => As(VolumeFlowUnit.DecaliterPerSecond); + public QuantityValue DecalitersPerSecond => this.As(VolumeFlowUnit.DecaliterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecilitersPerDay => As(VolumeFlowUnit.DeciliterPerDay); + public QuantityValue DecilitersPerDay => this.As(VolumeFlowUnit.DeciliterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecilitersPerHour => As(VolumeFlowUnit.DeciliterPerHour); + public QuantityValue DecilitersPerHour => this.As(VolumeFlowUnit.DeciliterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecilitersPerMinute => As(VolumeFlowUnit.DeciliterPerMinute); + public QuantityValue DecilitersPerMinute => this.As(VolumeFlowUnit.DeciliterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecilitersPerSecond => As(VolumeFlowUnit.DeciliterPerSecond); + public QuantityValue DecilitersPerSecond => this.As(VolumeFlowUnit.DeciliterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HectolitersPerDay => As(VolumeFlowUnit.HectoliterPerDay); + public QuantityValue HectolitersPerDay => this.As(VolumeFlowUnit.HectoliterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HectolitersPerHour => As(VolumeFlowUnit.HectoliterPerHour); + public QuantityValue HectolitersPerHour => this.As(VolumeFlowUnit.HectoliterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HectolitersPerMinute => As(VolumeFlowUnit.HectoliterPerMinute); + public QuantityValue HectolitersPerMinute => this.As(VolumeFlowUnit.HectoliterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double HectolitersPerSecond => As(VolumeFlowUnit.HectoliterPerSecond); + public QuantityValue HectolitersPerSecond => this.As(VolumeFlowUnit.HectoliterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilolitersPerDay => As(VolumeFlowUnit.KiloliterPerDay); + public QuantityValue KilolitersPerDay => this.As(VolumeFlowUnit.KiloliterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilolitersPerHour => As(VolumeFlowUnit.KiloliterPerHour); + public QuantityValue KilolitersPerHour => this.As(VolumeFlowUnit.KiloliterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilolitersPerMinute => As(VolumeFlowUnit.KiloliterPerMinute); + public QuantityValue KilolitersPerMinute => this.As(VolumeFlowUnit.KiloliterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilolitersPerSecond => As(VolumeFlowUnit.KiloliterPerSecond); + public QuantityValue KilolitersPerSecond => this.As(VolumeFlowUnit.KiloliterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilousGallonsPerMinute => As(VolumeFlowUnit.KilousGallonPerMinute); + public QuantityValue KilousGallonsPerMinute => this.As(VolumeFlowUnit.KilousGallonPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double LitersPerDay => As(VolumeFlowUnit.LiterPerDay); + public QuantityValue LitersPerDay => this.As(VolumeFlowUnit.LiterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double LitersPerHour => As(VolumeFlowUnit.LiterPerHour); + public QuantityValue LitersPerHour => this.As(VolumeFlowUnit.LiterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double LitersPerMinute => As(VolumeFlowUnit.LiterPerMinute); + public QuantityValue LitersPerMinute => this.As(VolumeFlowUnit.LiterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double LitersPerSecond => As(VolumeFlowUnit.LiterPerSecond); + public QuantityValue LitersPerSecond => this.As(VolumeFlowUnit.LiterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegalitersPerDay => As(VolumeFlowUnit.MegaliterPerDay); + public QuantityValue MegalitersPerDay => this.As(VolumeFlowUnit.MegaliterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegalitersPerHour => As(VolumeFlowUnit.MegaliterPerHour); + public QuantityValue MegalitersPerHour => this.As(VolumeFlowUnit.MegaliterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegalitersPerMinute => As(VolumeFlowUnit.MegaliterPerMinute); + public QuantityValue MegalitersPerMinute => this.As(VolumeFlowUnit.MegaliterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegalitersPerSecond => As(VolumeFlowUnit.MegaliterPerSecond); + public QuantityValue MegalitersPerSecond => this.As(VolumeFlowUnit.MegaliterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegaukGallonsPerDay => As(VolumeFlowUnit.MegaukGallonPerDay); + public QuantityValue MegaukGallonsPerDay => this.As(VolumeFlowUnit.MegaukGallonPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegaukGallonsPerSecond => As(VolumeFlowUnit.MegaukGallonPerSecond); + public QuantityValue MegaukGallonsPerSecond => this.As(VolumeFlowUnit.MegaukGallonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegausGallonsPerDay => As(VolumeFlowUnit.MegausGallonPerDay); + public QuantityValue MegausGallonsPerDay => this.As(VolumeFlowUnit.MegausGallonPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrolitersPerDay => As(VolumeFlowUnit.MicroliterPerDay); + public QuantityValue MicrolitersPerDay => this.As(VolumeFlowUnit.MicroliterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrolitersPerHour => As(VolumeFlowUnit.MicroliterPerHour); + public QuantityValue MicrolitersPerHour => this.As(VolumeFlowUnit.MicroliterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrolitersPerMinute => As(VolumeFlowUnit.MicroliterPerMinute); + public QuantityValue MicrolitersPerMinute => this.As(VolumeFlowUnit.MicroliterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MicrolitersPerSecond => As(VolumeFlowUnit.MicroliterPerSecond); + public QuantityValue MicrolitersPerSecond => this.As(VolumeFlowUnit.MicroliterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillilitersPerDay => As(VolumeFlowUnit.MilliliterPerDay); + public QuantityValue MillilitersPerDay => this.As(VolumeFlowUnit.MilliliterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillilitersPerHour => As(VolumeFlowUnit.MilliliterPerHour); + public QuantityValue MillilitersPerHour => this.As(VolumeFlowUnit.MilliliterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillilitersPerMinute => As(VolumeFlowUnit.MilliliterPerMinute); + public QuantityValue MillilitersPerMinute => this.As(VolumeFlowUnit.MilliliterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillilitersPerSecond => As(VolumeFlowUnit.MilliliterPerSecond); + public QuantityValue MillilitersPerSecond => this.As(VolumeFlowUnit.MilliliterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillionUsGallonsPerDay => As(VolumeFlowUnit.MillionUsGallonPerDay); + public QuantityValue MillionUsGallonsPerDay => this.As(VolumeFlowUnit.MillionUsGallonPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanolitersPerDay => As(VolumeFlowUnit.NanoliterPerDay); + public QuantityValue NanolitersPerDay => this.As(VolumeFlowUnit.NanoliterPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanolitersPerHour => As(VolumeFlowUnit.NanoliterPerHour); + public QuantityValue NanolitersPerHour => this.As(VolumeFlowUnit.NanoliterPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanolitersPerMinute => As(VolumeFlowUnit.NanoliterPerMinute); + public QuantityValue NanolitersPerMinute => this.As(VolumeFlowUnit.NanoliterPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double NanolitersPerSecond => As(VolumeFlowUnit.NanoliterPerSecond); + public QuantityValue NanolitersPerSecond => this.As(VolumeFlowUnit.NanoliterPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double OilBarrelsPerDay => As(VolumeFlowUnit.OilBarrelPerDay); + public QuantityValue OilBarrelsPerDay => this.As(VolumeFlowUnit.OilBarrelPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double OilBarrelsPerHour => As(VolumeFlowUnit.OilBarrelPerHour); + public QuantityValue OilBarrelsPerHour => this.As(VolumeFlowUnit.OilBarrelPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double OilBarrelsPerMinute => As(VolumeFlowUnit.OilBarrelPerMinute); + public QuantityValue OilBarrelsPerMinute => this.As(VolumeFlowUnit.OilBarrelPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double OilBarrelsPerSecond => As(VolumeFlowUnit.OilBarrelPerSecond); + public QuantityValue OilBarrelsPerSecond => this.As(VolumeFlowUnit.OilBarrelPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UkGallonsPerDay => As(VolumeFlowUnit.UkGallonPerDay); + public QuantityValue UkGallonsPerDay => this.As(VolumeFlowUnit.UkGallonPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UkGallonsPerHour => As(VolumeFlowUnit.UkGallonPerHour); + public QuantityValue UkGallonsPerHour => this.As(VolumeFlowUnit.UkGallonPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UkGallonsPerMinute => As(VolumeFlowUnit.UkGallonPerMinute); + public QuantityValue UkGallonsPerMinute => this.As(VolumeFlowUnit.UkGallonPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UkGallonsPerSecond => As(VolumeFlowUnit.UkGallonPerSecond); + public QuantityValue UkGallonsPerSecond => this.As(VolumeFlowUnit.UkGallonPerSecond); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsGallonsPerDay => As(VolumeFlowUnit.UsGallonPerDay); + public QuantityValue UsGallonsPerDay => this.As(VolumeFlowUnit.UsGallonPerDay); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsGallonsPerHour => As(VolumeFlowUnit.UsGallonPerHour); + public QuantityValue UsGallonsPerHour => this.As(VolumeFlowUnit.UsGallonPerHour); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsGallonsPerMinute => As(VolumeFlowUnit.UsGallonPerMinute); + public QuantityValue UsGallonsPerMinute => this.As(VolumeFlowUnit.UsGallonPerMinute); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsGallonsPerSecond => As(VolumeFlowUnit.UsGallonPerSecond); + public QuantityValue UsGallonsPerSecond => this.As(VolumeFlowUnit.UsGallonPerSecond); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: VolumeFlowUnit -> BaseUnit - unitConverter.SetConversionFunction(VolumeFlowUnit.AcreFootPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.AcreFootPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.AcreFootPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.AcreFootPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CentiliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CentiliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CentiliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CentiliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicCentimeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicDecimeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicFootPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicFootPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicFootPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMillimeterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicYardPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicYardPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicYardPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicYardPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.DecaliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.DecaliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.DecaliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.DecaliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.DeciliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.DeciliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.DeciliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.DeciliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.HectoliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.HectoliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.HectoliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.HectoliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.KiloliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.KiloliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.KiloliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.KiloliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.KilousGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.LiterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.LiterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.LiterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.LiterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.MegaliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.MegaliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.MegaliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.MegaliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.MegaukGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.MegaukGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.MegausGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.MicroliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.MicroliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.MicroliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.MicroliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.MilliliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.MilliliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.MilliliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.MilliliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.MillionUsGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.NanoliterPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.NanoliterPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.NanoliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.NanoliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.OilBarrelPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.OilBarrelPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.OilBarrelPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.OilBarrelPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.UkGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.UkGallonPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.UkGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.UkGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.UsGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.UsGallonPerHour, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.UsGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.UsGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerSecond)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerSecond, quantity => quantity); - - // Register in unit converter: BaseUnit -> VolumeFlowUnit - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.AcreFootPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.AcreFootPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.AcreFootPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.AcreFootPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.CentiliterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.CentiliterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CentiliterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CentiliterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicCentimeterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CubicCentimeterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicDecimeterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CubicDecimeterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.CubicFootPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CubicFootPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicFootPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMeterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMillimeterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicMillimeterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.CubicYardPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.CubicYardPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.CubicYardPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.CubicYardPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DecaliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.DecaliterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DecaliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.DecaliterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DecaliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.DecaliterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DecaliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.DecaliterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.DeciliterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.DeciliterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.DeciliterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.DeciliterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.HectoliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.HectoliterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.HectoliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.HectoliterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.HectoliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.HectoliterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.HectoliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.HectoliterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.KiloliterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.KiloliterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.KiloliterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.KiloliterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KilousGallonPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.KilousGallonPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.LiterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.LiterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.LiterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.LiterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.MegaliterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.MegaliterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.MegaliterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.MegaliterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaukGallonPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.MegaukGallonPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaukGallonPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.MegaukGallonPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegausGallonPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.MegausGallonPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.MicroliterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.MicroliterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.MicroliterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.MicroliterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.MilliliterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.MilliliterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.MilliliterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.MilliliterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MillionUsGallonPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.MillionUsGallonPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.NanoliterPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.NanoliterPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.NanoliterPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.NanoliterPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.OilBarrelPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.OilBarrelPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.OilBarrelPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.OilBarrelPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.UkGallonPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.UkGallonPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.UkGallonPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.UkGallonPerSecond)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerDay, quantity => quantity.ToUnit(VolumeFlowUnit.UsGallonPerDay)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerHour, quantity => quantity.ToUnit(VolumeFlowUnit.UsGallonPerHour)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerMinute, quantity => quantity.ToUnit(VolumeFlowUnit.UsGallonPerMinute)); - unitConverter.SetConversionFunction(VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerSecond, quantity => quantity.ToUnit(VolumeFlowUnit.UsGallonPerSecond)); - } - /// /// Get unit abbreviation string. /// @@ -877,7 +859,7 @@ public static string GetAbbreviation(VolumeFlowUnit unit, IFormatProvider? provi /// /// Creates a from . /// - public static VolumeFlow FromAcreFeetPerDay(double value) + public static VolumeFlow FromAcreFeetPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.AcreFootPerDay); } @@ -885,7 +867,7 @@ public static VolumeFlow FromAcreFeetPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromAcreFeetPerHour(double value) + public static VolumeFlow FromAcreFeetPerHour(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.AcreFootPerHour); } @@ -893,7 +875,7 @@ public static VolumeFlow FromAcreFeetPerHour(double value) /// /// Creates a from . /// - public static VolumeFlow FromAcreFeetPerMinute(double value) + public static VolumeFlow FromAcreFeetPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.AcreFootPerMinute); } @@ -901,7 +883,7 @@ public static VolumeFlow FromAcreFeetPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromAcreFeetPerSecond(double value) + public static VolumeFlow FromAcreFeetPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.AcreFootPerSecond); } @@ -909,7 +891,7 @@ public static VolumeFlow FromAcreFeetPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromCentilitersPerDay(double value) + public static VolumeFlow FromCentilitersPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerDay); } @@ -917,7 +899,7 @@ public static VolumeFlow FromCentilitersPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromCentilitersPerHour(double value) + public static VolumeFlow FromCentilitersPerHour(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerHour); } @@ -925,7 +907,7 @@ public static VolumeFlow FromCentilitersPerHour(double value) /// /// Creates a from . /// - public static VolumeFlow FromCentilitersPerMinute(double value) + public static VolumeFlow FromCentilitersPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerMinute); } @@ -933,7 +915,7 @@ public static VolumeFlow FromCentilitersPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromCentilitersPerSecond(double value) + public static VolumeFlow FromCentilitersPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CentiliterPerSecond); } @@ -941,7 +923,7 @@ public static VolumeFlow FromCentilitersPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromCubicCentimetersPerMinute(double value) + public static VolumeFlow FromCubicCentimetersPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CubicCentimeterPerMinute); } @@ -949,7 +931,7 @@ public static VolumeFlow FromCubicCentimetersPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromCubicDecimetersPerMinute(double value) + public static VolumeFlow FromCubicDecimetersPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CubicDecimeterPerMinute); } @@ -957,7 +939,7 @@ public static VolumeFlow FromCubicDecimetersPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromCubicFeetPerHour(double value) + public static VolumeFlow FromCubicFeetPerHour(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerHour); } @@ -965,7 +947,7 @@ public static VolumeFlow FromCubicFeetPerHour(double value) /// /// Creates a from . /// - public static VolumeFlow FromCubicFeetPerMinute(double value) + public static VolumeFlow FromCubicFeetPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerMinute); } @@ -973,7 +955,7 @@ public static VolumeFlow FromCubicFeetPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromCubicFeetPerSecond(double value) + public static VolumeFlow FromCubicFeetPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CubicFootPerSecond); } @@ -981,7 +963,7 @@ public static VolumeFlow FromCubicFeetPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromCubicMetersPerDay(double value) + public static VolumeFlow FromCubicMetersPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerDay); } @@ -989,7 +971,7 @@ public static VolumeFlow FromCubicMetersPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromCubicMetersPerHour(double value) + public static VolumeFlow FromCubicMetersPerHour(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerHour); } @@ -997,7 +979,7 @@ public static VolumeFlow FromCubicMetersPerHour(double value) /// /// Creates a from . /// - public static VolumeFlow FromCubicMetersPerMinute(double value) + public static VolumeFlow FromCubicMetersPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerMinute); } @@ -1005,7 +987,7 @@ public static VolumeFlow FromCubicMetersPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromCubicMetersPerSecond(double value) + public static VolumeFlow FromCubicMetersPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CubicMeterPerSecond); } @@ -1013,7 +995,7 @@ public static VolumeFlow FromCubicMetersPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromCubicMillimetersPerSecond(double value) + public static VolumeFlow FromCubicMillimetersPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CubicMillimeterPerSecond); } @@ -1021,7 +1003,7 @@ public static VolumeFlow FromCubicMillimetersPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromCubicYardsPerDay(double value) + public static VolumeFlow FromCubicYardsPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerDay); } @@ -1029,7 +1011,7 @@ public static VolumeFlow FromCubicYardsPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromCubicYardsPerHour(double value) + public static VolumeFlow FromCubicYardsPerHour(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerHour); } @@ -1037,7 +1019,7 @@ public static VolumeFlow FromCubicYardsPerHour(double value) /// /// Creates a from . /// - public static VolumeFlow FromCubicYardsPerMinute(double value) + public static VolumeFlow FromCubicYardsPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerMinute); } @@ -1045,7 +1027,7 @@ public static VolumeFlow FromCubicYardsPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromCubicYardsPerSecond(double value) + public static VolumeFlow FromCubicYardsPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.CubicYardPerSecond); } @@ -1053,7 +1035,7 @@ public static VolumeFlow FromCubicYardsPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromDecalitersPerDay(double value) + public static VolumeFlow FromDecalitersPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.DecaliterPerDay); } @@ -1061,7 +1043,7 @@ public static VolumeFlow FromDecalitersPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromDecalitersPerHour(double value) + public static VolumeFlow FromDecalitersPerHour(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.DecaliterPerHour); } @@ -1069,7 +1051,7 @@ public static VolumeFlow FromDecalitersPerHour(double value) /// /// Creates a from . /// - public static VolumeFlow FromDecalitersPerMinute(double value) + public static VolumeFlow FromDecalitersPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.DecaliterPerMinute); } @@ -1077,7 +1059,7 @@ public static VolumeFlow FromDecalitersPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromDecalitersPerSecond(double value) + public static VolumeFlow FromDecalitersPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.DecaliterPerSecond); } @@ -1085,7 +1067,7 @@ public static VolumeFlow FromDecalitersPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromDecilitersPerDay(double value) + public static VolumeFlow FromDecilitersPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerDay); } @@ -1093,7 +1075,7 @@ public static VolumeFlow FromDecilitersPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromDecilitersPerHour(double value) + public static VolumeFlow FromDecilitersPerHour(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerHour); } @@ -1101,7 +1083,7 @@ public static VolumeFlow FromDecilitersPerHour(double value) /// /// Creates a from . /// - public static VolumeFlow FromDecilitersPerMinute(double value) + public static VolumeFlow FromDecilitersPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerMinute); } @@ -1109,7 +1091,7 @@ public static VolumeFlow FromDecilitersPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromDecilitersPerSecond(double value) + public static VolumeFlow FromDecilitersPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.DeciliterPerSecond); } @@ -1117,7 +1099,7 @@ public static VolumeFlow FromDecilitersPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromHectolitersPerDay(double value) + public static VolumeFlow FromHectolitersPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.HectoliterPerDay); } @@ -1125,7 +1107,7 @@ public static VolumeFlow FromHectolitersPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromHectolitersPerHour(double value) + public static VolumeFlow FromHectolitersPerHour(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.HectoliterPerHour); } @@ -1133,7 +1115,7 @@ public static VolumeFlow FromHectolitersPerHour(double value) /// /// Creates a from . /// - public static VolumeFlow FromHectolitersPerMinute(double value) + public static VolumeFlow FromHectolitersPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.HectoliterPerMinute); } @@ -1141,7 +1123,7 @@ public static VolumeFlow FromHectolitersPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromHectolitersPerSecond(double value) + public static VolumeFlow FromHectolitersPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.HectoliterPerSecond); } @@ -1149,7 +1131,7 @@ public static VolumeFlow FromHectolitersPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromKilolitersPerDay(double value) + public static VolumeFlow FromKilolitersPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerDay); } @@ -1157,7 +1139,7 @@ public static VolumeFlow FromKilolitersPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromKilolitersPerHour(double value) + public static VolumeFlow FromKilolitersPerHour(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerHour); } @@ -1165,7 +1147,7 @@ public static VolumeFlow FromKilolitersPerHour(double value) /// /// Creates a from . /// - public static VolumeFlow FromKilolitersPerMinute(double value) + public static VolumeFlow FromKilolitersPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerMinute); } @@ -1173,7 +1155,7 @@ public static VolumeFlow FromKilolitersPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromKilolitersPerSecond(double value) + public static VolumeFlow FromKilolitersPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.KiloliterPerSecond); } @@ -1181,7 +1163,7 @@ public static VolumeFlow FromKilolitersPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromKilousGallonsPerMinute(double value) + public static VolumeFlow FromKilousGallonsPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.KilousGallonPerMinute); } @@ -1189,7 +1171,7 @@ public static VolumeFlow FromKilousGallonsPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromLitersPerDay(double value) + public static VolumeFlow FromLitersPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.LiterPerDay); } @@ -1197,7 +1179,7 @@ public static VolumeFlow FromLitersPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromLitersPerHour(double value) + public static VolumeFlow FromLitersPerHour(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.LiterPerHour); } @@ -1205,7 +1187,7 @@ public static VolumeFlow FromLitersPerHour(double value) /// /// Creates a from . /// - public static VolumeFlow FromLitersPerMinute(double value) + public static VolumeFlow FromLitersPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.LiterPerMinute); } @@ -1213,7 +1195,7 @@ public static VolumeFlow FromLitersPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromLitersPerSecond(double value) + public static VolumeFlow FromLitersPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.LiterPerSecond); } @@ -1221,7 +1203,7 @@ public static VolumeFlow FromLitersPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromMegalitersPerDay(double value) + public static VolumeFlow FromMegalitersPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.MegaliterPerDay); } @@ -1229,7 +1211,7 @@ public static VolumeFlow FromMegalitersPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromMegalitersPerHour(double value) + public static VolumeFlow FromMegalitersPerHour(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.MegaliterPerHour); } @@ -1237,7 +1219,7 @@ public static VolumeFlow FromMegalitersPerHour(double value) /// /// Creates a from . /// - public static VolumeFlow FromMegalitersPerMinute(double value) + public static VolumeFlow FromMegalitersPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.MegaliterPerMinute); } @@ -1245,7 +1227,7 @@ public static VolumeFlow FromMegalitersPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromMegalitersPerSecond(double value) + public static VolumeFlow FromMegalitersPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.MegaliterPerSecond); } @@ -1253,7 +1235,7 @@ public static VolumeFlow FromMegalitersPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromMegaukGallonsPerDay(double value) + public static VolumeFlow FromMegaukGallonsPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.MegaukGallonPerDay); } @@ -1261,7 +1243,7 @@ public static VolumeFlow FromMegaukGallonsPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromMegaukGallonsPerSecond(double value) + public static VolumeFlow FromMegaukGallonsPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.MegaukGallonPerSecond); } @@ -1269,7 +1251,7 @@ public static VolumeFlow FromMegaukGallonsPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromMegausGallonsPerDay(double value) + public static VolumeFlow FromMegausGallonsPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.MegausGallonPerDay); } @@ -1277,7 +1259,7 @@ public static VolumeFlow FromMegausGallonsPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromMicrolitersPerDay(double value) + public static VolumeFlow FromMicrolitersPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerDay); } @@ -1285,7 +1267,7 @@ public static VolumeFlow FromMicrolitersPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromMicrolitersPerHour(double value) + public static VolumeFlow FromMicrolitersPerHour(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerHour); } @@ -1293,7 +1275,7 @@ public static VolumeFlow FromMicrolitersPerHour(double value) /// /// Creates a from . /// - public static VolumeFlow FromMicrolitersPerMinute(double value) + public static VolumeFlow FromMicrolitersPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerMinute); } @@ -1301,7 +1283,7 @@ public static VolumeFlow FromMicrolitersPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromMicrolitersPerSecond(double value) + public static VolumeFlow FromMicrolitersPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.MicroliterPerSecond); } @@ -1309,7 +1291,7 @@ public static VolumeFlow FromMicrolitersPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromMillilitersPerDay(double value) + public static VolumeFlow FromMillilitersPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerDay); } @@ -1317,7 +1299,7 @@ public static VolumeFlow FromMillilitersPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromMillilitersPerHour(double value) + public static VolumeFlow FromMillilitersPerHour(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerHour); } @@ -1325,7 +1307,7 @@ public static VolumeFlow FromMillilitersPerHour(double value) /// /// Creates a from . /// - public static VolumeFlow FromMillilitersPerMinute(double value) + public static VolumeFlow FromMillilitersPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerMinute); } @@ -1333,7 +1315,7 @@ public static VolumeFlow FromMillilitersPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromMillilitersPerSecond(double value) + public static VolumeFlow FromMillilitersPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.MilliliterPerSecond); } @@ -1341,7 +1323,7 @@ public static VolumeFlow FromMillilitersPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromMillionUsGallonsPerDay(double value) + public static VolumeFlow FromMillionUsGallonsPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.MillionUsGallonPerDay); } @@ -1349,7 +1331,7 @@ public static VolumeFlow FromMillionUsGallonsPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromNanolitersPerDay(double value) + public static VolumeFlow FromNanolitersPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerDay); } @@ -1357,7 +1339,7 @@ public static VolumeFlow FromNanolitersPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromNanolitersPerHour(double value) + public static VolumeFlow FromNanolitersPerHour(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerHour); } @@ -1365,7 +1347,7 @@ public static VolumeFlow FromNanolitersPerHour(double value) /// /// Creates a from . /// - public static VolumeFlow FromNanolitersPerMinute(double value) + public static VolumeFlow FromNanolitersPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerMinute); } @@ -1373,7 +1355,7 @@ public static VolumeFlow FromNanolitersPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromNanolitersPerSecond(double value) + public static VolumeFlow FromNanolitersPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.NanoliterPerSecond); } @@ -1381,7 +1363,7 @@ public static VolumeFlow FromNanolitersPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromOilBarrelsPerDay(double value) + public static VolumeFlow FromOilBarrelsPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerDay); } @@ -1389,7 +1371,7 @@ public static VolumeFlow FromOilBarrelsPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromOilBarrelsPerHour(double value) + public static VolumeFlow FromOilBarrelsPerHour(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerHour); } @@ -1397,7 +1379,7 @@ public static VolumeFlow FromOilBarrelsPerHour(double value) /// /// Creates a from . /// - public static VolumeFlow FromOilBarrelsPerMinute(double value) + public static VolumeFlow FromOilBarrelsPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerMinute); } @@ -1405,7 +1387,7 @@ public static VolumeFlow FromOilBarrelsPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromOilBarrelsPerSecond(double value) + public static VolumeFlow FromOilBarrelsPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.OilBarrelPerSecond); } @@ -1413,7 +1395,7 @@ public static VolumeFlow FromOilBarrelsPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromUkGallonsPerDay(double value) + public static VolumeFlow FromUkGallonsPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.UkGallonPerDay); } @@ -1421,7 +1403,7 @@ public static VolumeFlow FromUkGallonsPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromUkGallonsPerHour(double value) + public static VolumeFlow FromUkGallonsPerHour(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.UkGallonPerHour); } @@ -1429,7 +1411,7 @@ public static VolumeFlow FromUkGallonsPerHour(double value) /// /// Creates a from . /// - public static VolumeFlow FromUkGallonsPerMinute(double value) + public static VolumeFlow FromUkGallonsPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.UkGallonPerMinute); } @@ -1437,7 +1419,7 @@ public static VolumeFlow FromUkGallonsPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromUkGallonsPerSecond(double value) + public static VolumeFlow FromUkGallonsPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.UkGallonPerSecond); } @@ -1445,7 +1427,7 @@ public static VolumeFlow FromUkGallonsPerSecond(double value) /// /// Creates a from . /// - public static VolumeFlow FromUsGallonsPerDay(double value) + public static VolumeFlow FromUsGallonsPerDay(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerDay); } @@ -1453,7 +1435,7 @@ public static VolumeFlow FromUsGallonsPerDay(double value) /// /// Creates a from . /// - public static VolumeFlow FromUsGallonsPerHour(double value) + public static VolumeFlow FromUsGallonsPerHour(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerHour); } @@ -1461,7 +1443,7 @@ public static VolumeFlow FromUsGallonsPerHour(double value) /// /// Creates a from . /// - public static VolumeFlow FromUsGallonsPerMinute(double value) + public static VolumeFlow FromUsGallonsPerMinute(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerMinute); } @@ -1469,7 +1451,7 @@ public static VolumeFlow FromUsGallonsPerMinute(double value) /// /// Creates a from . /// - public static VolumeFlow FromUsGallonsPerSecond(double value) + public static VolumeFlow FromUsGallonsPerSecond(QuantityValue value) { return new VolumeFlow(value, VolumeFlowUnit.UsGallonPerSecond); } @@ -1480,7 +1462,7 @@ public static VolumeFlow FromUsGallonsPerSecond(double value) /// Value to convert from. /// Unit to convert from. /// VolumeFlow unit value. - public static VolumeFlow From(double value, VolumeFlowUnit fromUnit) + public static VolumeFlow From(QuantityValue value, VolumeFlowUnit fromUnit) { return new VolumeFlow(value, fromUnit); } @@ -1541,10 +1523,7 @@ public static VolumeFlow Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static VolumeFlow Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -1572,11 +1551,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out VolumeFlow resul /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out VolumeFlow result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -1597,7 +1572,7 @@ public static VolumeFlowUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -1608,7 +1583,7 @@ public static VolumeFlowUnit ParseUnit(string str, IFormatProvider? provider) return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out VolumeFlowUnit unit) { return TryParseUnit(str, null, out unit); @@ -1623,7 +1598,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out VolumeFlowUn /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out VolumeFlowUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -1642,35 +1617,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static VolumeFlow operator +(VolumeFlow left, VolumeFlow right) { - return new VolumeFlow(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new VolumeFlow(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static VolumeFlow operator -(VolumeFlow left, VolumeFlow right) { - return new VolumeFlow(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new VolumeFlow(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -1716,97 +1691,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(VolumeFlow left, VolumeFlow right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(VolumeFlow left, VolumeFlow right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(VolumeFlow left, VolumeFlow right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(VolumeFlow left, VolumeFlow right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(VolumeFlow other, VolumeFlow tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(VolumeFlow left, VolumeFlow right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(VolumeFlow other, VolumeFlow tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(VolumeFlow left, VolumeFlow right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(VolumeFlow other, VolumeFlow tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is VolumeFlow otherQuantity)) + if (obj is not VolumeFlow otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(VolumeFlow other, VolumeFlow tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(VolumeFlow other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current VolumeFlow. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(VolumeFlow), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is VolumeFlow otherQuantity)) throw new ArgumentException("Expected type VolumeFlow.", nameof(obj)); + if (obj is not VolumeFlow otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -1818,294 +1778,24 @@ public int CompareTo(object? obj) /// public int CompareTo(VolumeFlow other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumeFlowUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this VolumeFlow to another VolumeFlow with the unit representation . - /// - /// The unit to convert to. - /// A VolumeFlow with the specified unit. - public VolumeFlow ToUnit(VolumeFlowUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A VolumeFlow with the specified unit. - public VolumeFlow ToUnit(VolumeFlowUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(VolumeFlow), Unit, typeof(VolumeFlow), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (VolumeFlow)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(VolumeFlowUnit unit, [NotNullWhen(true)] out VolumeFlow? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - VolumeFlow? convertedOrNull = (Unit, unit) switch - { - // VolumeFlowUnit -> BaseUnit - (VolumeFlowUnit.AcreFootPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 1233.48183754752 / 86400, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.AcreFootPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 1233.48183754752 / 3600, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.AcreFootPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 1233.48183754752 / 60, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.AcreFootPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 1233.48183754752, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.CentiliterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 86400)) * 1e-2d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.CentiliterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 3600)) * 1e-2d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.CentiliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 60)) * 1e-2d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.CentiliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 1000) * 1e-2d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.CubicCentimeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 1e-6 / 60, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.CubicDecimeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 60000.00000, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.CubicFootPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.028316846592 / 3600, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.CubicFootPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.028316846592 / 60, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.CubicFootPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.028316846592, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.CubicMeterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 86400, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.CubicMeterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 3600, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.CubicMeterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 60, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.CubicMillimeterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 1e-9, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.CubicYardPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.764554857984 / 86400, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.CubicYardPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.764554857984 / 3600, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.CubicYardPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.764554857984 / 60, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.CubicYardPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.764554857984, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.DecaliterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 86400)) * 1e1d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.DecaliterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 3600)) * 1e1d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.DecaliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 60)) * 1e1d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.DecaliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 1000) * 1e1d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.DeciliterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 86400)) * 1e-1d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.DeciliterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 3600)) * 1e-1d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.DeciliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 60)) * 1e-1d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.DeciliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 1000) * 1e-1d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.HectoliterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 86400)) * 1e2d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.HectoliterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 3600)) * 1e2d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.HectoliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 60)) * 1e2d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.HectoliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 1000) * 1e2d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.KiloliterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 86400)) * 1e3d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.KiloliterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 3600)) * 1e3d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.KiloliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 60)) * 1e3d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.KiloliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 1000) * 1e3d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.KilousGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 1000 * 0.003785411784 / 60, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.LiterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / (1000 * 86400), VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.LiterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / (1000 * 3600), VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.LiterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / (1000 * 60), VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.LiterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value / 1000, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.MegaliterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 86400)) * 1e6d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.MegaliterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 3600)) * 1e6d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.MegaliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 60)) * 1e6d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.MegaliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 1000) * 1e6d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.MegaukGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value * 0.00454609 / 86400) * 1e6d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.MegaukGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value * 0.00454609) * 1e6d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.MegausGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value * 0.003785411784 / 86400) * 1e6d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.MicroliterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 86400)) * 1e-6d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.MicroliterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 3600)) * 1e-6d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.MicroliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 60)) * 1e-6d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.MicroliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 1000) * 1e-6d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.MilliliterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 86400)) * 1e-3d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.MilliliterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 3600)) * 1e-3d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.MilliliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 60)) * 1e-3d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.MilliliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 1000) * 1e-3d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.MillionUsGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 1e6 * 0.003785411784 / 86400, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.NanoliterPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 86400)) * 1e-9d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.NanoliterPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 3600)) * 1e-9d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.NanoliterPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / (1000 * 60)) * 1e-9d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.NanoliterPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow((_value / 1000) * 1e-9d, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.OilBarrelPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.158987294928 / 86400, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.OilBarrelPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.158987294928 / 3600, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.OilBarrelPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.158987294928 / 60, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.OilBarrelPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.158987294928, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.UkGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.00454609 / 86400, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.UkGallonPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.00454609 / 3600, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.UkGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.00454609 / 60, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.UkGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.00454609, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.UsGallonPerDay, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.003785411784 / 86400, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.UsGallonPerHour, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.003785411784 / 3600, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.UsGallonPerMinute, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.003785411784 / 60, VolumeFlowUnit.CubicMeterPerSecond), - (VolumeFlowUnit.UsGallonPerSecond, VolumeFlowUnit.CubicMeterPerSecond) => new VolumeFlow(_value * 0.003785411784, VolumeFlowUnit.CubicMeterPerSecond), - - // BaseUnit -> VolumeFlowUnit - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerDay) => new VolumeFlow(_value / (1233.48183754752 / 86400), VolumeFlowUnit.AcreFootPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerHour) => new VolumeFlow(_value / (1233.48183754752 / 3600), VolumeFlowUnit.AcreFootPerHour), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerMinute) => new VolumeFlow(_value / (1233.48183754752 / 60), VolumeFlowUnit.AcreFootPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.AcreFootPerSecond) => new VolumeFlow(_value / 1233.48183754752, VolumeFlowUnit.AcreFootPerSecond), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerDay) => new VolumeFlow((_value * (1000 * 86400)) / 1e-2d, VolumeFlowUnit.CentiliterPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerHour) => new VolumeFlow((_value * (1000 * 3600)) / 1e-2d, VolumeFlowUnit.CentiliterPerHour), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerMinute) => new VolumeFlow((_value * (1000 * 60)) / 1e-2d, VolumeFlowUnit.CentiliterPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CentiliterPerSecond) => new VolumeFlow((_value * 1000) / 1e-2d, VolumeFlowUnit.CentiliterPerSecond), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicCentimeterPerMinute) => new VolumeFlow(_value / (1e-6 / 60), VolumeFlowUnit.CubicCentimeterPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicDecimeterPerMinute) => new VolumeFlow(_value * 60000.00000, VolumeFlowUnit.CubicDecimeterPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerHour) => new VolumeFlow(_value / (0.028316846592 / 3600), VolumeFlowUnit.CubicFootPerHour), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerMinute) => new VolumeFlow(_value / (0.028316846592 / 60), VolumeFlowUnit.CubicFootPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicFootPerSecond) => new VolumeFlow(_value / 0.028316846592, VolumeFlowUnit.CubicFootPerSecond), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerDay) => new VolumeFlow(_value * 86400, VolumeFlowUnit.CubicMeterPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerHour) => new VolumeFlow(_value * 3600, VolumeFlowUnit.CubicMeterPerHour), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMeterPerMinute) => new VolumeFlow(_value * 60, VolumeFlowUnit.CubicMeterPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicMillimeterPerSecond) => new VolumeFlow(_value / 1e-9, VolumeFlowUnit.CubicMillimeterPerSecond), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerDay) => new VolumeFlow(_value / (0.764554857984 / 86400), VolumeFlowUnit.CubicYardPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerHour) => new VolumeFlow(_value / (0.764554857984 / 3600), VolumeFlowUnit.CubicYardPerHour), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerMinute) => new VolumeFlow(_value / (0.764554857984 / 60), VolumeFlowUnit.CubicYardPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.CubicYardPerSecond) => new VolumeFlow(_value / 0.764554857984, VolumeFlowUnit.CubicYardPerSecond), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DecaliterPerDay) => new VolumeFlow((_value * (1000 * 86400)) / 1e1d, VolumeFlowUnit.DecaliterPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DecaliterPerHour) => new VolumeFlow((_value * (1000 * 3600)) / 1e1d, VolumeFlowUnit.DecaliterPerHour), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DecaliterPerMinute) => new VolumeFlow((_value * (1000 * 60)) / 1e1d, VolumeFlowUnit.DecaliterPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DecaliterPerSecond) => new VolumeFlow((_value * 1000) / 1e1d, VolumeFlowUnit.DecaliterPerSecond), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerDay) => new VolumeFlow((_value * (1000 * 86400)) / 1e-1d, VolumeFlowUnit.DeciliterPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerHour) => new VolumeFlow((_value * (1000 * 3600)) / 1e-1d, VolumeFlowUnit.DeciliterPerHour), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerMinute) => new VolumeFlow((_value * (1000 * 60)) / 1e-1d, VolumeFlowUnit.DeciliterPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.DeciliterPerSecond) => new VolumeFlow((_value * 1000) / 1e-1d, VolumeFlowUnit.DeciliterPerSecond), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.HectoliterPerDay) => new VolumeFlow((_value * (1000 * 86400)) / 1e2d, VolumeFlowUnit.HectoliterPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.HectoliterPerHour) => new VolumeFlow((_value * (1000 * 3600)) / 1e2d, VolumeFlowUnit.HectoliterPerHour), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.HectoliterPerMinute) => new VolumeFlow((_value * (1000 * 60)) / 1e2d, VolumeFlowUnit.HectoliterPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.HectoliterPerSecond) => new VolumeFlow((_value * 1000) / 1e2d, VolumeFlowUnit.HectoliterPerSecond), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerDay) => new VolumeFlow((_value * (1000 * 86400)) / 1e3d, VolumeFlowUnit.KiloliterPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerHour) => new VolumeFlow((_value * (1000 * 3600)) / 1e3d, VolumeFlowUnit.KiloliterPerHour), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerMinute) => new VolumeFlow((_value * (1000 * 60)) / 1e3d, VolumeFlowUnit.KiloliterPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KiloliterPerSecond) => new VolumeFlow((_value * 1000) / 1e3d, VolumeFlowUnit.KiloliterPerSecond), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.KilousGallonPerMinute) => new VolumeFlow(_value / (1000 * 0.003785411784 / 60), VolumeFlowUnit.KilousGallonPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerDay) => new VolumeFlow(_value * (1000 * 86400), VolumeFlowUnit.LiterPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerHour) => new VolumeFlow(_value * (1000 * 3600), VolumeFlowUnit.LiterPerHour), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerMinute) => new VolumeFlow(_value * (1000 * 60), VolumeFlowUnit.LiterPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.LiterPerSecond) => new VolumeFlow(_value * 1000, VolumeFlowUnit.LiterPerSecond), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaliterPerDay) => new VolumeFlow((_value * (1000 * 86400)) / 1e6d, VolumeFlowUnit.MegaliterPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaliterPerHour) => new VolumeFlow((_value * (1000 * 3600)) / 1e6d, VolumeFlowUnit.MegaliterPerHour), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaliterPerMinute) => new VolumeFlow((_value * (1000 * 60)) / 1e6d, VolumeFlowUnit.MegaliterPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaliterPerSecond) => new VolumeFlow((_value * 1000) / 1e6d, VolumeFlowUnit.MegaliterPerSecond), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaukGallonPerDay) => new VolumeFlow((_value / (0.00454609 / 86400)) / 1e6d, VolumeFlowUnit.MegaukGallonPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegaukGallonPerSecond) => new VolumeFlow((_value / 0.00454609) / 1e6d, VolumeFlowUnit.MegaukGallonPerSecond), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MegausGallonPerDay) => new VolumeFlow((_value / (0.003785411784 / 86400)) / 1e6d, VolumeFlowUnit.MegausGallonPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerDay) => new VolumeFlow((_value * (1000 * 86400)) / 1e-6d, VolumeFlowUnit.MicroliterPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerHour) => new VolumeFlow((_value * (1000 * 3600)) / 1e-6d, VolumeFlowUnit.MicroliterPerHour), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerMinute) => new VolumeFlow((_value * (1000 * 60)) / 1e-6d, VolumeFlowUnit.MicroliterPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MicroliterPerSecond) => new VolumeFlow((_value * 1000) / 1e-6d, VolumeFlowUnit.MicroliterPerSecond), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerDay) => new VolumeFlow((_value * (1000 * 86400)) / 1e-3d, VolumeFlowUnit.MilliliterPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerHour) => new VolumeFlow((_value * (1000 * 3600)) / 1e-3d, VolumeFlowUnit.MilliliterPerHour), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerMinute) => new VolumeFlow((_value * (1000 * 60)) / 1e-3d, VolumeFlowUnit.MilliliterPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MilliliterPerSecond) => new VolumeFlow((_value * 1000) / 1e-3d, VolumeFlowUnit.MilliliterPerSecond), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.MillionUsGallonPerDay) => new VolumeFlow(_value / (1e6 * 0.003785411784 / 86400), VolumeFlowUnit.MillionUsGallonPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerDay) => new VolumeFlow((_value * (1000 * 86400)) / 1e-9d, VolumeFlowUnit.NanoliterPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerHour) => new VolumeFlow((_value * (1000 * 3600)) / 1e-9d, VolumeFlowUnit.NanoliterPerHour), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerMinute) => new VolumeFlow((_value * (1000 * 60)) / 1e-9d, VolumeFlowUnit.NanoliterPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.NanoliterPerSecond) => new VolumeFlow((_value * 1000) / 1e-9d, VolumeFlowUnit.NanoliterPerSecond), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerDay) => new VolumeFlow(_value / (0.158987294928 / 86400), VolumeFlowUnit.OilBarrelPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerHour) => new VolumeFlow(_value / (0.158987294928 / 3600), VolumeFlowUnit.OilBarrelPerHour), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerMinute) => new VolumeFlow(_value / (0.158987294928 / 60), VolumeFlowUnit.OilBarrelPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.OilBarrelPerSecond) => new VolumeFlow(_value / 0.158987294928, VolumeFlowUnit.OilBarrelPerSecond), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerDay) => new VolumeFlow(_value / (0.00454609 / 86400), VolumeFlowUnit.UkGallonPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerHour) => new VolumeFlow(_value / (0.00454609 / 3600), VolumeFlowUnit.UkGallonPerHour), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerMinute) => new VolumeFlow(_value / (0.00454609 / 60), VolumeFlowUnit.UkGallonPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UkGallonPerSecond) => new VolumeFlow(_value / 0.00454609, VolumeFlowUnit.UkGallonPerSecond), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerDay) => new VolumeFlow(_value / (0.003785411784 / 86400), VolumeFlowUnit.UsGallonPerDay), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerHour) => new VolumeFlow(_value / (0.003785411784 / 3600), VolumeFlowUnit.UsGallonPerHour), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerMinute) => new VolumeFlow(_value / (0.003785411784 / 60), VolumeFlowUnit.UsGallonPerMinute), - (VolumeFlowUnit.CubicMeterPerSecond, VolumeFlowUnit.UsGallonPerSecond) => new VolumeFlow(_value / 0.003785411784, VolumeFlowUnit.UsGallonPerSecond), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public VolumeFlow ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not VolumeFlowUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeFlowUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(VolumeFlowUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(VolumeFlowUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -2120,7 +1810,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs index 3631b331ce..277087aa65 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumeFlowPerArea.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct VolumeFlowPerArea : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly VolumeFlowPerAreaUnit? _unit; /// @@ -101,7 +100,7 @@ public static VolumeFlowPerAreaInfo CreateDefault(Func - /// The for is [T^-1][L]. + /// The for is T^-1L. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(1, 0, -1, 0, 0, 0, 0); @@ -116,16 +115,16 @@ public static VolumeFlowPerAreaInfo CreateDefault(FuncAn of representing the default unit mappings for VolumeFlowPerArea. public static IEnumerable> GetDefaultMappings() { - yield return new (VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, "CubicFootPerMinutePerSquareFoot", "CubicFeetPerMinutePerSquareFoot", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Minute)); + yield return new (VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, "CubicFootPerMinutePerSquareFoot", "CubicFeetPerMinutePerSquareFoot", new BaseUnits(length: LengthUnit.Foot, time: DurationUnit.Minute), + new QuantityValue(25000, 127) + ); yield return new (VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, "CubicMeterPerSecondPerSquareMeter", "CubicMetersPerSecondPerSquareMeter", new BaseUnits(length: LengthUnit.Meter, time: DurationUnit.Second)); } } static VolumeFlowPerArea() { - Info = VolumeFlowPerAreaInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(VolumeFlowPerAreaInfo.CreateDefault); } /// @@ -133,7 +132,7 @@ static VolumeFlowPerArea() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public VolumeFlowPerArea(double value, VolumeFlowPerAreaUnit unit) + public VolumeFlowPerArea(QuantityValue value, VolumeFlowPerAreaUnit unit) { _value = value; _unit = unit; @@ -147,7 +146,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -158,7 +157,8 @@ public VolumeFlowPerArea(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -187,10 +187,8 @@ public VolumeFlowPerArea(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public VolumeFlowPerAreaUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -229,35 +227,19 @@ public VolumeFlowPerArea(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicFeetPerMinutePerSquareFoot => As(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot); + public QuantityValue CubicFeetPerMinutePerSquareFoot => this.As(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicMetersPerSecondPerSquareMeter => As(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter); + public QuantityValue CubicMetersPerSecondPerSquareMeter => this.As(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: VolumeFlowPerAreaUnit -> BaseUnit - unitConverter.SetConversionFunction(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, quantity => quantity.ToUnit(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> VolumeFlowPerAreaUnit - unitConverter.SetConversionFunction(VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, quantity => quantity.ToUnit(VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot)); - } - /// /// Get unit abbreviation string. /// @@ -286,7 +268,7 @@ public static string GetAbbreviation(VolumeFlowPerAreaUnit unit, IFormatProvider /// /// Creates a from . /// - public static VolumeFlowPerArea FromCubicFeetPerMinutePerSquareFoot(double value) + public static VolumeFlowPerArea FromCubicFeetPerMinutePerSquareFoot(QuantityValue value) { return new VolumeFlowPerArea(value, VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot); } @@ -294,7 +276,7 @@ public static VolumeFlowPerArea FromCubicFeetPerMinutePerSquareFoot(double value /// /// Creates a from . /// - public static VolumeFlowPerArea FromCubicMetersPerSecondPerSquareMeter(double value) + public static VolumeFlowPerArea FromCubicMetersPerSecondPerSquareMeter(QuantityValue value) { return new VolumeFlowPerArea(value, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter); } @@ -305,7 +287,7 @@ public static VolumeFlowPerArea FromCubicMetersPerSecondPerSquareMeter(double va /// Value to convert from. /// Unit to convert from. /// VolumeFlowPerArea unit value. - public static VolumeFlowPerArea From(double value, VolumeFlowPerAreaUnit fromUnit) + public static VolumeFlowPerArea From(QuantityValue value, VolumeFlowPerAreaUnit fromUnit) { return new VolumeFlowPerArea(value, fromUnit); } @@ -366,10 +348,7 @@ public static VolumeFlowPerArea Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static VolumeFlowPerArea Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -397,11 +376,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out VolumeFlowPerAre /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out VolumeFlowPerArea result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -422,7 +397,7 @@ public static VolumeFlowPerAreaUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -433,7 +408,7 @@ public static VolumeFlowPerAreaUnit ParseUnit(string str, IFormatProvider? provi return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out VolumeFlowPerAreaUnit unit) { return TryParseUnit(str, null, out unit); @@ -448,7 +423,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out VolumeFlowPe /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out VolumeFlowPerAreaUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -467,35 +442,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static VolumeFlowPerArea operator +(VolumeFlowPerArea left, VolumeFlowPerArea right) { - return new VolumeFlowPerArea(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new VolumeFlowPerArea(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static VolumeFlowPerArea operator -(VolumeFlowPerArea left, VolumeFlowPerArea right) { - return new VolumeFlowPerArea(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new VolumeFlowPerArea(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -507,97 +482,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(VolumeFlowPerArea left, VolumeFlowPerArea right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(VolumeFlowPerArea left, VolumeFlowPerArea right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(VolumeFlowPerArea left, VolumeFlowPerArea right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(VolumeFlowPerArea left, VolumeFlowPerArea right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(VolumeFlowPerArea other, VolumeFlowPerArea tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(VolumeFlowPerArea left, VolumeFlowPerArea right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(VolumeFlowPerArea other, VolumeFlowPerArea tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(VolumeFlowPerArea left, VolumeFlowPerArea right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(VolumeFlowPerArea other, VolumeFlowPerArea tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is VolumeFlowPerArea otherQuantity)) + if (obj is not VolumeFlowPerArea otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(VolumeFlowPerArea other, VolumeFlowPerArea tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(VolumeFlowPerArea other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current VolumeFlowPerArea. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(VolumeFlowPerArea), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is VolumeFlowPerArea otherQuantity)) throw new ArgumentException("Expected type VolumeFlowPerArea.", nameof(obj)); + if (obj is not VolumeFlowPerArea otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -609,148 +569,24 @@ public int CompareTo(object? obj) /// public int CompareTo(VolumeFlowPerArea other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumeFlowPerAreaUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } - - /// - /// Converts this VolumeFlowPerArea to another VolumeFlowPerArea with the unit representation . - /// - /// The unit to convert to. - /// A VolumeFlowPerArea with the specified unit. - public VolumeFlowPerArea ToUnit(VolumeFlowPerAreaUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A VolumeFlowPerArea with the specified unit. - public VolumeFlowPerArea ToUnit(VolumeFlowPerAreaUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(VolumeFlowPerArea), Unit, typeof(VolumeFlowPerArea), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (VolumeFlowPerArea)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(VolumeFlowPerAreaUnit unit, [NotNullWhen(true)] out VolumeFlowPerArea? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - VolumeFlowPerArea? convertedOrNull = (Unit, unit) switch - { - // VolumeFlowPerAreaUnit -> BaseUnit - (VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter) => new VolumeFlowPerArea(_value * (0.028316846592 / 60) / 9.290304e-2, VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter), + #region Conversion Methods (explicit implementations for netstandard2.0) - // BaseUnit -> VolumeFlowPerAreaUnit - (VolumeFlowPerAreaUnit.CubicMeterPerSecondPerSquareMeter, VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot) => new VolumeFlowPerArea(_value * 9.290304e-2 / (0.028316846592 / 60), VolumeFlowPerAreaUnit.CubicFootPerMinutePerSquareFoot), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public VolumeFlowPerArea ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not VolumeFlowPerAreaUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeFlowPerAreaUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - if (!(unit is VolumeFlowPerAreaUnit typedUnit)) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumeFlowPerAreaUnit)} is supported.", nameof(unit)); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - return ToUnit(typedUnit, DefaultConversionFunctions); - } + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(VolumeFlowPerAreaUnit unit) => this.ToUnit(unit); - /// - IQuantity IQuantity.ToUnit(VolumeFlowPerAreaUnit unit) => ToUnit(unit); - - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); - - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -765,7 +601,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs index f167382e54..70527ca047 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumePerLength.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// Volume, typically of fluid, that a container can hold within a unit of length. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct VolumePerLength : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly VolumePerLengthUnit? _unit; /// @@ -101,7 +100,7 @@ public static VolumePerLengthInfo CreateDefault(Func - /// The for is [L^2]. + /// The for is L^2. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(2, 0, 0, 0, 0, 0, 0); @@ -117,22 +116,36 @@ public static VolumePerLengthInfo CreateDefault(Func> GetDefaultMappings() { yield return new (VolumePerLengthUnit.CubicMeterPerMeter, "CubicMeterPerMeter", "CubicMetersPerMeter", new BaseUnits(length: LengthUnit.Meter)); - yield return new (VolumePerLengthUnit.CubicYardPerFoot, "CubicYardPerFoot", "CubicYardsPerFoot", BaseUnits.Undefined); - yield return new (VolumePerLengthUnit.CubicYardPerUsSurveyFoot, "CubicYardPerUsSurveyFoot", "CubicYardsPerUsSurveyFoot", BaseUnits.Undefined); - yield return new (VolumePerLengthUnit.ImperialGallonPerMile, "ImperialGallonPerMile", "ImperialGallonsPerMile", BaseUnits.Undefined); - yield return new (VolumePerLengthUnit.LiterPerKilometer, "LiterPerKilometer", "LitersPerKilometer", BaseUnits.Undefined); - yield return new (VolumePerLengthUnit.LiterPerMeter, "LiterPerMeter", "LitersPerMeter", new BaseUnits(length: LengthUnit.Decimeter)); - yield return new (VolumePerLengthUnit.LiterPerMillimeter, "LiterPerMillimeter", "LitersPerMillimeter", BaseUnits.Undefined); - yield return new (VolumePerLengthUnit.OilBarrelPerFoot, "OilBarrelPerFoot", "OilBarrelsPerFoot", BaseUnits.Undefined); - yield return new (VolumePerLengthUnit.UsGallonPerMile, "UsGallonPerMile", "UsGallonsPerMile", BaseUnits.Undefined); + yield return new (VolumePerLengthUnit.CubicYardPerFoot, "CubicYardPerFoot", "CubicYardsPerFoot", BaseUnits.Undefined, + new QuantityValue(1562500, 3919347) + ); + yield return new (VolumePerLengthUnit.CubicYardPerUsSurveyFoot, "CubicYardPerUsSurveyFoot", "CubicYardsPerUsSurveyFoot", BaseUnits.Undefined, + new QuantityValue(781250000000, 1959669580653) + ); + yield return new (VolumePerLengthUnit.ImperialGallonPerMile, "ImperialGallonPerMile", "ImperialGallonsPerMile", BaseUnits.Undefined, + new QuantityValue(160934400000, 454609) + ); + yield return new (VolumePerLengthUnit.LiterPerKilometer, "LiterPerKilometer", "LitersPerKilometer", BaseUnits.Undefined, + 1000000 + ); + yield return new (VolumePerLengthUnit.LiterPerMeter, "LiterPerMeter", "LitersPerMeter", new BaseUnits(length: LengthUnit.Decimeter), + 1000 + ); + yield return new (VolumePerLengthUnit.LiterPerMillimeter, "LiterPerMillimeter", "LitersPerMillimeter", BaseUnits.Undefined, + 1 + ); + yield return new (VolumePerLengthUnit.OilBarrelPerFoot, "OilBarrelPerFoot", "OilBarrelsPerFoot", BaseUnits.Undefined, + new QuantityValue(50000000, 26080593) + ); + yield return new (VolumePerLengthUnit.UsGallonPerMile, "UsGallonPerMile", "UsGallonsPerMile", BaseUnits.Undefined, + new QuantityValue(48000000000, 112903) + ); } } static VolumePerLength() { - Info = VolumePerLengthInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(VolumePerLengthInfo.CreateDefault); } /// @@ -140,7 +153,7 @@ static VolumePerLength() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public VolumePerLength(double value, VolumePerLengthUnit unit) + public VolumePerLength(QuantityValue value, VolumePerLengthUnit unit) { _value = value; _unit = unit; @@ -154,7 +167,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -165,7 +178,8 @@ public VolumePerLength(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -194,10 +208,8 @@ public VolumePerLength(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public VolumePerLengthUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -236,84 +248,54 @@ public VolumePerLength(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicMetersPerMeter => As(VolumePerLengthUnit.CubicMeterPerMeter); + public QuantityValue CubicMetersPerMeter => this.As(VolumePerLengthUnit.CubicMeterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicYardsPerFoot => As(VolumePerLengthUnit.CubicYardPerFoot); + public QuantityValue CubicYardsPerFoot => this.As(VolumePerLengthUnit.CubicYardPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CubicYardsPerUsSurveyFoot => As(VolumePerLengthUnit.CubicYardPerUsSurveyFoot); + public QuantityValue CubicYardsPerUsSurveyFoot => this.As(VolumePerLengthUnit.CubicYardPerUsSurveyFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double ImperialGallonsPerMile => As(VolumePerLengthUnit.ImperialGallonPerMile); + public QuantityValue ImperialGallonsPerMile => this.As(VolumePerLengthUnit.ImperialGallonPerMile); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double LitersPerKilometer => As(VolumePerLengthUnit.LiterPerKilometer); + public QuantityValue LitersPerKilometer => this.As(VolumePerLengthUnit.LiterPerKilometer); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double LitersPerMeter => As(VolumePerLengthUnit.LiterPerMeter); + public QuantityValue LitersPerMeter => this.As(VolumePerLengthUnit.LiterPerMeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double LitersPerMillimeter => As(VolumePerLengthUnit.LiterPerMillimeter); + public QuantityValue LitersPerMillimeter => this.As(VolumePerLengthUnit.LiterPerMillimeter); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double OilBarrelsPerFoot => As(VolumePerLengthUnit.OilBarrelPerFoot); + public QuantityValue OilBarrelsPerFoot => this.As(VolumePerLengthUnit.OilBarrelPerFoot); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double UsGallonsPerMile => As(VolumePerLengthUnit.UsGallonPerMile); + public QuantityValue UsGallonsPerMile => this.As(VolumePerLengthUnit.UsGallonPerMile); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: VolumePerLengthUnit -> BaseUnit - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicYardPerFoot, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicMeterPerMeter)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicYardPerUsSurveyFoot, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicMeterPerMeter)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.ImperialGallonPerMile, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicMeterPerMeter)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.LiterPerKilometer, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicMeterPerMeter)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.LiterPerMeter, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicMeterPerMeter)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.LiterPerMillimeter, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicMeterPerMeter)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.OilBarrelPerFoot, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicMeterPerMeter)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.UsGallonPerMile, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicMeterPerMeter)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.CubicMeterPerMeter, quantity => quantity); - - // Register in unit converter: BaseUnit -> VolumePerLengthUnit - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.CubicYardPerFoot, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicYardPerFoot)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.CubicYardPerUsSurveyFoot, quantity => quantity.ToUnit(VolumePerLengthUnit.CubicYardPerUsSurveyFoot)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.ImperialGallonPerMile, quantity => quantity.ToUnit(VolumePerLengthUnit.ImperialGallonPerMile)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerKilometer, quantity => quantity.ToUnit(VolumePerLengthUnit.LiterPerKilometer)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerMeter, quantity => quantity.ToUnit(VolumePerLengthUnit.LiterPerMeter)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerMillimeter, quantity => quantity.ToUnit(VolumePerLengthUnit.LiterPerMillimeter)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.OilBarrelPerFoot, quantity => quantity.ToUnit(VolumePerLengthUnit.OilBarrelPerFoot)); - unitConverter.SetConversionFunction(VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.UsGallonPerMile, quantity => quantity.ToUnit(VolumePerLengthUnit.UsGallonPerMile)); - } - /// /// Get unit abbreviation string. /// @@ -342,7 +324,7 @@ public static string GetAbbreviation(VolumePerLengthUnit unit, IFormatProvider? /// /// Creates a from . /// - public static VolumePerLength FromCubicMetersPerMeter(double value) + public static VolumePerLength FromCubicMetersPerMeter(QuantityValue value) { return new VolumePerLength(value, VolumePerLengthUnit.CubicMeterPerMeter); } @@ -350,7 +332,7 @@ public static VolumePerLength FromCubicMetersPerMeter(double value) /// /// Creates a from . /// - public static VolumePerLength FromCubicYardsPerFoot(double value) + public static VolumePerLength FromCubicYardsPerFoot(QuantityValue value) { return new VolumePerLength(value, VolumePerLengthUnit.CubicYardPerFoot); } @@ -358,7 +340,7 @@ public static VolumePerLength FromCubicYardsPerFoot(double value) /// /// Creates a from . /// - public static VolumePerLength FromCubicYardsPerUsSurveyFoot(double value) + public static VolumePerLength FromCubicYardsPerUsSurveyFoot(QuantityValue value) { return new VolumePerLength(value, VolumePerLengthUnit.CubicYardPerUsSurveyFoot); } @@ -366,7 +348,7 @@ public static VolumePerLength FromCubicYardsPerUsSurveyFoot(double value) /// /// Creates a from . /// - public static VolumePerLength FromImperialGallonsPerMile(double value) + public static VolumePerLength FromImperialGallonsPerMile(QuantityValue value) { return new VolumePerLength(value, VolumePerLengthUnit.ImperialGallonPerMile); } @@ -374,7 +356,7 @@ public static VolumePerLength FromImperialGallonsPerMile(double value) /// /// Creates a from . /// - public static VolumePerLength FromLitersPerKilometer(double value) + public static VolumePerLength FromLitersPerKilometer(QuantityValue value) { return new VolumePerLength(value, VolumePerLengthUnit.LiterPerKilometer); } @@ -382,7 +364,7 @@ public static VolumePerLength FromLitersPerKilometer(double value) /// /// Creates a from . /// - public static VolumePerLength FromLitersPerMeter(double value) + public static VolumePerLength FromLitersPerMeter(QuantityValue value) { return new VolumePerLength(value, VolumePerLengthUnit.LiterPerMeter); } @@ -390,7 +372,7 @@ public static VolumePerLength FromLitersPerMeter(double value) /// /// Creates a from . /// - public static VolumePerLength FromLitersPerMillimeter(double value) + public static VolumePerLength FromLitersPerMillimeter(QuantityValue value) { return new VolumePerLength(value, VolumePerLengthUnit.LiterPerMillimeter); } @@ -398,7 +380,7 @@ public static VolumePerLength FromLitersPerMillimeter(double value) /// /// Creates a from . /// - public static VolumePerLength FromOilBarrelsPerFoot(double value) + public static VolumePerLength FromOilBarrelsPerFoot(QuantityValue value) { return new VolumePerLength(value, VolumePerLengthUnit.OilBarrelPerFoot); } @@ -406,7 +388,7 @@ public static VolumePerLength FromOilBarrelsPerFoot(double value) /// /// Creates a from . /// - public static VolumePerLength FromUsGallonsPerMile(double value) + public static VolumePerLength FromUsGallonsPerMile(QuantityValue value) { return new VolumePerLength(value, VolumePerLengthUnit.UsGallonPerMile); } @@ -417,7 +399,7 @@ public static VolumePerLength FromUsGallonsPerMile(double value) /// Value to convert from. /// Unit to convert from. /// VolumePerLength unit value. - public static VolumePerLength From(double value, VolumePerLengthUnit fromUnit) + public static VolumePerLength From(QuantityValue value, VolumePerLengthUnit fromUnit) { return new VolumePerLength(value, fromUnit); } @@ -478,10 +460,7 @@ public static VolumePerLength Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static VolumePerLength Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -509,11 +488,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out VolumePerLength /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out VolumePerLength result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -534,7 +509,7 @@ public static VolumePerLengthUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -545,7 +520,7 @@ public static VolumePerLengthUnit ParseUnit(string str, IFormatProvider? provide return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out VolumePerLengthUnit unit) { return TryParseUnit(str, null, out unit); @@ -560,7 +535,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out VolumePerLen /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out VolumePerLengthUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -579,35 +554,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static VolumePerLength operator +(VolumePerLength left, VolumePerLength right) { - return new VolumePerLength(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new VolumePerLength(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static VolumePerLength operator -(VolumePerLength left, VolumePerLength right) { - return new VolumePerLength(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new VolumePerLength(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -619,97 +594,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(VolumePerLength left, VolumePerLength right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(VolumePerLength left, VolumePerLength right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(VolumePerLength left, VolumePerLength right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(VolumePerLength left, VolumePerLength right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(VolumePerLength other, VolumePerLength tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(VolumePerLength left, VolumePerLength right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(VolumePerLength other, VolumePerLength tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(VolumePerLength left, VolumePerLength right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(VolumePerLength other, VolumePerLength tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is VolumePerLength otherQuantity)) + if (obj is not VolumePerLength otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(VolumePerLength other, VolumePerLength tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(VolumePerLength other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current VolumePerLength. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(VolumePerLength), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is VolumePerLength otherQuantity)) throw new ArgumentException("Expected type VolumePerLength.", nameof(obj)); + if (obj is not VolumePerLength otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -721,162 +681,24 @@ public int CompareTo(object? obj) /// public int CompareTo(VolumePerLength other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumePerLengthUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this VolumePerLength to another VolumePerLength with the unit representation . - /// - /// The unit to convert to. - /// A VolumePerLength with the specified unit. - public VolumePerLength ToUnit(VolumePerLengthUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A VolumePerLength with the specified unit. - public VolumePerLength ToUnit(VolumePerLengthUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(VolumePerLength), Unit, typeof(VolumePerLength), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (VolumePerLength)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(VolumePerLengthUnit unit, [NotNullWhen(true)] out VolumePerLength? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - VolumePerLength? convertedOrNull = (Unit, unit) switch - { - // VolumePerLengthUnit -> BaseUnit - (VolumePerLengthUnit.CubicYardPerFoot, VolumePerLengthUnit.CubicMeterPerMeter) => new VolumePerLength(_value * 0.764554857984 / 0.3048, VolumePerLengthUnit.CubicMeterPerMeter), - (VolumePerLengthUnit.CubicYardPerUsSurveyFoot, VolumePerLengthUnit.CubicMeterPerMeter) => new VolumePerLength(_value * 0.764554857984 * 3937 / 1200, VolumePerLengthUnit.CubicMeterPerMeter), - (VolumePerLengthUnit.ImperialGallonPerMile, VolumePerLengthUnit.CubicMeterPerMeter) => new VolumePerLength(_value * 0.00454609 / 1609.344, VolumePerLengthUnit.CubicMeterPerMeter), - (VolumePerLengthUnit.LiterPerKilometer, VolumePerLengthUnit.CubicMeterPerMeter) => new VolumePerLength(_value / 1e6, VolumePerLengthUnit.CubicMeterPerMeter), - (VolumePerLengthUnit.LiterPerMeter, VolumePerLengthUnit.CubicMeterPerMeter) => new VolumePerLength(_value / 1000, VolumePerLengthUnit.CubicMeterPerMeter), - (VolumePerLengthUnit.LiterPerMillimeter, VolumePerLengthUnit.CubicMeterPerMeter) => new VolumePerLength(_value, VolumePerLengthUnit.CubicMeterPerMeter), - (VolumePerLengthUnit.OilBarrelPerFoot, VolumePerLengthUnit.CubicMeterPerMeter) => new VolumePerLength(_value * 0.158987294928 / 0.3048, VolumePerLengthUnit.CubicMeterPerMeter), - (VolumePerLengthUnit.UsGallonPerMile, VolumePerLengthUnit.CubicMeterPerMeter) => new VolumePerLength(_value * 0.003785411784 / 1609.344, VolumePerLengthUnit.CubicMeterPerMeter), - - // BaseUnit -> VolumePerLengthUnit - (VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.CubicYardPerFoot) => new VolumePerLength(_value * 0.3048 / 0.764554857984, VolumePerLengthUnit.CubicYardPerFoot), - (VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.CubicYardPerUsSurveyFoot) => new VolumePerLength(_value * 1200 / (0.764554857984 * 3937), VolumePerLengthUnit.CubicYardPerUsSurveyFoot), - (VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.ImperialGallonPerMile) => new VolumePerLength(_value * 1609.344 / 0.00454609, VolumePerLengthUnit.ImperialGallonPerMile), - (VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerKilometer) => new VolumePerLength(_value * 1e6, VolumePerLengthUnit.LiterPerKilometer), - (VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerMeter) => new VolumePerLength(_value * 1000, VolumePerLengthUnit.LiterPerMeter), - (VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.LiterPerMillimeter) => new VolumePerLength(_value, VolumePerLengthUnit.LiterPerMillimeter), - (VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.OilBarrelPerFoot) => new VolumePerLength(_value * 0.3048 / 0.158987294928, VolumePerLengthUnit.OilBarrelPerFoot), - (VolumePerLengthUnit.CubicMeterPerMeter, VolumePerLengthUnit.UsGallonPerMile) => new VolumePerLength(_value * 1609.344 / 0.003785411784, VolumePerLengthUnit.UsGallonPerMile), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public VolumePerLength ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not VolumePerLengthUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumePerLengthUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(VolumePerLengthUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(VolumePerLengthUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -891,7 +713,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs b/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs index 56184e2c08..71897ff902 100644 --- a/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/VolumetricHeatCapacity.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -38,7 +36,8 @@ namespace UnitsNet /// https://en.wikipedia.org/wiki/Volumetric_heat_capacity /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct VolumetricHeatCapacity : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -53,13 +52,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly VolumetricHeatCapacityUnit? _unit; /// @@ -104,7 +103,7 @@ public static VolumetricHeatCapacityInfo CreateDefault(Func - /// The for is [T^-2][L^-1][M][Θ^-1]. + /// The for is T^-2L^-1MΘ^-1. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(-1, 1, -2, 0, -1, 0, 0); @@ -119,23 +118,37 @@ public static VolumetricHeatCapacityInfo CreateDefault(FuncAn of representing the default unit mappings for VolumetricHeatCapacity. public static IEnumerable> GetDefaultMappings() { - yield return new (VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, "BtuPerCubicFootDegreeFahrenheit", "BtusPerCubicFootDegreeFahrenheit", BaseUnits.Undefined); - yield return new (VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, "CaloriePerCubicCentimeterDegreeCelsius", "CaloriesPerCubicCentimeterDegreeCelsius", BaseUnits.Undefined); - yield return new (VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, "JoulePerCubicMeterDegreeCelsius", "JoulesPerCubicMeterDegreeCelsius", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius)); + yield return new (VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, "BtuPerCubicFootDegreeFahrenheit", "BtusPerCubicFootDegreeFahrenheit", BaseUnits.Undefined, + new QuantityValue(98322384, 6594099078875) + ); + yield return new (VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, "CaloriePerCubicCentimeterDegreeCelsius", "CaloriesPerCubicCentimeterDegreeCelsius", BaseUnits.Undefined, + new QuantityValue(1, 4184000) + ); + yield return new (VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, "JoulePerCubicMeterDegreeCelsius", "JoulesPerCubicMeterDegreeCelsius", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), + 1 + ); yield return new (VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, "JoulePerCubicMeterKelvin", "JoulesPerCubicMeterKelvin", new BaseUnits(length: LengthUnit.Meter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin)); - yield return new (VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, "KilocaloriePerCubicCentimeterDegreeCelsius", "KilocaloriesPerCubicCentimeterDegreeCelsius", BaseUnits.Undefined); - yield return new (VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, "KilojoulePerCubicMeterDegreeCelsius", "KilojoulesPerCubicMeterDegreeCelsius", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius)); - yield return new (VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, "KilojoulePerCubicMeterKelvin", "KilojoulesPerCubicMeterKelvin", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin)); - yield return new (VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, "MegajoulePerCubicMeterDegreeCelsius", "MegajoulesPerCubicMeterDegreeCelsius", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius)); - yield return new (VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, "MegajoulePerCubicMeterKelvin", "MegajoulesPerCubicMeterKelvin", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin)); + yield return new (VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, "KilocaloriePerCubicCentimeterDegreeCelsius", "KilocaloriesPerCubicCentimeterDegreeCelsius", BaseUnits.Undefined, + new QuantityValue(1, 4184000000) + ); + yield return new (VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, "KilojoulePerCubicMeterDegreeCelsius", "KilojoulesPerCubicMeterDegreeCelsius", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), + new QuantityValue(1, 1000) + ); + yield return new (VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, "KilojoulePerCubicMeterKelvin", "KilojoulesPerCubicMeterKelvin", new BaseUnits(length: LengthUnit.Millimeter, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin), + new QuantityValue(1, 1000) + ); + yield return new (VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, "MegajoulePerCubicMeterDegreeCelsius", "MegajoulesPerCubicMeterDegreeCelsius", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.DegreeCelsius), + new QuantityValue(1, 1000000) + ); + yield return new (VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, "MegajoulePerCubicMeterKelvin", "MegajoulesPerCubicMeterKelvin", new BaseUnits(length: LengthUnit.Micrometer, mass: MassUnit.Kilogram, time: DurationUnit.Second, temperature: TemperatureUnit.Kelvin), + new QuantityValue(1, 1000000) + ); } } static VolumetricHeatCapacity() { - Info = VolumetricHeatCapacityInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(VolumetricHeatCapacityInfo.CreateDefault); } /// @@ -143,7 +156,7 @@ static VolumetricHeatCapacity() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public VolumetricHeatCapacity(double value, VolumetricHeatCapacityUnit unit) + public VolumetricHeatCapacity(QuantityValue value, VolumetricHeatCapacityUnit unit) { _value = value; _unit = unit; @@ -157,7 +170,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -168,7 +181,8 @@ public VolumetricHeatCapacity(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -197,10 +211,8 @@ public VolumetricHeatCapacity(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public VolumetricHeatCapacityUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -239,84 +251,54 @@ public VolumetricHeatCapacity(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double BtusPerCubicFootDegreeFahrenheit => As(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit); + public QuantityValue BtusPerCubicFootDegreeFahrenheit => this.As(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CaloriesPerCubicCentimeterDegreeCelsius => As(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius); + public QuantityValue CaloriesPerCubicCentimeterDegreeCelsius => this.As(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double JoulesPerCubicMeterDegreeCelsius => As(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius); + public QuantityValue JoulesPerCubicMeterDegreeCelsius => this.As(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double JoulesPerCubicMeterKelvin => As(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin); + public QuantityValue JoulesPerCubicMeterKelvin => this.As(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilocaloriesPerCubicCentimeterDegreeCelsius => As(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius); + public QuantityValue KilocaloriesPerCubicCentimeterDegreeCelsius => this.As(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilojoulesPerCubicMeterDegreeCelsius => As(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius); + public QuantityValue KilojoulesPerCubicMeterDegreeCelsius => this.As(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double KilojoulesPerCubicMeterKelvin => As(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin); + public QuantityValue KilojoulesPerCubicMeterKelvin => this.As(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegajoulesPerCubicMeterDegreeCelsius => As(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius); + public QuantityValue MegajoulesPerCubicMeterDegreeCelsius => this.As(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MegajoulesPerCubicMeterKelvin => As(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin); + public QuantityValue MegajoulesPerCubicMeterKelvin => this.As(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: VolumetricHeatCapacityUnit -> BaseUnit - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, quantity => quantity); - - // Register in unit converter: BaseUnit -> VolumetricHeatCapacityUnit - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius)); - unitConverter.SetConversionFunction(VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, quantity => quantity.ToUnit(VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin)); - } - /// /// Get unit abbreviation string. /// @@ -345,7 +327,7 @@ public static string GetAbbreviation(VolumetricHeatCapacityUnit unit, IFormatPro /// /// Creates a from . /// - public static VolumetricHeatCapacity FromBtusPerCubicFootDegreeFahrenheit(double value) + public static VolumetricHeatCapacity FromBtusPerCubicFootDegreeFahrenheit(QuantityValue value) { return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit); } @@ -353,7 +335,7 @@ public static VolumetricHeatCapacity FromBtusPerCubicFootDegreeFahrenheit(double /// /// Creates a from . /// - public static VolumetricHeatCapacity FromCaloriesPerCubicCentimeterDegreeCelsius(double value) + public static VolumetricHeatCapacity FromCaloriesPerCubicCentimeterDegreeCelsius(QuantityValue value) { return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius); } @@ -361,7 +343,7 @@ public static VolumetricHeatCapacity FromCaloriesPerCubicCentimeterDegreeCelsius /// /// Creates a from . /// - public static VolumetricHeatCapacity FromJoulesPerCubicMeterDegreeCelsius(double value) + public static VolumetricHeatCapacity FromJoulesPerCubicMeterDegreeCelsius(QuantityValue value) { return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius); } @@ -369,7 +351,7 @@ public static VolumetricHeatCapacity FromJoulesPerCubicMeterDegreeCelsius(double /// /// Creates a from . /// - public static VolumetricHeatCapacity FromJoulesPerCubicMeterKelvin(double value) + public static VolumetricHeatCapacity FromJoulesPerCubicMeterKelvin(QuantityValue value) { return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin); } @@ -377,7 +359,7 @@ public static VolumetricHeatCapacity FromJoulesPerCubicMeterKelvin(double value) /// /// Creates a from . /// - public static VolumetricHeatCapacity FromKilocaloriesPerCubicCentimeterDegreeCelsius(double value) + public static VolumetricHeatCapacity FromKilocaloriesPerCubicCentimeterDegreeCelsius(QuantityValue value) { return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius); } @@ -385,7 +367,7 @@ public static VolumetricHeatCapacity FromKilocaloriesPerCubicCentimeterDegreeCel /// /// Creates a from . /// - public static VolumetricHeatCapacity FromKilojoulesPerCubicMeterDegreeCelsius(double value) + public static VolumetricHeatCapacity FromKilojoulesPerCubicMeterDegreeCelsius(QuantityValue value) { return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius); } @@ -393,7 +375,7 @@ public static VolumetricHeatCapacity FromKilojoulesPerCubicMeterDegreeCelsius(do /// /// Creates a from . /// - public static VolumetricHeatCapacity FromKilojoulesPerCubicMeterKelvin(double value) + public static VolumetricHeatCapacity FromKilojoulesPerCubicMeterKelvin(QuantityValue value) { return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin); } @@ -401,7 +383,7 @@ public static VolumetricHeatCapacity FromKilojoulesPerCubicMeterKelvin(double va /// /// Creates a from . /// - public static VolumetricHeatCapacity FromMegajoulesPerCubicMeterDegreeCelsius(double value) + public static VolumetricHeatCapacity FromMegajoulesPerCubicMeterDegreeCelsius(QuantityValue value) { return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius); } @@ -409,7 +391,7 @@ public static VolumetricHeatCapacity FromMegajoulesPerCubicMeterDegreeCelsius(do /// /// Creates a from . /// - public static VolumetricHeatCapacity FromMegajoulesPerCubicMeterKelvin(double value) + public static VolumetricHeatCapacity FromMegajoulesPerCubicMeterKelvin(QuantityValue value) { return new VolumetricHeatCapacity(value, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin); } @@ -420,7 +402,7 @@ public static VolumetricHeatCapacity FromMegajoulesPerCubicMeterKelvin(double va /// Value to convert from. /// Unit to convert from. /// VolumetricHeatCapacity unit value. - public static VolumetricHeatCapacity From(double value, VolumetricHeatCapacityUnit fromUnit) + public static VolumetricHeatCapacity From(QuantityValue value, VolumetricHeatCapacityUnit fromUnit) { return new VolumetricHeatCapacity(value, fromUnit); } @@ -481,10 +463,7 @@ public static VolumetricHeatCapacity Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static VolumetricHeatCapacity Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -512,11 +491,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out VolumetricHeatCa /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out VolumetricHeatCapacity result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -537,7 +512,7 @@ public static VolumetricHeatCapacityUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -548,7 +523,7 @@ public static VolumetricHeatCapacityUnit ParseUnit(string str, IFormatProvider? return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out VolumetricHeatCapacityUnit unit) { return TryParseUnit(str, null, out unit); @@ -563,7 +538,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out VolumetricHe /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out VolumetricHeatCapacityUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -582,35 +557,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static VolumetricHeatCapacity operator +(VolumetricHeatCapacity left, VolumetricHeatCapacity right) { - return new VolumetricHeatCapacity(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new VolumetricHeatCapacity(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static VolumetricHeatCapacity operator -(VolumetricHeatCapacity left, VolumetricHeatCapacity right) { - return new VolumetricHeatCapacity(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new VolumetricHeatCapacity(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -622,97 +597,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(VolumetricHeatCapacity left, VolumetricHeatCapacity right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(VolumetricHeatCapacity left, VolumetricHeatCapacity right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(VolumetricHeatCapacity left, VolumetricHeatCapacity right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(VolumetricHeatCapacity left, VolumetricHeatCapacity right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(VolumetricHeatCapacity other, VolumetricHeatCapacity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(VolumetricHeatCapacity left, VolumetricHeatCapacity right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(VolumetricHeatCapacity other, VolumetricHeatCapacity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(VolumetricHeatCapacity left, VolumetricHeatCapacity right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(VolumetricHeatCapacity other, VolumetricHeatCapacity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is VolumetricHeatCapacity otherQuantity)) + if (obj is not VolumetricHeatCapacity otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(VolumetricHeatCapacity other, VolumetricHeatCapacity tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(VolumetricHeatCapacity other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current VolumetricHeatCapacity. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(VolumetricHeatCapacity), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is VolumetricHeatCapacity otherQuantity)) throw new ArgumentException("Expected type VolumetricHeatCapacity.", nameof(obj)); + if (obj is not VolumetricHeatCapacity otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -724,162 +684,24 @@ public int CompareTo(object? obj) /// public int CompareTo(VolumetricHeatCapacity other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(VolumetricHeatCapacityUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this VolumetricHeatCapacity to another VolumetricHeatCapacity with the unit representation . - /// - /// The unit to convert to. - /// A VolumetricHeatCapacity with the specified unit. - public VolumetricHeatCapacity ToUnit(VolumetricHeatCapacityUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A VolumetricHeatCapacity with the specified unit. - public VolumetricHeatCapacity ToUnit(VolumetricHeatCapacityUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(VolumetricHeatCapacity), Unit, typeof(VolumetricHeatCapacity), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (VolumetricHeatCapacity)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(VolumetricHeatCapacityUnit unit, [NotNullWhen(true)] out VolumetricHeatCapacity? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - VolumetricHeatCapacity? convertedOrNull = (Unit, unit) switch - { - // VolumetricHeatCapacityUnit -> BaseUnit - (VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin) => new VolumetricHeatCapacity(_value * (1055.05585262 / 0.028316846592) * 1.8, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin), - (VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin) => new VolumetricHeatCapacity(_value * 4.184e6, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin), - (VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin) => new VolumetricHeatCapacity(_value, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin), - (VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin) => new VolumetricHeatCapacity((_value * 4.184e6) * 1e3d, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin), - (VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin) => new VolumetricHeatCapacity((_value) * 1e3d, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin), - (VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin) => new VolumetricHeatCapacity((_value) * 1e3d, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin), - (VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin) => new VolumetricHeatCapacity((_value) * 1e6d, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin), - (VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin) => new VolumetricHeatCapacity((_value) * 1e6d, VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin), - - // BaseUnit -> VolumetricHeatCapacityUnit - (VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit) => new VolumetricHeatCapacity(_value / ((1055.05585262 / 0.028316846592) * 1.8), VolumetricHeatCapacityUnit.BtuPerCubicFootDegreeFahrenheit), - (VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius) => new VolumetricHeatCapacity(_value / 4.184e6, VolumetricHeatCapacityUnit.CaloriePerCubicCentimeterDegreeCelsius), - (VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius) => new VolumetricHeatCapacity(_value, VolumetricHeatCapacityUnit.JoulePerCubicMeterDegreeCelsius), - (VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius) => new VolumetricHeatCapacity((_value / 4.184e6) / 1e3d, VolumetricHeatCapacityUnit.KilocaloriePerCubicCentimeterDegreeCelsius), - (VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius) => new VolumetricHeatCapacity((_value) / 1e3d, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterDegreeCelsius), - (VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin) => new VolumetricHeatCapacity((_value) / 1e3d, VolumetricHeatCapacityUnit.KilojoulePerCubicMeterKelvin), - (VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius) => new VolumetricHeatCapacity((_value) / 1e6d, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterDegreeCelsius), - (VolumetricHeatCapacityUnit.JoulePerCubicMeterKelvin, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin) => new VolumetricHeatCapacity((_value) / 1e6d, VolumetricHeatCapacityUnit.MegajoulePerCubicMeterKelvin), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public VolumetricHeatCapacity ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not VolumetricHeatCapacityUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(VolumetricHeatCapacityUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(VolumetricHeatCapacityUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(VolumetricHeatCapacityUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -894,7 +716,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs b/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs index 50c81deecf..39b044d683 100644 --- a/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs +++ b/UnitsNet/GeneratedCode/Quantities/WarpingMomentOfInertia.g.cs @@ -20,9 +20,7 @@ using System.Globalization; using System.Resources; using System.Runtime.Serialization; -#if NET -using System.Numerics; -#endif +using UnitsNet.Debug; #nullable enable @@ -35,7 +33,8 @@ namespace UnitsNet /// A geometric property of an area that is used to determine the warping stress. /// [DataContract] - [DebuggerTypeProxy(typeof(QuantityDisplay))] + [DebuggerDisplay(QuantityDebugProxy.DisplayFormat)] + [DebuggerTypeProxy(typeof(QuantityDebugProxy))] public readonly partial struct WarpingMomentOfInertia : IArithmeticQuantity, #if NET7_0_OR_GREATER @@ -50,13 +49,13 @@ namespace UnitsNet /// /// The numeric value this quantity was constructed with. /// - [DataMember(Name = "Value", Order = 1)] - private readonly double _value; + [DataMember(Name = "Value", Order = 1, EmitDefaultValue = false)] + private readonly QuantityValue _value; /// /// The unit this quantity was constructed with. /// - [DataMember(Name = "Unit", Order = 2)] + [DataMember(Name = "Unit", Order = 2, EmitDefaultValue = false)] private readonly WarpingMomentOfInertiaUnit? _unit; /// @@ -101,7 +100,7 @@ public static WarpingMomentOfInertiaInfo CreateDefault(Func - /// The for is [L^6]. + /// The for is L^6. /// public static BaseDimensions DefaultBaseDimensions { get; } = new BaseDimensions(6, 0, 0, 0, 0, 0, 0); @@ -116,20 +115,28 @@ public static WarpingMomentOfInertiaInfo CreateDefault(FuncAn of representing the default unit mappings for WarpingMomentOfInertia. public static IEnumerable> GetDefaultMappings() { - yield return new (WarpingMomentOfInertiaUnit.CentimeterToTheSixth, "CentimeterToTheSixth", "CentimetersToTheSixth", new BaseUnits(length: LengthUnit.Centimeter)); - yield return new (WarpingMomentOfInertiaUnit.DecimeterToTheSixth, "DecimeterToTheSixth", "DecimetersToTheSixth", new BaseUnits(length: LengthUnit.Decimeter)); - yield return new (WarpingMomentOfInertiaUnit.FootToTheSixth, "FootToTheSixth", "FeetToTheSixth", new BaseUnits(length: LengthUnit.Foot)); - yield return new (WarpingMomentOfInertiaUnit.InchToTheSixth, "InchToTheSixth", "InchesToTheSixth", new BaseUnits(length: LengthUnit.Inch)); + yield return new (WarpingMomentOfInertiaUnit.CentimeterToTheSixth, "CentimeterToTheSixth", "CentimetersToTheSixth", new BaseUnits(length: LengthUnit.Centimeter), + 1000000000000 + ); + yield return new (WarpingMomentOfInertiaUnit.DecimeterToTheSixth, "DecimeterToTheSixth", "DecimetersToTheSixth", new BaseUnits(length: LengthUnit.Decimeter), + 1000000 + ); + yield return new (WarpingMomentOfInertiaUnit.FootToTheSixth, "FootToTheSixth", "FeetToTheSixth", new BaseUnits(length: LengthUnit.Foot), + new QuantityValue(3814697265625000000, 3058791354808281) + ); + yield return new (WarpingMomentOfInertiaUnit.InchToTheSixth, "InchToTheSixth", "InchesToTheSixth", new BaseUnits(length: LengthUnit.Inch), + new QuantityValue(new BigInteger(15625) * QuantityValue.PowerOfTen(18), 4195872914689) + ); yield return new (WarpingMomentOfInertiaUnit.MeterToTheSixth, "MeterToTheSixth", "MetersToTheSixth", new BaseUnits(length: LengthUnit.Meter)); - yield return new (WarpingMomentOfInertiaUnit.MillimeterToTheSixth, "MillimeterToTheSixth", "MillimetersToTheSixth", new BaseUnits(length: LengthUnit.Millimeter)); + yield return new (WarpingMomentOfInertiaUnit.MillimeterToTheSixth, "MillimeterToTheSixth", "MillimetersToTheSixth", new BaseUnits(length: LengthUnit.Millimeter), + 1000000000000000000 + ); } } static WarpingMomentOfInertia() { - Info = WarpingMomentOfInertiaInfo.CreateDefault(); - DefaultConversionFunctions = new UnitConverter(); - RegisterDefaultConversions(DefaultConversionFunctions); + Info = UnitsNetSetup.CreateQuantityInfo(WarpingMomentOfInertiaInfo.CreateDefault); } /// @@ -137,7 +144,7 @@ static WarpingMomentOfInertia() /// /// The numeric value to construct this quantity with. /// The unit representation to construct this quantity with. - public WarpingMomentOfInertia(double value, WarpingMomentOfInertiaUnit unit) + public WarpingMomentOfInertia(QuantityValue value, WarpingMomentOfInertiaUnit unit) { _value = value; _unit = unit; @@ -151,7 +158,7 @@ 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) { _value = value; _unit = Info.GetDefaultUnit(unitSystem); @@ -162,7 +169,8 @@ public WarpingMomentOfInertia(double value, UnitSystem unitSystem) /// /// The containing the default generated conversion functions for instances. /// - public static UnitConverter DefaultConversionFunctions { get; } + [Obsolete("Replaced by UnitConverter.Default")] + public static UnitConverter DefaultConversionFunctions => UnitConverter.Default; /// public static QuantityInfo Info { get; } @@ -191,10 +199,8 @@ public WarpingMomentOfInertia(double value, UnitSystem unitSystem) #region Properties - /// - /// The numeric value this quantity was constructed with. - /// - public double Value => _value; + /// + public QuantityValue Value => _value; /// public WarpingMomentOfInertiaUnit Unit => _unit.GetValueOrDefault(BaseUnit); @@ -233,63 +239,39 @@ public WarpingMomentOfInertia(double value, UnitSystem unitSystem) #region Conversion Properties /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double CentimetersToTheSixth => As(WarpingMomentOfInertiaUnit.CentimeterToTheSixth); + public QuantityValue CentimetersToTheSixth => this.As(WarpingMomentOfInertiaUnit.CentimeterToTheSixth); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double DecimetersToTheSixth => As(WarpingMomentOfInertiaUnit.DecimeterToTheSixth); + public QuantityValue DecimetersToTheSixth => this.As(WarpingMomentOfInertiaUnit.DecimeterToTheSixth); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double FeetToTheSixth => As(WarpingMomentOfInertiaUnit.FootToTheSixth); + public QuantityValue FeetToTheSixth => this.As(WarpingMomentOfInertiaUnit.FootToTheSixth); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double InchesToTheSixth => As(WarpingMomentOfInertiaUnit.InchToTheSixth); + public QuantityValue InchesToTheSixth => this.As(WarpingMomentOfInertiaUnit.InchToTheSixth); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MetersToTheSixth => As(WarpingMomentOfInertiaUnit.MeterToTheSixth); + public QuantityValue MetersToTheSixth => this.As(WarpingMomentOfInertiaUnit.MeterToTheSixth); /// - /// Gets a value of this quantity converted into + /// Gets a value of this quantity converted into /// - public double MillimetersToTheSixth => As(WarpingMomentOfInertiaUnit.MillimeterToTheSixth); + public QuantityValue MillimetersToTheSixth => this.As(WarpingMomentOfInertiaUnit.MillimeterToTheSixth); #endregion #region Static Methods - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - internal static void RegisterDefaultConversions(UnitConverter unitConverter) - { - // Register in unit converter: WarpingMomentOfInertiaUnit -> BaseUnit - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.CentimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.MeterToTheSixth)); - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.DecimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.MeterToTheSixth)); - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.FootToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.MeterToTheSixth)); - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.InchToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.MeterToTheSixth)); - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MillimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.MeterToTheSixth)); - - // Register in unit converter: BaseUnit <-> BaseUnit - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth, quantity => quantity); - - // Register in unit converter: BaseUnit -> WarpingMomentOfInertiaUnit - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.CentimeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.CentimeterToTheSixth)); - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.DecimeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.DecimeterToTheSixth)); - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.FootToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.FootToTheSixth)); - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.InchToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.InchToTheSixth)); - unitConverter.SetConversionFunction(WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.MillimeterToTheSixth, quantity => quantity.ToUnit(WarpingMomentOfInertiaUnit.MillimeterToTheSixth)); - } - /// /// Get unit abbreviation string. /// @@ -318,7 +300,7 @@ public static string GetAbbreviation(WarpingMomentOfInertiaUnit unit, IFormatPro /// /// Creates a from . /// - public static WarpingMomentOfInertia FromCentimetersToTheSixth(double value) + public static WarpingMomentOfInertia FromCentimetersToTheSixth(QuantityValue value) { return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.CentimeterToTheSixth); } @@ -326,7 +308,7 @@ public static WarpingMomentOfInertia FromCentimetersToTheSixth(double value) /// /// Creates a from . /// - public static WarpingMomentOfInertia FromDecimetersToTheSixth(double value) + public static WarpingMomentOfInertia FromDecimetersToTheSixth(QuantityValue value) { return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.DecimeterToTheSixth); } @@ -334,7 +316,7 @@ public static WarpingMomentOfInertia FromDecimetersToTheSixth(double value) /// /// Creates a from . /// - public static WarpingMomentOfInertia FromFeetToTheSixth(double value) + public static WarpingMomentOfInertia FromFeetToTheSixth(QuantityValue value) { return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.FootToTheSixth); } @@ -342,7 +324,7 @@ public static WarpingMomentOfInertia FromFeetToTheSixth(double value) /// /// Creates a from . /// - public static WarpingMomentOfInertia FromInchesToTheSixth(double value) + public static WarpingMomentOfInertia FromInchesToTheSixth(QuantityValue value) { return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.InchToTheSixth); } @@ -350,7 +332,7 @@ public static WarpingMomentOfInertia FromInchesToTheSixth(double value) /// /// Creates a from . /// - public static WarpingMomentOfInertia FromMetersToTheSixth(double value) + public static WarpingMomentOfInertia FromMetersToTheSixth(QuantityValue value) { return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.MeterToTheSixth); } @@ -358,7 +340,7 @@ public static WarpingMomentOfInertia FromMetersToTheSixth(double value) /// /// Creates a from . /// - public static WarpingMomentOfInertia FromMillimetersToTheSixth(double value) + public static WarpingMomentOfInertia FromMillimetersToTheSixth(QuantityValue value) { return new WarpingMomentOfInertia(value, WarpingMomentOfInertiaUnit.MillimeterToTheSixth); } @@ -369,7 +351,7 @@ public static WarpingMomentOfInertia FromMillimetersToTheSixth(double value) /// Value to convert from. /// Unit to convert from. /// WarpingMomentOfInertia unit value. - public static WarpingMomentOfInertia From(double value, WarpingMomentOfInertiaUnit fromUnit) + public static WarpingMomentOfInertia From(QuantityValue value, WarpingMomentOfInertiaUnit fromUnit) { return new WarpingMomentOfInertia(value, fromUnit); } @@ -430,10 +412,7 @@ public static WarpingMomentOfInertia Parse(string str) /// Format to use when parsing number and unit. Defaults to if null. public static WarpingMomentOfInertia Parse(string str, IFormatProvider? provider) { - return UnitsNetSetup.Default.QuantityParser.Parse( - str, - provider, - From); + return QuantityParser.Default.Parse(str, provider, From); } /// @@ -461,11 +440,7 @@ public static bool TryParse([NotNullWhen(true)]string? str, out WarpingMomentOfI /// Format to use when parsing number and unit. Defaults to if null. public static bool TryParse([NotNullWhen(true)]string? str, IFormatProvider? provider, out WarpingMomentOfInertia result) { - return UnitsNetSetup.Default.QuantityParser.TryParse( - str, - provider, - From, - out result); + return QuantityParser.Default.TryParse(str, provider, From, out result); } /// @@ -486,7 +461,7 @@ public static WarpingMomentOfInertiaUnit ParseUnit(string str) /// Parse a unit string. /// /// String to parse. Typically in the form: {number} {unit} - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. /// /// Length.ParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// @@ -497,7 +472,7 @@ public static WarpingMomentOfInertiaUnit ParseUnit(string str, IFormatProvider? return UnitParser.Default.Parse(str, Info.UnitInfos, provider).Value; } - /// + /// public static bool TryParseUnit([NotNullWhen(true)]string? str, out WarpingMomentOfInertiaUnit unit) { return TryParseUnit(str, null, out unit); @@ -512,7 +487,7 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, out WarpingMomen /// /// Length.TryParseUnit("m", CultureInfo.GetCultureInfo("en-US")); /// - /// Format to use when parsing number and unit. Defaults to if null. + /// Format to use when parsing the unit. Defaults to if null. public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? provider, out WarpingMomentOfInertiaUnit unit) { return UnitParser.Default.TryParse(str, Info, provider, out unit); @@ -531,35 +506,35 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Get from adding two . public static WarpingMomentOfInertia operator +(WarpingMomentOfInertia left, WarpingMomentOfInertia right) { - return new WarpingMomentOfInertia(left.Value + right.ToUnit(left.Unit).Value, left.Unit); + return new WarpingMomentOfInertia(left.Value + right.As(left.Unit), left.Unit); } /// Get from subtracting two . public static WarpingMomentOfInertia operator -(WarpingMomentOfInertia left, WarpingMomentOfInertia right) { - return new WarpingMomentOfInertia(left.Value - right.ToUnit(left.Unit).Value, left.Unit); + return new WarpingMomentOfInertia(left.Value - right.As(left.Unit), left.Unit); } /// 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; } @@ -571,97 +546,82 @@ public static bool TryParseUnit([NotNullWhen(true)]string? str, IFormatProvider? /// Returns true if less or equal to. public static bool operator <=(WarpingMomentOfInertia left, WarpingMomentOfInertia right) { - return left.Value <= right.ToUnit(left.Unit).Value; + return left.Value <= right.As(left.Unit); } /// Returns true if greater than or equal to. public static bool operator >=(WarpingMomentOfInertia left, WarpingMomentOfInertia right) { - return left.Value >= right.ToUnit(left.Unit).Value; + return left.Value >= right.As(left.Unit); } /// Returns true if less than. public static bool operator <(WarpingMomentOfInertia left, WarpingMomentOfInertia right) { - return left.Value < right.ToUnit(left.Unit).Value; + return left.Value < right.As(left.Unit); } /// Returns true if greater than. public static bool operator >(WarpingMomentOfInertia left, WarpingMomentOfInertia right) { - return left.Value > right.ToUnit(left.Unit).Value; + return left.Value > right.As(left.Unit); } - // We use obsolete attribute to communicate the preferred equality members to use. - // CS0809: Obsolete member 'memberA' overrides non-obsolete member 'memberB'. - #pragma warning disable CS0809 - - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(WarpingMomentOfInertia other, WarpingMomentOfInertia tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public static bool operator ==(WarpingMomentOfInertia left, WarpingMomentOfInertia right) { return left.Equals(right); } - /// Indicates strict inequality of two quantities, where both and are exactly equal. - [Obsolete("For null checks, use `x is null` syntax to not invoke overloads. For equality checks, use Equals(WarpingMomentOfInertia other, WarpingMomentOfInertia tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict inequality of two quantities. public static bool operator !=(WarpingMomentOfInertia left, WarpingMomentOfInertia right) { return !(left == right); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(WarpingMomentOfInertia other, WarpingMomentOfInertia tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public override bool Equals(object? obj) { - if (obj is null || !(obj is WarpingMomentOfInertia otherQuantity)) + if (obj is not WarpingMomentOfInertia otherQuantity) return false; return Equals(otherQuantity); } /// - /// Indicates strict equality of two quantities, where both and are exactly equal. - [Obsolete("Use Equals(WarpingMomentOfInertia other, WarpingMomentOfInertia tolerance) instead, to check equality across units and to specify the max tolerance for rounding errors due to floating-point arithmetic when converting between units.")] + /// Indicates strict equality of two quantities. public bool Equals(WarpingMomentOfInertia other) { - return new { Value, Unit }.Equals(new { other.Value, other.Unit }); + return _value.Equals(other.As(this.Unit)); } - #pragma warning restore CS0809 - /// /// Returns the hash code for this instance. /// /// A hash code for the current WarpingMomentOfInertia. public override int GetHashCode() { - return Comparison.GetHashCode(Unit, Value); + return Comparison.GetHashCode(typeof(WarpingMomentOfInertia), this.As(BaseUnit)); } - - /// Compares the current with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + + /// /// An object to compare with this instance. /// /// is not the same type as this instance. /// - /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: - /// - /// Value Meaning - /// Less than zero This instance precedes in the sort order. - /// Zero This instance occurs in the same position in the sort order as . - /// Greater than zero This instance follows in the sort order. - /// - /// public int CompareTo(object? obj) { - if (obj is null) throw new ArgumentNullException(nameof(obj)); - if (!(obj is WarpingMomentOfInertia otherQuantity)) throw new ArgumentException("Expected type WarpingMomentOfInertia.", nameof(obj)); + if (obj is not WarpingMomentOfInertia otherQuantity) + throw obj is null ? new ArgumentNullException(nameof(obj)) : ExceptionHelper.CreateArgumentException(obj, nameof(obj)); return CompareTo(otherQuantity); } - /// Compares the current with another and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other when converted to the same unit. + /// + /// Compares the current with another and returns an integer that indicates + /// whether the current instance precedes, follows, or occurs in the same position in the sort order as the other quantity, when converted to the same unit. + /// /// A quantity to compare with this instance. /// A value that indicates the relative order of the quantities being compared. The return value has these meanings: /// @@ -673,156 +633,24 @@ public int CompareTo(object? obj) /// public int CompareTo(WarpingMomentOfInertia other) { - return _value.CompareTo(other.ToUnit(this.Unit).Value); + return _value.CompareTo(other.As(this.Unit)); } #endregion - #region Conversion Methods - - /// - /// Convert to the unit representation . - /// - /// Value converted to the specified unit. - public double As(WarpingMomentOfInertiaUnit unit) - { - if (Unit == unit) - return Value; - - return ToUnit(unit).Value; - } - - /// - public double As(UnitKey unitKey) - { - return As(unitKey.ToUnit()); - } - - /// - public double As(UnitSystem unitSystem) - { - return As(Info.GetDefaultUnit(unitSystem)); - } + #region Conversion Methods (explicit implementations for netstandard2.0) - /// - /// Converts this WarpingMomentOfInertia to another WarpingMomentOfInertia with the unit representation . - /// - /// The unit to convert to. - /// A WarpingMomentOfInertia with the specified unit. - public WarpingMomentOfInertia ToUnit(WarpingMomentOfInertiaUnit unit) - { - return ToUnit(unit, DefaultConversionFunctions); - } - - /// - /// Converts this to another using the given with the unit representation . - /// - /// The unit to convert to. - /// The to use for the conversion. - /// A WarpingMomentOfInertia with the specified unit. - public WarpingMomentOfInertia ToUnit(WarpingMomentOfInertiaUnit unit, UnitConverter unitConverter) - { - if (TryToUnit(unit, out var converted)) - { - // Try to convert using the auto-generated conversion methods. - return converted!.Value; - } - else if (unitConverter.TryGetConversionFunction((typeof(WarpingMomentOfInertia), Unit, typeof(WarpingMomentOfInertia), unit), out var conversionFunction)) - { - // See if the unit converter has an extensibility conversion registered. - return (WarpingMomentOfInertia)conversionFunction(this); - } - else if (Unit != BaseUnit) - { - // Conversion to requested unit NOT found. Try to convert to BaseUnit, and then from BaseUnit to requested unit. - var inBaseUnits = ToUnit(BaseUnit); - return inBaseUnits.ToUnit(unit); - } - else - { - // No possible conversion - throw new UnitNotFoundException($"Can't convert {Unit} to {unit}."); - } - } - - /// - /// Attempts to convert this to another with the unit representation . - /// - /// The unit to convert to. - /// The converted in , if successful. - /// True if successful, otherwise false. - private bool TryToUnit(WarpingMomentOfInertiaUnit unit, [NotNullWhen(true)] out WarpingMomentOfInertia? converted) - { - if (Unit == unit) - { - converted = this; - return true; - } - - WarpingMomentOfInertia? convertedOrNull = (Unit, unit) switch - { - // WarpingMomentOfInertiaUnit -> BaseUnit - (WarpingMomentOfInertiaUnit.CentimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth) => new WarpingMomentOfInertia(_value / 1e12, WarpingMomentOfInertiaUnit.MeterToTheSixth), - (WarpingMomentOfInertiaUnit.DecimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth) => new WarpingMomentOfInertia(_value / 1e6, WarpingMomentOfInertiaUnit.MeterToTheSixth), - (WarpingMomentOfInertiaUnit.FootToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth) => new WarpingMomentOfInertia(_value * 0.000801843800914862014464, WarpingMomentOfInertiaUnit.MeterToTheSixth), - (WarpingMomentOfInertiaUnit.InchToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth) => new WarpingMomentOfInertia(_value * 0.000000000268535866540096, WarpingMomentOfInertiaUnit.MeterToTheSixth), - (WarpingMomentOfInertiaUnit.MillimeterToTheSixth, WarpingMomentOfInertiaUnit.MeterToTheSixth) => new WarpingMomentOfInertia(_value / 1e18, WarpingMomentOfInertiaUnit.MeterToTheSixth), - - // BaseUnit -> WarpingMomentOfInertiaUnit - (WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.CentimeterToTheSixth) => new WarpingMomentOfInertia(_value * 1e12, WarpingMomentOfInertiaUnit.CentimeterToTheSixth), - (WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.DecimeterToTheSixth) => new WarpingMomentOfInertia(_value * 1e6, WarpingMomentOfInertiaUnit.DecimeterToTheSixth), - (WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.FootToTheSixth) => new WarpingMomentOfInertia(_value / 0.000801843800914862014464, WarpingMomentOfInertiaUnit.FootToTheSixth), - (WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.InchToTheSixth) => new WarpingMomentOfInertia(_value / 0.000000000268535866540096, WarpingMomentOfInertiaUnit.InchToTheSixth), - (WarpingMomentOfInertiaUnit.MeterToTheSixth, WarpingMomentOfInertiaUnit.MillimeterToTheSixth) => new WarpingMomentOfInertia(_value * 1e18, WarpingMomentOfInertiaUnit.MillimeterToTheSixth), - - _ => null - }; - - if (convertedOrNull is null) - { - converted = default; - return false; - } - - converted = convertedOrNull.Value; - return true; - } - - /// - public WarpingMomentOfInertia ToUnit(UnitSystem unitSystem) - { - return ToUnit(Info.GetDefaultUnit(unitSystem)); - } - - #region Explicit implementations - - double IQuantity.As(Enum unit) - { - if (unit is not WarpingMomentOfInertiaUnit typedUnit) - throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(WarpingMomentOfInertiaUnit)} is supported.", nameof(unit)); - - return As(typedUnit); - } - - /// - IQuantity IQuantity.ToUnit(Enum unit) - { - 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(typedUnit, DefaultConversionFunctions); - } +#if NETSTANDARD2_0 + QuantityValue IQuantity.As(Enum unit) => UnitConverter.Default.ConvertValue(Value, UnitKey.ForUnit(Unit), unit); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(Enum unit) => UnitConverter.Default.ConvertTo(this, unit); - /// - IQuantity IQuantity.ToUnit(WarpingMomentOfInertiaUnit unit) => ToUnit(unit); + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); - /// - IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); + IQuantity IQuantity.ToUnit(WarpingMomentOfInertiaUnit unit) => this.ToUnit(unit); - #endregion + IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => this.ToUnit(unitSystem); +#endif #endregion @@ -837,7 +665,7 @@ public override string ToString() return ToString(null, null); } - /// + /// /// /// Gets the string representation of this instance in the specified format string using the specified format provider, or if null. /// diff --git a/UnitsNet/GeneratedCode/Quantity.g.cs b/UnitsNet/GeneratedCode/Quantity.g.cs index c7a7c3af9c..49cdccda47 100644 --- a/UnitsNet/GeneratedCode/Quantity.g.cs +++ b/UnitsNet/GeneratedCode/Quantity.g.cs @@ -34,8 +34,8 @@ internal static class DefaultProvider /// /// All QuantityInfo instances that are present in UnitsNet by default. /// - internal static IReadOnlyList Quantities { get; } = - [ + internal static IReadOnlyList Quantities => new QuantityInfo[] + { AbsorbedDoseOfIonizingRadiation.Info, Acceleration.Info, AmountOfSubstance.Info, @@ -164,138 +164,17 @@ internal static class DefaultProvider VolumePerLength.Info, VolumetricHeatCapacity.Info, WarpingMomentOfInertia.Info, - ]; + }; - internal static void RegisterUnitConversions(UnitConverter unitConverter) + /// + /// All implicit quantity conversions that exist by default. + /// + internal static readonly IReadOnlyList Conversions = new QuantityConversionMapping[] { - AbsorbedDoseOfIonizingRadiation.RegisterDefaultConversions(unitConverter); - Acceleration.RegisterDefaultConversions(unitConverter); - AmountOfSubstance.RegisterDefaultConversions(unitConverter); - AmplitudeRatio.RegisterDefaultConversions(unitConverter); - Angle.RegisterDefaultConversions(unitConverter); - Area.RegisterDefaultConversions(unitConverter); - AreaDensity.RegisterDefaultConversions(unitConverter); - AreaMomentOfInertia.RegisterDefaultConversions(unitConverter); - BitRate.RegisterDefaultConversions(unitConverter); - BrakeSpecificFuelConsumption.RegisterDefaultConversions(unitConverter); - CoefficientOfThermalExpansion.RegisterDefaultConversions(unitConverter); - Compressibility.RegisterDefaultConversions(unitConverter); - Density.RegisterDefaultConversions(unitConverter); - DoseAreaProduct.RegisterDefaultConversions(unitConverter); - Duration.RegisterDefaultConversions(unitConverter); - DynamicViscosity.RegisterDefaultConversions(unitConverter); - ElectricAdmittance.RegisterDefaultConversions(unitConverter); - ElectricApparentEnergy.RegisterDefaultConversions(unitConverter); - ElectricApparentPower.RegisterDefaultConversions(unitConverter); - ElectricCapacitance.RegisterDefaultConversions(unitConverter); - ElectricCharge.RegisterDefaultConversions(unitConverter); - ElectricChargeDensity.RegisterDefaultConversions(unitConverter); - ElectricConductance.RegisterDefaultConversions(unitConverter); - ElectricConductivity.RegisterDefaultConversions(unitConverter); - ElectricCurrent.RegisterDefaultConversions(unitConverter); - ElectricCurrentDensity.RegisterDefaultConversions(unitConverter); - ElectricCurrentGradient.RegisterDefaultConversions(unitConverter); - ElectricField.RegisterDefaultConversions(unitConverter); - ElectricImpedance.RegisterDefaultConversions(unitConverter); - ElectricInductance.RegisterDefaultConversions(unitConverter); - ElectricPotential.RegisterDefaultConversions(unitConverter); - ElectricPotentialChangeRate.RegisterDefaultConversions(unitConverter); - ElectricReactance.RegisterDefaultConversions(unitConverter); - ElectricReactiveEnergy.RegisterDefaultConversions(unitConverter); - ElectricReactivePower.RegisterDefaultConversions(unitConverter); - ElectricResistance.RegisterDefaultConversions(unitConverter); - ElectricResistivity.RegisterDefaultConversions(unitConverter); - ElectricSurfaceChargeDensity.RegisterDefaultConversions(unitConverter); - ElectricSusceptance.RegisterDefaultConversions(unitConverter); - Energy.RegisterDefaultConversions(unitConverter); - EnergyDensity.RegisterDefaultConversions(unitConverter); - Entropy.RegisterDefaultConversions(unitConverter); - FluidResistance.RegisterDefaultConversions(unitConverter); - Force.RegisterDefaultConversions(unitConverter); - ForceChangeRate.RegisterDefaultConversions(unitConverter); - ForcePerLength.RegisterDefaultConversions(unitConverter); - Frequency.RegisterDefaultConversions(unitConverter); - FuelEfficiency.RegisterDefaultConversions(unitConverter); - HeatFlux.RegisterDefaultConversions(unitConverter); - HeatTransferCoefficient.RegisterDefaultConversions(unitConverter); - Illuminance.RegisterDefaultConversions(unitConverter); - Impulse.RegisterDefaultConversions(unitConverter); - Information.RegisterDefaultConversions(unitConverter); - Irradiance.RegisterDefaultConversions(unitConverter); - Irradiation.RegisterDefaultConversions(unitConverter); - Jerk.RegisterDefaultConversions(unitConverter); - KinematicViscosity.RegisterDefaultConversions(unitConverter); - LeakRate.RegisterDefaultConversions(unitConverter); - Length.RegisterDefaultConversions(unitConverter); - Level.RegisterDefaultConversions(unitConverter); - LinearDensity.RegisterDefaultConversions(unitConverter); - LinearPowerDensity.RegisterDefaultConversions(unitConverter); - Luminance.RegisterDefaultConversions(unitConverter); - Luminosity.RegisterDefaultConversions(unitConverter); - LuminousFlux.RegisterDefaultConversions(unitConverter); - LuminousIntensity.RegisterDefaultConversions(unitConverter); - MagneticField.RegisterDefaultConversions(unitConverter); - MagneticFlux.RegisterDefaultConversions(unitConverter); - Magnetization.RegisterDefaultConversions(unitConverter); - Mass.RegisterDefaultConversions(unitConverter); - MassConcentration.RegisterDefaultConversions(unitConverter); - MassFlow.RegisterDefaultConversions(unitConverter); - MassFlux.RegisterDefaultConversions(unitConverter); - MassFraction.RegisterDefaultConversions(unitConverter); - MassMomentOfInertia.RegisterDefaultConversions(unitConverter); - Molality.RegisterDefaultConversions(unitConverter); - MolarEnergy.RegisterDefaultConversions(unitConverter); - MolarEntropy.RegisterDefaultConversions(unitConverter); - MolarFlow.RegisterDefaultConversions(unitConverter); - Molarity.RegisterDefaultConversions(unitConverter); - MolarMass.RegisterDefaultConversions(unitConverter); - Permeability.RegisterDefaultConversions(unitConverter); - Permittivity.RegisterDefaultConversions(unitConverter); - PorousMediumPermeability.RegisterDefaultConversions(unitConverter); - Power.RegisterDefaultConversions(unitConverter); - PowerDensity.RegisterDefaultConversions(unitConverter); - PowerRatio.RegisterDefaultConversions(unitConverter); - Pressure.RegisterDefaultConversions(unitConverter); - PressureChangeRate.RegisterDefaultConversions(unitConverter); - RadiationEquivalentDose.RegisterDefaultConversions(unitConverter); - RadiationEquivalentDoseRate.RegisterDefaultConversions(unitConverter); - RadiationExposure.RegisterDefaultConversions(unitConverter); - Radioactivity.RegisterDefaultConversions(unitConverter); - Ratio.RegisterDefaultConversions(unitConverter); - RatioChangeRate.RegisterDefaultConversions(unitConverter); - ReciprocalArea.RegisterDefaultConversions(unitConverter); - ReciprocalLength.RegisterDefaultConversions(unitConverter); - RelativeHumidity.RegisterDefaultConversions(unitConverter); - RotationalAcceleration.RegisterDefaultConversions(unitConverter); - RotationalSpeed.RegisterDefaultConversions(unitConverter); - RotationalStiffness.RegisterDefaultConversions(unitConverter); - RotationalStiffnessPerLength.RegisterDefaultConversions(unitConverter); - Scalar.RegisterDefaultConversions(unitConverter); - SolidAngle.RegisterDefaultConversions(unitConverter); - SpecificEnergy.RegisterDefaultConversions(unitConverter); - SpecificEntropy.RegisterDefaultConversions(unitConverter); - SpecificFuelConsumption.RegisterDefaultConversions(unitConverter); - SpecificVolume.RegisterDefaultConversions(unitConverter); - SpecificWeight.RegisterDefaultConversions(unitConverter); - Speed.RegisterDefaultConversions(unitConverter); - StandardVolumeFlow.RegisterDefaultConversions(unitConverter); - Temperature.RegisterDefaultConversions(unitConverter); - TemperatureChangeRate.RegisterDefaultConversions(unitConverter); - TemperatureDelta.RegisterDefaultConversions(unitConverter); - TemperatureGradient.RegisterDefaultConversions(unitConverter); - ThermalConductivity.RegisterDefaultConversions(unitConverter); - ThermalInsulance.RegisterDefaultConversions(unitConverter); - ThermalResistance.RegisterDefaultConversions(unitConverter); - Torque.RegisterDefaultConversions(unitConverter); - Turbidity.RegisterDefaultConversions(unitConverter); - VitaminA.RegisterDefaultConversions(unitConverter); - Volume.RegisterDefaultConversions(unitConverter); - VolumeConcentration.RegisterDefaultConversions(unitConverter); - VolumeFlow.RegisterDefaultConversions(unitConverter); - VolumeFlowPerArea.RegisterDefaultConversions(unitConverter); - VolumePerLength.RegisterDefaultConversions(unitConverter); - VolumetricHeatCapacity.RegisterDefaultConversions(unitConverter); - WarpingMomentOfInertia.RegisterDefaultConversions(unitConverter); - } + new (typeof(Area), typeof(ReciprocalArea)), + new (typeof(Density), typeof(SpecificVolume)), + new (typeof(ElectricConductivity), typeof(ElectricResistivity)), + new (typeof(Length), typeof(ReciprocalLength)), + }; } } diff --git a/UnitsNet/GenericMath/GenericMathExtensions.cs b/UnitsNet/GenericMath/GenericMathExtensions.cs index 239f85c299..ddfd2f3536 100644 --- a/UnitsNet/GenericMath/GenericMathExtensions.cs +++ b/UnitsNet/GenericMath/GenericMathExtensions.cs @@ -2,7 +2,6 @@ // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. #if NET7_0_OR_GREATER -using System.Numerics; namespace UnitsNet.GenericMath; @@ -81,12 +80,12 @@ public static TQuantity Sum(this IEnumerable source) /// public static TQuantity Average(this IEnumerable source) where TQuantity : IQuantity, IAdditionOperators, IAdditiveIdentity, - IDivisionOperators + IDivisionOperators { using IEnumerator e = source.GetEnumerator(); if (!e.MoveNext()) { - throw new InvalidOperationException("Sequence contains no elements"); + throw ExceptionHelper.CreateInvalidOperationOnEmptyCollectionException(); } TQuantity result = e.Current; diff --git a/UnitsNet/IAffineQuantity.cs b/UnitsNet/IAffineQuantity.cs index 0a8028f784..5ae13bdc2c 100644 --- a/UnitsNet/IAffineQuantity.cs +++ b/UnitsNet/IAffineQuantity.cs @@ -1,29 +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. -#if NET7_0_OR_GREATER -using System.Numerics; -#endif - namespace UnitsNet; -/// -/// An that (in .NET 7+) implements generic math interfaces for arithmetic operations. -/// -/// The type itself, for the CRT pattern. -/// The underlying unit enum type. -/// -public interface IAffineQuantity : IQuantity, IAffineQuantity -#if NET7_0_OR_GREATER - , IAdditionOperators - , ISubtractionOperators - where TOffset : IAdditiveIdentity -#endif - where TSelf : IAffineQuantity - where TUnitType : struct, Enum -{ -} - /// /// An that (in .NET 7+) implements generic math interfaces for arithmetic operations. /// @@ -44,4 +23,45 @@ public interface IAffineQuantity : IQuantityOfType static TOffset IAdditiveIdentity.AdditiveIdentity => TOffset.AdditiveIdentity; #endif + +#if EXTENDED_EQUALS_INTERFACE + /// + /// + /// Compare equality to given a for the maximum allowed +/- difference. + /// + /// + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromMeters(2.1); + /// var tolerance = Length.FromCentimeters(10); + /// a.Equals(b, tolerance); // true, 2m equals 2.1m +/- 0.1m + /// + /// + /// + /// It is generally advised against specifying "zero" tolerance, due to the nature of floating-point operations. + /// + /// + /// The other quantity to compare to. + /// The absolute tolerance value. Must be greater than or equal to zero. + /// True if the absolute difference between the two values is not greater than the specified tolerance. + bool Equals(TSelf? other, TOffset tolerance); +#endif +} + +/// +/// An that (in .NET 7+) implements generic math interfaces for arithmetic operations. +/// +/// The type itself, for the CRT pattern. +/// The underlying unit enum type. +/// +public interface IAffineQuantity : IQuantity, IAffineQuantity +#if NET7_0_OR_GREATER + , IAdditionOperators + , ISubtractionOperators + where TOffset : IAdditiveIdentity +#endif + where TSelf : IAffineQuantity + where TUnitType : struct, Enum +{ } diff --git a/UnitsNet/IArithmeticQuantity.cs b/UnitsNet/IArithmeticQuantity.cs index d9d075d19e..3101869e8a 100644 --- a/UnitsNet/IArithmeticQuantity.cs +++ b/UnitsNet/IArithmeticQuantity.cs @@ -1,10 +1,6 @@ // 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. -#if NET -using System.Numerics; -#endif - namespace UnitsNet; /// @@ -44,6 +40,30 @@ static TSelf IAdditiveIdentity.AdditiveIdentity } #endif + +#if EXTENDED_EQUALS_INTERFACE + /// + /// + /// Compare equality to given a for the maximum allowed +/- difference. + /// + /// + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromMeters(2.1); + /// var tolerance = Length.FromCentimeters(10); + /// a.Equals(b, tolerance); // true, 2m equals 2.1m +/- 0.1m + /// + /// + /// + /// It is generally advised against specifying "zero" tolerance, due to the nature of floating-point operations. + /// + /// + /// The other quantity to compare to. + /// The absolute tolerance value. Must be greater than or equal to zero. + /// True if the absolute difference between the two values is not greater than the specified tolerance. + bool Equals(TSelf? other, TSelf tolerance); +#endif } /// @@ -56,8 +76,8 @@ public interface IArithmeticQuantity : IQuantity , ISubtractionOperators - , IMultiplyOperators - , IDivisionOperators + , IMultiplyOperators + , IDivisionOperators , IUnaryNegationOperators #endif where TSelf : IArithmeticQuantity diff --git a/UnitsNet/ILogarithmicQuantity.cs b/UnitsNet/ILogarithmicQuantity.cs index eb35775ac1..bcaae079bd 100644 --- a/UnitsNet/ILogarithmicQuantity.cs +++ b/UnitsNet/ILogarithmicQuantity.cs @@ -1,28 +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. -#if NET7_0_OR_GREATER -using System.Numerics; -#endif - namespace UnitsNet; -/// -/// The type itself, for the CRT pattern. -/// The underlying unit enum type. -public interface ILogarithmicQuantity : IQuantity, ILogarithmicQuantity -#if NET7_0_OR_GREATER - , IAdditionOperators - , ISubtractionOperators - , IMultiplyOperators - , IDivisionOperators - , IUnaryNegationOperators -#endif - where TSelf : ILogarithmicQuantity - where TUnitType : struct, Enum -{ -} - /// /// Represents a logarithmic quantity that supports arithmetic operations and implements generic math interfaces /// (in .NET 7+). This interface is designed for quantities that are logarithmic in nature, such as decibels. @@ -48,7 +28,7 @@ public interface ILogarithmicQuantity : IQuantityOfType /// /// The logarithmic scaling factor. /// - static abstract double LogarithmicScalingFactor { get; } + static abstract QuantityValue LogarithmicScalingFactor { get; } /// /// The zero value of this quantity. @@ -57,13 +37,29 @@ public interface ILogarithmicQuantity : IQuantityOfType static TSelf IMultiplicativeIdentity.MultiplicativeIdentity => TSelf.Zero; #else - /// - /// Gets the logarithmic scaling factor used to convert between linear and logarithmic units. - /// This factor is typically 10, but there are exceptions such as the PowerRatio, which uses 20. - /// - /// - /// The logarithmic scaling factor. - /// - double LogarithmicScalingFactor { get; } + /// + /// Gets the logarithmic scaling factor used to convert between linear and logarithmic units. + /// This factor is typically 10, but there are exceptions such as the PowerRatio, which uses 20. + /// + /// + /// The logarithmic scaling factor. + /// + QuantityValue LogarithmicScalingFactor { get; } #endif } + +/// +/// The type itself, for the CRT pattern. +/// The underlying unit enum type. +public interface ILogarithmicQuantity : IQuantity, ILogarithmicQuantity +#if NET7_0_OR_GREATER + , IAdditionOperators + , ISubtractionOperators + , IMultiplyOperators + , IDivisionOperators + , IUnaryNegationOperators +#endif + where TSelf : ILogarithmicQuantity + where TUnitType : struct, Enum +{ +} diff --git a/UnitsNet/IQuantity.cs b/UnitsNet/IQuantity.cs index 42debad321..eede929ca2 100644 --- a/UnitsNet/IQuantity.cs +++ b/UnitsNet/IQuantity.cs @@ -23,24 +23,43 @@ 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); + /// Thrown when the is not recognized. + [Obsolete("This method will be removed from the interface in the next major update. Consider using the UnitConverter.Default.ConvertValue(quantity, unit) method instead.")] + QuantityValue As(Enum unit) +#if NET + => this.GetValue(unit) +#endif + ; - /// - /// Gets the value in the given unit key. - /// - /// The unit key. The unit type must be compatible, so for you should provide a value. - /// Value converted to the specified unit. - /// Wrong unit enum type was given. - double As(UnitKey unitKey); + // /// + // /// Gets the value in the unit determined by the given . If multiple units were found for the given , + // /// the first match will be used. + // /// + // /// The to convert the quantity value to. + // /// The converted value. + // QuantityValue As(UnitSystem unitSystem); +#if EXTENDED_EQUALS_INTERFACE /// - /// Gets the value in the unit determined by the given . If multiple units were found for the given , - /// the first match will be used. + /// + /// Compare equality to given a for the maximum allowed +/- difference. + /// + /// + /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). + /// + /// var a = Length.FromMeters(2.0); + /// var b = Length.FromMeters(2.1); + /// var tolerance = Length.FromCentimeters(10); + /// a.Equals(b, tolerance); // true, 2m equals 2.1m +/- 0.1m + /// + /// /// - /// The to convert the quantity value to. - /// The converted value. - double As(UnitSystem unitSystem); + /// The other quantity to compare to. Not equal if the quantity types are different. + /// The absolute tolerance value. Must be greater than or equal to zero. Must be same quantity type as . + /// True if the absolute difference between the two values is not greater than the specified tolerance. + /// Tolerance must be of the same quantity type. + bool Equals(IQuantity? other, IQuantity tolerance); +#endif /// /// The unit this quantity was constructed with -or- BaseUnit if default ctor was used. @@ -50,7 +69,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 . @@ -59,17 +78,29 @@ public interface IQuantity : IFormattable /// The unit value. The must be compatible with the units of the . /// For example, if the is a , you should provide a value. /// - /// Conversion was not possible from this to . + /// Wrong unit enum type was given. + /// Thrown when the is not recognized. /// A new in the given . - IQuantity ToUnit(Enum unit); + [Obsolete("This method will be removed from the interface in the next major update. Consider using the UnitConverter.Default.ConvertTo(quantity, unit) method instead.")] + IQuantity ToUnit(Enum unit) +#if NET + => UnitConverter.Default.ConvertTo(this, unit) +#endif + ; /// /// Converts to a quantity with a unit determined by the given . /// If multiple units were found for the given , the first match will be used. /// /// The to convert the quantity to. + /// Thrown when no units were found for the given UnitSystem. /// A new quantity with the determined unit. - IQuantity ToUnit(UnitSystem unitSystem); + [Obsolete("This method will be removed from the interface in the next major update. Consider using the UnitConverter.Default.ConvertTo(quantity, unit) method instead.")] + IQuantity ToUnit(UnitSystem unitSystem) +#if NET + => UnitConverter.Default.ConvertTo(this, QuantityInfo.GetDefaultUnit(unitSystem).UnitKey) +#endif + ; /// /// Gets the unique key for the unit type and its corresponding value. @@ -93,11 +124,11 @@ public interface IQuantity : IFormattable public interface IQuantity : IQuantity where TUnitType : struct, Enum { - /// - /// Convert to a unit representation . - /// - /// Value converted to the specified unit. - double As(TUnitType unit); + // /// + // /// Convert to a unit representation . + // /// + // /// Value converted to the specified unit. + // QuantityValue As(TUnitType unit); /// new TUnitType Unit { get; } @@ -109,11 +140,13 @@ public interface IQuantity : IQuantity /// Converts this to an in the given . /// /// The unit value. - /// Conversion was not possible from this to . + /// Thrown when the is not recognized. /// A new in the given . + [Obsolete("This method will be removed from the interface in the next major update. Consider using the UnitConverter.Default.ConvertToUnit(quantity, unit) method instead.")] IQuantity ToUnit(TUnitType unit); /// + [Obsolete("This method will be removed from the interface in the next major update. Consider using the UnitConverter.Default.ConvertToUnit(quantity, unit) method instead.")] new IQuantity ToUnit(UnitSystem unitSystem); #if NET @@ -145,7 +178,7 @@ public interface IQuantityOfType : IQuantity where TQuantity : IQuantity { #if NET - internal static abstract TQuantity Create(double value, UnitKey unit); + internal static abstract TQuantity Create(QuantityValue value, UnitKey unit); #else /// new IQuantityInstanceInfo QuantityInfo { get; } @@ -161,6 +194,16 @@ public interface IQuantity : IQuantityOfType, IQuantity where TSelf : IQuantity where TUnitType : struct, Enum { + // /// + // /// Converts the quantity to the specified unit. + // /// + // /// The unit to convert to. + // /// A new instance of the quantity in the specified unit. + // new TSelf ToUnit(TUnitType unit); + + // /// + // new TSelf ToUnit(UnitSystem unitSystem); + /// new QuantityInfo QuantityInfo { get; } @@ -171,19 +214,19 @@ public interface IQuantity : IQuantityOfType, IQuantity /// The numerical value of the quantity. /// The unit of the quantity. /// An instance of the quantity with the specified value and unit. - static abstract TSelf From(double value, TUnitType unit); + static abstract TSelf From(QuantityValue value, TUnitType unit); - static TSelf IQuantityOfType.Create(double value, UnitKey unit) => TSelf.From(value, unit.ToUnit()); + static TSelf IQuantityOfType.Create(QuantityValue value, UnitKey unit) => TSelf.From(value, unit.ToUnit()); IQuantity IQuantity.ToUnit(TUnitType unit) { - return TSelf.From(As(unit), unit); + return TSelf.From(UnitConverter.Default.ConvertValue(Value, Unit, unit), unit); } IQuantity IQuantity.ToUnit(UnitSystem unitSystem) { TUnitType unit = QuantityInfo.GetDefaultUnit(unitSystem); - return ToUnit(unit); + return TSelf.From(UnitConverter.Default.ConvertValue(Value, Unit, unit), unit); } #endif diff --git a/UnitsNet/IQuantityInfo.cs b/UnitsNet/IQuantityInfo.cs index 79928c6f49..df285e6d1e 100644 --- a/UnitsNet/IQuantityInfo.cs +++ b/UnitsNet/IQuantityInfo.cs @@ -19,7 +19,7 @@ namespace UnitsNet; #else internal #endif -interface IQuantityInfo +interface IQuantityInfo { /// /// Quantity name, such as "Length" or "Mass". @@ -122,5 +122,5 @@ interface IQuantityInstanceInfo : IQuantityInfo /// new TQuantity Zero { get; } - internal TQuantity Create(double value, UnitKey unitKey); + internal TQuantity Create(QuantityValue value, UnitKey unitKey); } diff --git a/UnitsNet/IUnitDefinition.cs b/UnitsNet/IUnitDefinition.cs index c719817325..bf4df497f5 100644 --- a/UnitsNet/IUnitDefinition.cs +++ b/UnitsNet/IUnitDefinition.cs @@ -23,6 +23,61 @@ public interface IUnitDefinition /// Gets the for this unit. /// BaseUnits BaseUnits { get; } + + /// + /// Gets the conversion expression used to convert from the base unit to this unit. + /// + /// + /// The conversion expression, represented as a . + /// + /// + /// The conversion expression is defined as an equation of the form: + /// + /// f(x) = a * g(x)^n + b + /// + /// where: + /// + /// + /// a and b are constants of type . + /// + /// + /// + /// g(x) is an optional custom function applied to the input x (of type + /// ). + /// + /// + /// + /// n is an integer exponent. + /// + /// + /// + ConversionExpression ConversionFromBase { get; } + + /// + /// Gets the conversion expression used to convert a unit to its base unit. + /// + /// + /// The conversion is defined as a function of the form: + /// + /// f(x) = a * g(x)^n + b + /// + /// where: + /// + /// + /// a and b are constants of type . + /// + /// + /// + /// g(x) is an optional custom function applied to the input x (of type + /// ). + /// + /// + /// + /// n is an integer exponent. + /// + /// + /// + ConversionExpression ConversionToBase { get; } } /// diff --git a/UnitsNet/QuantityDisplay.cs b/UnitsNet/QuantityDisplay.cs deleted file mode 100644 index 166afc9544..0000000000 --- a/UnitsNet/QuantityDisplay.cs +++ /dev/null @@ -1,142 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.Linq; - -namespace UnitsNet; - -/// -/// Serves as a debug display proxy for a quantity, providing a convenient way to view various components of the -/// quantity during debugging. -/// -/// -/// This struct provides a structured view of a quantity's components such as abbreviation, unit, value, and convertor -/// during debugging. -/// Each component is represented by a nested struct, which can be expanded in the debugger to inspect its properties. -/// -internal readonly struct QuantityDisplay(IQuantity quantity) -{ - public UnitDisplay Unit => new(quantity); - public AbbreviationDisplay UnitAbbreviation => new(quantity); - public ValueDisplay Value => new(quantity); - public QuantityConvertor ValueConvertor => new(quantity); - - - [DebuggerDisplay("{DefaultAbbreviation}")] - internal readonly struct AbbreviationDisplay - { - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - private readonly IQuantity _quantity; - - public AbbreviationDisplay(IQuantity quantity) - { - _quantity = quantity; - QuantityInfo quantityQuantityInfo = quantity.QuantityInfo; - IQuantity baseQuantity = quantity.ToUnit(quantityQuantityInfo.BaseUnitInfo.Value); - Conversions = quantityQuantityInfo.UnitInfos.Select(x => new ConvertedQuantity(baseQuantity, x)).ToArray(); - } - - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - public string DefaultAbbreviation => UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(_quantity.Unit); - - [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public IReadOnlyList Abbreviations => UnitsNetSetup.Default.UnitAbbreviations.GetUnitAbbreviations(_quantity.Unit); - - public ConvertedQuantity[] Conversions { get; } - - [DebuggerDisplay("{Abbreviation}")] - internal readonly struct ConvertedQuantity(IQuantity baseQuantity, UnitInfo unit) - { - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - public UnitInfo Unit { get; } = unit; - - [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public IQuantity Quantity => baseQuantity.ToUnit(Unit.Value); - - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - public string Abbreviation => UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(Unit.UnitKey); - - public override string ToString() - { - return Abbreviation; - } - } - } - - [DebuggerDisplay("{Unit}")] - internal readonly struct UnitDisplay - { - public UnitDisplay(IQuantity quantity) - { - Unit = quantity.Unit; - IQuantity baseQuantity = quantity.ToUnit(quantity.QuantityInfo.BaseUnitInfo.Value); - Conversions = quantity.QuantityInfo.UnitInfos.Select(x => new ConvertedQuantity(baseQuantity, x.Value)).ToArray(); - } - - [DebuggerBrowsable(DebuggerBrowsableState.Never)] - public Enum Unit { get; } - - [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public ConvertedQuantity[] Conversions { get; } - - internal readonly struct ConvertedQuantity(IQuantity baseQuantity, Enum unit) - { - [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public IQuantity Quantity => baseQuantity.ToUnit(unit); - - public override string ToString() - { - return unit.ToString(); - } - } - } - - [DebuggerDisplay("{DoubleValue}")] - internal readonly struct ValueDisplay(IQuantity quantity) - { - public double DoubleValue => quantity.Value; - public decimal DecimalValue => (decimal)quantity.Value; - - public override string ToString() - { - return DoubleValue.ToString(CultureInfo.CurrentCulture); - } - } - - [DebuggerDisplay("{QuantityToString}")] - internal readonly struct QuantityConvertor - { - public QuantityConvertor(IQuantity quantity) - { - QuantityToString = new StringFormatsDisplay(quantity); - QuantityInfo quantityQuantityInfo = quantity.QuantityInfo; - IQuantity baseQuantity = quantity.ToUnit(quantityQuantityInfo.BaseUnitInfo.Value); - QuantityToUnit = quantityQuantityInfo.UnitInfos.Select(x => new ConvertedQuantity(baseQuantity.ToUnit(x.Value), x)).ToArray(); - } - - public StringFormatsDisplay QuantityToString { get; } - public ConvertedQuantity[] QuantityToUnit { get; } - - [DebuggerDisplay("{ShortFormat}")] - internal readonly struct StringFormatsDisplay(IQuantity quantity) - { - public string GeneralFormat => quantity.ToString("g", CultureInfo.CurrentCulture); - public string ShortFormat => quantity.ToString("s", CultureInfo.CurrentCulture); - } - - [DebuggerDisplay("{Quantity}")] - internal readonly struct ConvertedQuantity(IQuantity quantity, UnitInfo unitInfo) - { - public UnitInfo Unit { get; } = unitInfo; - public string Abbreviation => UnitsNetSetup.Default.UnitAbbreviations.GetDefaultAbbreviation(Unit.UnitKey); - public ValueDisplay Value => new(Quantity); - public IQuantity Quantity { get; } = quantity; - - public override string ToString() - { - return Quantity.ToString()!; - } - } - } -} diff --git a/UnitsNet/QuantityFormatter.cs b/UnitsNet/QuantityFormatter.cs index af2ff1cf22..af234f76b7 100644 --- a/UnitsNet/QuantityFormatter.cs +++ b/UnitsNet/QuantityFormatter.cs @@ -121,10 +121,16 @@ public string Format(TQuantity quantity, string? format = null, IForm { switch (format[0]) { - case 'G' or 'g': - return FormatWithValueAndAbbreviation(quantity, format, formatProvider); - case 'S' or 's': - return ToStringWithSignificantDigitsAfterRadix(quantity, formatProvider, 0); + case 'S': + { + format = "S15"; + break; + } + case 's': + { + format = "s15"; + break; + } case 'A' or 'a': return _unitAbbreviations.GetDefaultAbbreviation(quantity.UnitKey, formatProvider); case 'U' or 'u': @@ -144,8 +150,6 @@ public string Format(TQuantity quantity, string? format = null, IForm switch (format[0]) { #if NET - case 'S' or 's' when int.TryParse(format.AsSpan(1), out var precisionSpecifier): - return ToStringWithSignificantDigitsAfterRadix(quantity, formatProvider, precisionSpecifier); case 'A' or 'a' when int.TryParse(format.AsSpan(1), out var abbreviationIndex): { IReadOnlyList abbreviations = _unitAbbreviations.GetUnitAbbreviations(quantity.UnitKey, formatProvider); @@ -162,8 +166,6 @@ public string Format(TQuantity quantity, string? format = null, IForm case 'P' or 'p' when int.TryParse(format.AsSpan(1), out _): throw new FormatException($"The \"{format}\" (percent) format is not supported."); #else - case 'S' or 's' when int.TryParse(format.Substring(1), out var precisionSpecifier): - return ToStringWithSignificantDigitsAfterRadix(quantity, formatProvider, precisionSpecifier); case 'A' or 'a' when int.TryParse(format.Substring(1), out var abbreviationIndex): { IReadOnlyList abbreviations = _unitAbbreviations.GetUnitAbbreviations(quantity.UnitKey, formatProvider); @@ -182,14 +184,7 @@ public string Format(TQuantity quantity, string? format = null, IForm #endif } } - - // Anything else is a standard numeric format string with default unit abbreviation postfix. - return FormatWithValueAndAbbreviation(quantity, format, formatProvider); - } - - private string FormatWithValueAndAbbreviation(TQuantity quantity, string format, IFormatProvider formatProvider) - where TQuantity : IQuantity - { + var abbreviation = _unitAbbreviations.GetDefaultAbbreviation(quantity.UnitKey, formatProvider); if (abbreviation.Length == 0) { @@ -203,13 +198,4 @@ private string FormatWithValueAndAbbreviation(TQuantity quantity, str return quantity.Value.ToString(format, formatProvider) + ' ' + abbreviation; #endif } - - private string ToStringWithSignificantDigitsAfterRadix(TQuantity quantity, IFormatProvider formatProvider, int number) - where TQuantity : IQuantity - { - var formatForSignificantDigits = UnitFormatter.GetFormat(quantity.Value, number); - var abbreviation = _unitAbbreviations.GetDefaultAbbreviation(quantity.UnitKey, formatProvider); - var formatArgs = UnitFormatter.GetFormatArgs(quantity.Value, abbreviation, formatProvider, []); - return string.Format(formatProvider, formatForSignificantDigits, formatArgs).TrimEnd(); - } } diff --git a/UnitsNet/QuantityInfo.cs b/UnitsNet/QuantityInfo.cs index bcddfb60a0..afea5c2a02 100644 --- a/UnitsNet/QuantityInfo.cs +++ b/UnitsNet/QuantityInfo.cs @@ -107,7 +107,7 @@ public IEnumerable GetUnitInfosFor(BaseUnits baseUnits) /// An instance of representing the specified value and unit. /// Thrown when is null. /// Thrown when is not a valid unit for this quantity. - internal abstract IQuantity From(double value, UnitKey unitKey); + internal abstract IQuantity From(QuantityValue value, UnitKey unitKey); /// public override string ToString() @@ -190,13 +190,13 @@ public UnitInfo this[TUnit unit] } /// - public IQuantity From(double value, TUnit unit) + public IQuantity From(QuantityValue value, TUnit unit) { return CreateGenericQuantity(value, unit); } - /// - protected internal abstract IQuantity CreateGenericQuantity(double value, TUnit unit); + /// + protected internal abstract IQuantity CreateGenericQuantity(QuantityValue value, TUnit unit); #endregion @@ -233,7 +233,7 @@ public override UnitInfo this[UnitKey unit] } /// - internal override IQuantity From(double value, UnitKey unitKey) + internal override IQuantity From(QuantityValue value, UnitKey unitKey) { return From(value, unitKey.ToUnit()); } @@ -303,13 +303,13 @@ protected QuantityInfoBase(string name, TQuantity zero, BaseDimensions baseDimen /// The numerical value of the quantity. /// The unit of the quantity. /// An instance of representing the specified value and unit. - public new TQuantity From(double value, TUnit unit) + public new TQuantity From(QuantityValue value, TUnit unit) { return FromDelegate(value, unit); } /// - TQuantity IQuantityInstanceInfo.Create(double value, UnitKey unitKey) + TQuantity IQuantityInstanceInfo.Create(QuantityValue value, UnitKey unitKey) { return From(value, unitKey.ToUnit()); } @@ -343,7 +343,7 @@ protected internal override UnitInfo GetUnitInfo(TUnit unit) } /// - protected internal override IQuantity CreateGenericQuantity(double value, TUnit unit) + protected internal override IQuantity CreateGenericQuantity(QuantityValue value, TUnit unit) { return From(value, unit); } @@ -361,7 +361,7 @@ public class QuantityInfo : QuantityInfoBase> _unitMappings; - + #if NET /// @@ -400,12 +400,12 @@ public QuantityInfo(TUnit baseUnit, IEnumerable> unitMapp /// public QuantityInfo(string name, TUnit baseUnit, IEnumerable> unitMappings, BaseDimensions baseDimensions, ResourceManager? unitAbbreviations = null) - : this(name, baseUnit, unitMappings, TQuantity.From(0, baseUnit), baseDimensions, TQuantity.From, unitAbbreviations) + : this(name, baseUnit, unitMappings, TQuantity.From(QuantityValue.Zero, baseUnit), baseDimensions, TQuantity.From, unitAbbreviations) { } #endif - + /// /// Initializes a new instance of the class using the default quantity /// name. @@ -444,7 +444,7 @@ public QuantityInfo(TUnit baseUnit, IEnumerable> unitMapp /// public QuantityInfo(string name, TUnit baseUnit, IEnumerable> unitMappings, BaseDimensions baseDimensions, QuantityFromDelegate fromDelegate, ResourceManager? unitAbbreviations = null) - : this(name, baseUnit, unitMappings, fromDelegate(0, baseUnit), baseDimensions, fromDelegate, unitAbbreviations) + : this(name, baseUnit, unitMappings, fromDelegate(QuantityValue.Zero, baseUnit), baseDimensions, fromDelegate, unitAbbreviations) { } diff --git a/UnitsNet/QuantityInfoLookup.cs b/UnitsNet/QuantityInfoLookup.cs index 5aa7843f93..6b4a68f1b3 100644 --- a/UnitsNet/QuantityInfoLookup.cs +++ b/UnitsNet/QuantityInfoLookup.cs @@ -99,6 +99,18 @@ public QuantityInfoLookup(IEnumerable quantityInfos) /// public IReadOnlyList Infos => _quantities; + internal static QuantityInfoLookup Create(IEnumerable defaultQuantities, Action configureQuantities) + { + var selector = new QuantitiesSelector(() => defaultQuantities); + configureQuantities(selector); + return Create(selector); + } + + internal static QuantityInfoLookup Create(QuantitiesSelector selector) + { + return new QuantityInfoLookup(selector.GetQuantityInfos()); + } + /// /// Retrieves the associated with the specified quantity type. /// @@ -167,7 +179,7 @@ public bool TryGetUnitInfo(UnitKey unitKey, [NotNullWhen(true)] out UnitInfo? un /// Unit enum value. /// An object. /// Unit value is not a know unit enum type. - public IQuantity From(double value, UnitKey unit) + public IQuantity From(QuantityValue value, UnitKey unit) { return GetUnitInfo(unit).From(value); } @@ -184,14 +196,14 @@ public IQuantity From(double value, UnitKey unit) /// /// true if the quantity was successfully created; otherwise, false. /// - public bool TryFrom(double value, [NotNullWhen(true)] Enum? unit, [NotNullWhen(true)] out IQuantity? quantity) + public bool TryFrom(QuantityValue value, [NotNullWhen(true)] Enum? unit, [NotNullWhen(true)] out IQuantity? quantity) { if (unit == null) { quantity = null; return false; } - + if (!TryGetUnitInfo(unit, out UnitInfo? unitInfo)) { quantity = null; diff --git a/UnitsNet/QuantityTypeConverter.cs b/UnitsNet/QuantityTypeConverter.cs index ad4350abef..1500ae6e42 100644 --- a/UnitsNet/QuantityTypeConverter.cs +++ b/UnitsNet/QuantityTypeConverter.cs @@ -153,11 +153,12 @@ private static TAttribute? GetAttribute< // Ensure the attribute's unit is compatible with this converter's quantity. if (attribute?.UnitType != null) { - string converterQuantityName = default(TQuantity).QuantityInfo.Name; - string attributeQuantityName = Quantity.From(1, attribute.UnitType).QuantityInfo.Name; - if (converterQuantityName != attributeQuantityName) + Type declaredUnitType = attribute.UnitType.GetType(); + QuantityInfo quantityInfo = default(TQuantity).QuantityInfo; + if (declaredUnitType != quantityInfo.UnitType) { - throw new ArgumentException($"The {attribute.GetType()}'s UnitType [{attribute.UnitType}] is not compatible with the converter's quantity [{converterQuantityName}]."); + throw new ArgumentException( + $"The {attribute.GetType()}'s UnitType [{declaredUnitType}] is not compatible with the converter's quantity [{quantityInfo.Name}]."); } } @@ -165,36 +166,48 @@ private static TAttribute? GetAttribute< } /// - /// Converts the given object, when it is of type to the type of this converter, using the specified context and culture information. + /// Converts the given object, when it is of type to the type of this converter, using the + /// specified context and culture information. /// /// An System.ComponentModel.ITypeDescriptorContext that provides a format context. /// The System.Globalization.CultureInfo to use as the current culture. /// The System.Object to convert. - /// An object. + /// An object. + /// + /// Thrown when the unit defined by the is not is not compatible with the + /// converter's quantity. + /// + /// + /// Thrown when the specified quantity type is not registered in the current configuration. + /// + /// Unit value is not a known unit enum type. /// The conversion cannot be performed. - /// Unit value is not a know unit enum type. public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) { if (value is string stringValue && !string.IsNullOrEmpty(stringValue)) { IQuantity? quantity = null; - if (double.TryParse(stringValue, NumberStyles.Any, culture, out double dvalue)) + if (QuantityValue.TryParse(stringValue, NumberStyles.Any, culture, out QuantityValue quantityValue)) { - var defaultUnit = GetAttribute(context) ?? new DefaultUnitAttribute(default(TQuantity).Unit); - if(defaultUnit.UnitType != null) - quantity = Quantity.From(dvalue, defaultUnit.UnitType); + DefaultUnitAttribute defaultUnit = GetAttribute(context) ?? new DefaultUnitAttribute(default(TQuantity).Unit); + if (defaultUnit.UnitType != null) + { + quantity = Quantity.From(quantityValue, defaultUnit.UnitType); + } } else { quantity = Quantity.Parse(culture, typeof(TQuantity), stringValue); } - if( quantity != null) + if (quantity != null) { ConvertToUnitAttribute? convertToUnit = GetAttribute(context); - if (convertToUnit != null && convertToUnit.UnitType != null) - quantity = quantity.ToUnit(convertToUnit.UnitType); + if (convertToUnit?.UnitType is {} targetUnit) + { + quantity = UnitConverter.Default.ConvertTo(quantity, targetUnit); + } return quantity; } @@ -239,7 +252,7 @@ public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destina return quantity.ToString(displayAsUnit.Format, culture); } - return quantity.ToUnit(displayAsUnit.UnitType).ToString(displayAsUnit.Format, culture); + return UnitConverter.Default.ConvertTo(quantity, displayAsUnit.UnitType).ToString(displayAsUnit.Format, culture); } } } diff --git a/UnitsNet/Serialization/QuantityValueSurrogate.cs b/UnitsNet/Serialization/QuantityValueSurrogate.cs new file mode 100644 index 0000000000..8b2a568c85 --- /dev/null +++ b/UnitsNet/Serialization/QuantityValueSurrogate.cs @@ -0,0 +1,31 @@ +using System.Runtime.Serialization; + +// ReSharper disable once CheckNamespace +namespace UnitsNet; + +/// +/// Represents a surrogate for serializing and deserializing quantity values. +/// +[DataContract] +internal class QuantityValueSurrogate +{ + /// + /// Gets or sets the numerator part of the quantity value. + /// + /// + /// A string representing the numerator of the quantity value. + /// + /// When omitted, the value is assumed to be "0". + [DataMember(Order = 1, IsRequired = false, EmitDefaultValue = false, Name = "N")] + public string? Numerator { get; set; } + + /// + /// Gets or sets the denominator part of the quantity value. + /// + /// + /// The denominator as a string. + /// + /// When omitted, the value is assumed to be "1". + [DataMember(Order = 2, IsRequired = false, EmitDefaultValue = false, Name = "D")] + public string? Denominator { get; set; } +} diff --git a/UnitsNet/Serialization/QuantityValueSurrogateSerializationProvider.cs b/UnitsNet/Serialization/QuantityValueSurrogateSerializationProvider.cs new file mode 100644 index 0000000000..d1b5aa431c --- /dev/null +++ b/UnitsNet/Serialization/QuantityValueSurrogateSerializationProvider.cs @@ -0,0 +1,92 @@ +// 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 System.Globalization; +using System.Numerics; +using System.Runtime.Serialization; + +namespace UnitsNet.Serialization; + +/// +/// Provides serialization and deserialization functionality for objects. +/// +public sealed class QuantityValueSurrogateSerializationProvider : ISerializationSurrogateProvider +{ + /// + /// Gets the singleton instance of the . + /// + public static readonly ISerializationSurrogateProvider Instance = new QuantityValueSurrogateSerializationProvider(); + + private QuantityValueSurrogateSerializationProvider() + { + } + + /// + /// Deserializes an object of type into a . + /// + /// The object to deserialize, expected to be of type . + /// The target type for deserialization, expected to be . + /// + /// A deserialized object if the input object is of type + /// ; + /// otherwise, returns the input object. + /// + /// + /// Thrown when the numerator or denominator in the cannot be parsed into a + /// . + /// + public object GetDeserializedObject(object obj, Type targetType) + { + if (obj is not QuantityValueSurrogate quantityValueSurrogate) + { + return obj; + } + + BigInteger numerator = quantityValueSurrogate.Numerator == null + ? BigInteger.Zero + : BigInteger.Parse(quantityValueSurrogate.Numerator, CultureInfo.InvariantCulture); + BigInteger denominator = quantityValueSurrogate.Denominator == null + ? BigInteger.One + : BigInteger.Parse(quantityValueSurrogate.Denominator, CultureInfo.InvariantCulture); + return new QuantityValue(numerator, denominator); + } + + /// + /// Converts a object to a object for serialization + /// purposes. + /// + /// The object to be serialized, expected to be of type . + /// The type of the target object, which is ignored in this implementation. + /// + /// A object containing the serialized data of the + /// object. + /// If the input object is not of type , the original object is returned. + /// + public object GetObjectToSerialize(object obj, Type targetType) + { + if (obj is not QuantityValue quantityValue) + { + return obj; + } + + (BigInteger numerator, BigInteger denominator) = quantityValue; + return new QuantityValueSurrogate + { + Numerator = numerator.IsZero ? null : numerator.ToString(CultureInfo.InvariantCulture), + Denominator = denominator.IsOne ? null : denominator.ToString(CultureInfo.InvariantCulture) + }; + } + + /// + /// Retrieves the surrogate type for the specified type. + /// + /// The type for which to get the surrogate type. + /// + /// The surrogate type if the specified type is ; otherwise, the original type. + /// + public Type GetSurrogateType(Type type) + { + return type == typeof(QuantityValue) ? typeof(QuantityValueSurrogate) : type; + } +} diff --git a/UnitsNet/UnitConverter.cs b/UnitsNet/UnitConverter.cs index e32b1bb26b..5fd35c4b24 100644 --- a/UnitsNet/UnitConverter.cs +++ b/UnitsNet/UnitConverter.cs @@ -1,555 +1,1202 @@ // 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.Collections.Concurrent; +using System; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; +using System.Linq; using UnitsNet.InternalHelpers; -namespace UnitsNet +#if NET +using System.Collections.Frozen; +#endif + +namespace UnitsNet; + +/// +/// Convert between units of a quantity, such as converting from meters to centimeters of a given length. +/// +public class UnitConverter { - using ConversionFunctionLookupKey = ValueTuple; + #if NET + private readonly FrozenSet _quantityConversions; + #else + private readonly HashSet _quantityConversions; + #endif /// - /// + /// Initializes a new instance of the class with the specified + /// . /// - /// - /// - public delegate IQuantity ConversionFunction(IQuantity inputValue); + /// The used for parsing units. + public UnitConverter(UnitParser unitParser) + : this(unitParser, unitParser.Quantities.GetQuantityConversions(Quantity.DefaultProvider.Conversions)) + { + UnitParser = unitParser; + } + + internal UnitConverter(UnitParser unitParser, IEnumerable quantityConversions) + { + UnitParser = unitParser; +#if NET + _quantityConversions = quantityConversions.ToFrozenSet(); +#else + _quantityConversions = [..quantityConversions]; +#endif + } + /// - /// + /// Gets the instance used to parse unit abbreviations. /// - /// - /// - /// - public delegate TQuantity ConversionFunction(TQuantity inputValue) - where TQuantity : IQuantity; + private UnitParser UnitParser { get; } /// - /// Convert between units of a quantity, such as converting from meters to centimeters of a given length. + /// Gets the lookup for quantity information, which provides access to details about available quantities, + /// their associated units, and related metadata. /// - public sealed class UnitConverter + /// + /// It enables retrieval of unit and quantity information for conversion operations. + /// + public QuantityInfoLookup Quantities { - /// - /// The default singleton instance for converting values from one unit to another.
- /// Modify this to add/remove conversion functions at runtime, such as adding your own third-party units and quantities to convert between. - ///
- /// - /// Convenience shortcut for ... - /// - public static UnitConverter Default => UnitsNetSetup.Default.UnitConverter; + get => UnitParser.Quantities; + } - /// - /// Creates a new instance. - /// - public UnitConverter() + /// + /// Gets the default instance of the class. + /// + /// + /// The default instance configured by . + /// + public static UnitConverter Default => UnitsNetSetup.Default.UnitConverter; + + /// + /// Creates a new instance of the class. + /// + /// The parser used to interpret unit abbreviations and symbols. + /// + /// Options for building the quantity converter, including whether to freeze + /// the converter. + /// + /// A new instance of configured according to the provided options. + /// + /// If specifies freezing, a + /// is created. + /// Otherwise, a is created. + /// + /// + /// Thrown when failing to create a conversion expression for one of the user-specified quantity-conversions. + /// + public static UnitConverter Create(UnitParser unitParser, QuantityConverterBuildOptions options) + { + if (options is { DefaultCachingMode: ConversionCachingMode.None, CustomQuantityOptions.Count: 0, QuantityConversionOptions: null, Freeze: true }) { - ConversionFunctions = new ConcurrentDictionary(); + return new NoCachingConverter(unitParser); // this is just a sealed version of the default converter } - /// - /// Creates a new instance with the copied from . - /// - /// The to copy from. - public UnitConverter(UnitConverter other) + QuantityInfoLookup quantityLookup = unitParser.Quantities; + IEnumerable> unitConversionFunctions = + quantityLookup.Infos.GetUnitConversionFunctions(options.DefaultCachingMode, options.ReduceConstants, options.CustomQuantityOptions); + + var quantityConversions = new HashSet(quantityLookup.GetQuantityConversions(Quantity.DefaultProvider.Conversions)); + + IEnumerable> quantityConversionFunctions; + if (options.QuantityConversionOptions is { } customConversionOptions) + { + Dictionary conversionOptions = quantityLookup.GetQuantityConversionMappingOptions(customConversionOptions); + quantityConversions.UnionWith(quantityLookup.GetQuantityConversions(customConversionOptions.CustomConversions).Concat(conversionOptions.Keys)); + quantityConversionFunctions = quantityConversions.GetConversionFunctions(conversionOptions, options.DefaultCachingMode, options.ReduceConstants, options.CustomQuantityOptions); + } + else + { + quantityConversionFunctions = quantityConversions.GetConversionFunctions(options.DefaultCachingMode, options.ReduceConstants, options.CustomQuantityOptions); + } + + if (options.Freeze) { - ConversionFunctions = new ConcurrentDictionary(other.ConversionFunctions); + return new FrozenQuantityConverter(unitParser, quantityConversions, unitConversionFunctions, quantityConversionFunctions); } - /// - /// Create an instance of the unit converter with all the built-in unit conversions defined in the library. - /// - /// The unit converter. - public static UnitConverter CreateDefault() + return new DynamicQuantityConverter(unitParser, quantityConversions, unitConversionFunctions, quantityConversionFunctions, options.ReduceConstants); + } + + /// + /// Attempts to convert the specified quantity to the specified unit. + /// + /// The quantity to convert. Must not be null. + /// The unit to convert the quantity to. + /// + /// When this method returns, contains the converted quantity if the conversion succeeded, or null if the + /// conversion failed. + /// + /// + /// true if the conversion succeeded; otherwise, false. + /// + public bool TryConvertTo(TQuantity quantity, UnitKey toUnitKey, [NotNullWhen(true)] out IQuantity? convertedQuantity) + where TQuantity : IQuantity + { + QuantityInfo quantityInfo = quantity.QuantityInfo; + if (quantityInfo.UnitType == toUnitKey.UnitEnumType) + { + if (TryConvertValue(quantity.Value, quantity.UnitKey, toUnitKey, out QuantityValue convertedValue)) + { + convertedQuantity = quantityInfo.From(convertedValue, toUnitKey); + return true; + } + } + else if (TryGetUnitInfo(quantity.UnitKey, out UnitInfo? fromUnitInfo) && TryGetUnitInfo(toUnitKey, out UnitInfo? toUnitInfo) && + TryConvertValueInternal(quantity.Value, fromUnitInfo, toUnitInfo, out QuantityValue convertedValue)) { - var unitConverter = new UnitConverter(); - RegisterDefaultConversions(unitConverter); + convertedQuantity = toUnitInfo.From(convertedValue); + return true; + } + + convertedQuantity = null; + return false; + } - return unitConverter; + /// + /// Attempts to convert a quantity to a specified unit. + /// + /// The type of the quantity. + /// The type of the unit. + /// The quantity to convert. + /// The unit to convert to. + /// + /// When this method returns, contains the converted quantity if the conversion succeeded, or null if the + /// conversion failed. + /// + /// + /// true if the conversion succeeded; otherwise, false. + /// + public bool TryConvertToUnit(TQuantity quantity, TUnit toUnit, [NotNullWhen(true)] out TQuantity? convertedQuantity) + where TQuantity : IQuantity + where TUnit : struct, Enum + { + if (TryConvertValue(quantity.Value, quantity.Unit, toUnit, out QuantityValue convertedValue)) + { + convertedQuantity = quantity.QuantityInfo.From(convertedValue, toUnit); + return true; } - private ConcurrentDictionary ConversionFunctions + convertedQuantity = default; + return false; + } + + /// + /// Attempts to retrieve information about a specified unit. + /// + /// The unit for which information is being requested. + /// + /// When this method returns, contains the unit information associated with the specified unit, + /// if the unit is found; otherwise, null. This parameter is passed uninitialized. + /// + /// + /// true if the unit information was found; otherwise, false. + /// + protected bool TryGetUnitInfo(UnitKey unit, [NotNullWhen(true)] out UnitInfo? unitInfo) + { + return Quantities.TryGetUnitInfo(unit, out unitInfo); + } + + /// + /// Determines whether a conversion is defined between the specified source and target quantities. + /// + /// The source quantity information. + /// The target quantity information. + /// + /// true if a conversion is defined between the source and target quantities; otherwise, false. + /// + protected bool ConversionDefined(QuantityInfo sourceQuantity, QuantityInfo targetQuantity) + { + return _quantityConversions.Contains(new QuantityConversion(sourceQuantity, targetQuantity)); + } + + /// + /// Gets the collection of quantity conversions available in this . + /// + /// + /// A quantity conversion defines the relationship between two quantities, enabling conversions + /// between them. This property provides access to all such conversions configured for this instance. + /// + internal IReadOnlyCollection QuantityConversions => _quantityConversions; + + /// + /// Attempts to convert the specified quantity to a different unit. + /// + /// The type of the quantity to be converted. + /// The type of the unit to convert to. + /// The quantity to be converted. + /// The unit to convert the quantity to. + /// + /// When this method returns, contains the converted value if the conversion succeeded; otherwise, the default value + /// for the type of the converted value. + /// + /// + /// true if the conversion succeeded; otherwise, false. + /// + public bool TryConvertValue(TQuantity quantity, TUnit toUnit, out QuantityValue convertedValue) + where TQuantity : IQuantity + where TUnit : struct, Enum + { + return TryConvertValue(quantity.Value, quantity.Unit, toUnit, out convertedValue); + } + + /// + /// Attempts to convert a quantity value from one unit to another. + /// + /// The type of the unit enumeration. + /// The quantity value to be converted. + /// The unit of the quantity value to convert from. + /// The unit of the quantity value to convert to. + /// + /// When this method returns, contains the converted quantity value if the conversion succeeded, + /// or null if the conversion failed. This parameter is passed uninitialized. + /// + /// + /// true if the conversion succeeded; otherwise, false. + /// + public virtual bool TryConvertValue(QuantityValue value, TUnit fromUnit, TUnit toUnit, out QuantityValue convertedValue) + where TUnit : struct, Enum + { + var fromUnitKey = UnitKey.ForUnit(fromUnit); + var toUnitKey = UnitKey.ForUnit(toUnit); + if (fromUnitKey == toUnitKey) { - get; + convertedValue = value; + return true; } + + if (TryGetUnitInfo(fromUnitKey, out UnitInfo? fromUnitInfo) && TryGetUnitInfo(toUnitKey, out UnitInfo? toUnitInfo)) + { + convertedValue = toUnitInfo.GetValueFrom(value, fromUnitInfo); + return true; + } + + convertedValue = default; + return false; + } - /// - /// Registers the default conversion functions in the given instance. - /// - /// The to register the default conversion functions in. - private static void RegisterDefaultConversions(UnitConverter unitConverter) + /// + /// Attempts to convert a quantity value from one unit to another. + /// + /// The value to be converted. + /// The unit of the value to be converted from. + /// The unit of the value to be converted to. + /// + /// When this method returns, contains the converted value if the conversion succeeded, + /// or null if the conversion failed. This parameter is passed uninitialized. + /// + /// + /// true if the conversion succeeded; otherwise, false. + /// + public virtual bool TryConvertValue(QuantityValue value, UnitKey fromUnitKey, UnitKey toUnitKey, out QuantityValue convertedValue) + { + if (fromUnitKey == toUnitKey) + { + convertedValue = value; + return true; + } + + if (TryGetUnitInfo(fromUnitKey, out UnitInfo? fromUnitInfo) && TryGetUnitInfo(toUnitKey, out UnitInfo? toUnitInfo)) { - if (unitConverter is null) throw new ArgumentNullException(nameof(unitConverter)); + return TryConvertValueInternal(value, fromUnitInfo, toUnitInfo, out convertedValue); + } + + convertedValue = default; + return false; + } - Quantity.DefaultProvider.RegisterUnitConversions(unitConverter); + /// + /// Attempts to convert a quantity value from one unit to another. + /// + /// The quantity value to convert. + /// The unit information of the source unit. + /// The unit information of the target unit. + /// + /// When this method returns, contains the converted quantity value if the conversion succeeded, + /// or null if the conversion failed. This parameter is passed uninitialized. + /// + /// + /// true if the conversion succeeded; otherwise, false. + /// + /// + /// This method should succeed for any two units of the same quantity, but may fail if the units are from two + /// incompatible quantities. + /// + protected virtual bool TryConvertValueInternal(QuantityValue value, UnitInfo fromUnitInfo, UnitInfo toUnitInfo, out QuantityValue convertedValue) + { + if (fromUnitInfo.QuantityInfo != toUnitInfo.QuantityInfo) + { + return TryConvertValueFromOneQuantityToAnother(value, fromUnitInfo, toUnitInfo, out convertedValue); } - /// - /// Sets the conversion function from two units of the same quantity type. - /// - /// The type of quantity, must implement . - /// From unit enum value, such as . - /// To unit enum value, such as . - /// The quantity conversion function. - public void SetConversionFunction(Enum from, Enum to, ConversionFunction conversionFunction) - where TQuantity : IQuantity + convertedValue = toUnitInfo.GetValueFrom(value, fromUnitInfo); + return true; + } + + /// + /// Attempts to convert a value from one quantity to another. + /// + /// The value to be converted. + /// The unit of the value to be converted. + /// The unit to which the value should be converted. + /// The converted value if the conversion is successful; otherwise, the default value. + /// + /// true if the conversion is successful; otherwise, false. + /// + /// + /// This method handles conversions between quantities with matching or inverse base dimensions. + /// + protected bool TryConvertValueFromOneQuantityToAnother(QuantityValue value, UnitInfo fromUnit, UnitInfo toUnit, out QuantityValue convertedValue) + { + QuantityInfo sourceQuantity = fromUnit.QuantityInfo; + QuantityInfo targetQuantity = toUnit.QuantityInfo; + if (!ConversionDefined(sourceQuantity, targetQuantity)) + { + convertedValue = default; + return false; + } + + ConvertValueDelegate conversionExpression; + if (sourceQuantity.BaseDimensions.IsInverseOf(targetQuantity.BaseDimensions)) + { + conversionExpression = QuantityValue.Inverse; + } + else if (sourceQuantity.BaseDimensions == targetQuantity.BaseDimensions) + { + if (sourceQuantity.BaseDimensions.IsDimensionless()) + { + convertedValue = toUnit.ConvertValueFromBaseUnit(fromUnit.ConvertValueToBaseUnit(value)); + return true; + } + + conversionExpression = sourceValue => sourceValue; + } + else { - var quantityType = typeof(TQuantity); - var conversionLookup = new ConversionFunctionLookupKey(quantityType, from, quantityType, to); - SetConversionFunction(conversionLookup, conversionFunction); + convertedValue = default; + return false; } - /// - /// Sets the conversion function from two units of different quantity types. - /// - /// From quantity type, must implement . - /// To quantity type, must implement . - /// From unit enum value, such as . - /// To unit enum value, such as . - /// The quantity conversion function. - public void SetConversionFunction(Enum from, Enum to, ConversionFunction conversionFunction) - where TQuantityFrom : IQuantity - where TQuantityTo : IQuantity + if (fromUnit.BaseUnits != BaseUnits.Undefined) + { + if (toUnit.BaseUnits == fromUnit.BaseUnits) + { + convertedValue = conversionExpression(value); + return true; + } + + if (targetQuantity.UnitInfos.TryGetUnitWithBase(fromUnit.BaseUnits, out UnitInfo? matchingUnit)) + { + convertedValue = ConvertValueInternal(conversionExpression(value), matchingUnit, toUnit); + return true; + } + + UnitInfo fromBaseUnit = sourceQuantity.BaseUnitInfo; + if (fromUnit.BaseUnits != fromBaseUnit.BaseUnits && fromBaseUnit.BaseUnits != BaseUnits.Undefined) + { + if (toUnit.QuantityInfo.BaseUnitInfo.BaseUnits == fromBaseUnit.BaseUnits) + { + convertedValue = toUnit.ConvertValueFromBaseUnit(conversionExpression(fromUnit.ConversionToBase.Evaluate(value))); + return true; + } + } + } + else if (toUnit.BaseUnits != BaseUnits.Undefined) { - SetConversionFunction(typeof(TQuantityFrom), from, typeof(TQuantityTo), to, conversionFunction); + if (sourceQuantity.UnitInfos.TryGetUnitWithBase(toUnit.BaseUnits, out UnitInfo? matchingUnit)) + { + convertedValue = conversionExpression(ConvertValueInternal(value, fromUnit, matchingUnit)); + return true; + } + + UnitInfo toBaseUnit = targetQuantity.BaseUnitInfo; + if (toUnit.BaseUnits != toBaseUnit.BaseUnits && toBaseUnit.BaseUnits != BaseUnits.Undefined) + { + if (sourceQuantity.BaseUnitInfo.BaseUnits == toBaseUnit.BaseUnits) + { + convertedValue = toUnit.ConversionFromBase.Evaluate(conversionExpression(fromUnit.ConvertValueToBaseUnit(value))); + return true; + } + } } - /// - /// Sets the conversion function from two units of different quantity types. - /// - /// From quantity type, must implement . - /// From unit enum value, such as . - /// To quantity type, must implement . - /// To unit enum value, such as . - /// The quantity conversion function. - public void SetConversionFunction(Type fromType, Enum from, Type toType, Enum to, ConversionFunction conversionFunction) + foreach (UnitInfo sourceUnit in sourceQuantity.UnitInfos) { - var conversionLookup = new ConversionFunctionLookupKey(fromType, from, toType, to); - SetConversionFunction(conversionLookup, conversionFunction); + if (sourceUnit.BaseUnits == BaseUnits.Undefined || sourceUnit.BaseUnits == fromUnit.BaseUnits) + { + continue; + } + + if (targetQuantity.UnitInfos.TryGetUnitWithBase(sourceUnit.BaseUnits, out UnitInfo? matchingUnit)) + { + convertedValue = ConvertValueInternal(conversionExpression(ConvertValueInternal(value, fromUnit, sourceUnit)), matchingUnit, toUnit); + return true; + } } - /// - /// Sets the conversion function for a particular conversion function lookup. - /// - /// The lookup key. - /// The quantity conversion function. - internal void SetConversionFunction(ConversionFunctionLookupKey lookupKey, ConversionFunction conversionFunction) + convertedValue = default; + return false; + } + + /// + /// Attempts to convert a quantity value from a source unit to a target quantity type and unit. + /// + /// The type of the source unit enumeration. + /// The type of the target quantity. + /// The type of the target unit enumeration. + /// The quantity value to convert. + /// The source unit of the quantity value. + /// The information about the target quantity type and unit. + /// + /// When this method returns, contains the converted quantity if the conversion succeeded, or null if the + /// conversion failed. + /// + /// true if the conversion succeeded; otherwise, false. + public virtual bool TryConvertTo(QuantityValue value, TSourceUnit fromUnit, + QuantityInfo targetQuantityInfo, [MaybeNullWhen(false)] out TTargetQuantity convertedQuantity) + where TSourceUnit : struct, Enum + where TTargetQuantity : IQuantity + where TTargetUnit : struct, Enum + { + if (TryGetUnitInfo(UnitKey.ForUnit(fromUnit), out UnitInfo? fromUnitInfo) && ConversionDefined(fromUnitInfo.QuantityInfo, targetQuantityInfo)) { - ConversionFunctions[lookupKey] = conversionFunction; + return targetQuantityInfo.TryConvertFrom(value, fromUnitInfo, out convertedQuantity); } - /// - /// Sets the conversion function for a particular conversion function lookup. - /// - /// The quantity type, must implement . - /// The quantity conversion function lookup key. - /// The quantity conversion function. - internal void SetConversionFunction(ConversionFunctionLookupKey conversionLookup, ConversionFunction conversionFunction) - where TQuantity : IQuantity + convertedQuantity = default; + return false; + } + + /// + public virtual bool TryConvertTo(QuantityValue value, UnitKey fromUnitKey, QuantityInfo targetQuantityInfo, + [NotNullWhen(true)] out IQuantity? convertedQuantity) + { + if (TryGetUnitInfo(fromUnitKey, out UnitInfo? fromUnitInfo) && ConversionDefined(fromUnitInfo.QuantityInfo, targetQuantityInfo)) { - IQuantity TypelessConversionFunction(IQuantity quantity) => conversionFunction((TQuantity) quantity); + return targetQuantityInfo.TryConvertFrom(value, fromUnitInfo, out convertedQuantity); + } - ConversionFunctions[conversionLookup] = TypelessConversionFunction; + convertedQuantity = null; + return false; + } + + /// + /// Converts the quantity to the specified unit. + /// + /// The quantity to convert. Must not be null. + /// The unit to convert the quantity to. + /// When this method returns, contains the converted quantity if the conversion succeeded, or + /// null + /// if the + /// conversion failed. + /// + /// true if the conversion succeeded; otherwise, false. + /// + /// Thrown when no unit information is found for the specified enum value. + /// + /// Thrown when the conversion between the specified units is not possible. + /// + /// + /// This method should succeed for any two units of the same quantity, but may fail if the units are not found or are + /// found to be from two + /// incompatible quantities. + /// + public IQuantity ConvertTo(TQuantity quantity, UnitKey toUnitKey) + where TQuantity : IQuantity + { + QuantityInfo quantityInfo = quantity.QuantityInfo; + if (quantityInfo.UnitType == toUnitKey.UnitEnumType) + { + QuantityValue convertedValue = ConvertValue(quantity.Value, quantity.UnitKey, toUnitKey); + return quantityInfo.From(convertedValue, toUnitKey); + } + else + { + UnitInfo fromUnitInfo = GetUnitInfo(quantity.UnitKey); + UnitInfo toUnitInfo = GetUnitInfo(toUnitKey); + QuantityValue convertedValue = ConvertValueInternal(quantity.Value, fromUnitInfo, toUnitInfo); + return toUnitInfo.From(convertedValue); } + } + + /// + /// Converts a quantity from its current unit to the specified unit. + /// + /// + /// The type of the quantity being converted. Must implement . + /// + /// + /// The type of the unit to convert to. Must be an enumeration. + /// + /// + /// The quantity to be converted, including its value and current unit. + /// + /// + /// The target unit to which the quantity should be converted. + /// + /// + /// A new instance of representing the converted value in the specified unit. + /// + /// Thrown when an unknown unit is provided. + public TQuantity ConvertToUnit(TQuantity quantity, TUnit toUnit) + where TQuantity : IQuantity + where TUnit : struct, Enum + { + QuantityValue convertedValue = ConvertValue(quantity.Value, quantity.Unit, toUnit); + return quantity.QuantityInfo.From(convertedValue, toUnit); + } + + /// + /// Retrieves information about a specific unit. + /// + /// The unit for which information is being requested. + /// An object containing details about the specified unit. + /// Thrown when the is null. + /// Thrown when the is not recognized. + protected UnitInfo GetUnitInfo(UnitKey unit) + { + return Quantities.GetUnitInfo(unit); + } + + /// + /// Converts the value of a quantity to a specified unit. + /// + /// The type of quantity to use as the source of the conversion. + /// The type of the unit to convert to. Must be a struct and an enum. + /// The quantity to convert. + /// The unit to convert the quantity to. + /// The converted quantity value. + /// Thrown when the is null. + /// Thrown when the conversion is not possible. + /// Thrown when is not found. + public QuantityValue ConvertValue(TQuantity quantity, TUnit toUnit) + where TQuantity : IQuantity + where TUnit : struct, Enum + { + return ConvertValue(quantity.Value, quantity.Unit, toUnit); + } - /// - /// Gets the conversion function from two units of the same quantity type. - /// - /// The quantity type, must implement . - /// From unit enum value, such as . - /// To unit enum value, such as . - /// - public ConversionFunction GetConversionFunction(Enum from, Enum to) where TQuantity : IQuantity + /// + /// Converts a quantity value from one unit to another using the specified quantity information. + /// + /// The type of the unit. + /// The value to be converted. + /// The unit of the value to be converted. + /// The unit to which the value should be converted. + /// Thrown when either or is not found. + /// The converted quantity value. + public virtual QuantityValue ConvertValue(QuantityValue value, TUnit fromUnit, TUnit toUnit) + where TUnit : struct, Enum + { + var fromUnitKey = UnitKey.ForUnit(fromUnit); + var toUnitKey = UnitKey.ForUnit(toUnit); + if (fromUnitKey.UnitEnumValue == toUnitKey.UnitEnumValue) { - return GetConversionFunction(typeof(TQuantity), from, typeof(TQuantity), to); + return value; } + + UnitInfo fromUnitInfo = GetUnitInfo(fromUnitKey); + UnitInfo toUnitInfo = GetUnitInfo(toUnitKey); + return toUnitInfo.GetValueFrom(value, fromUnitInfo); + } - /// - /// Gets the conversion function from two units of different quantity types. - /// - /// From quantity type, must implement . - /// To quantity type, must implement . - /// From unit enum value, such as . - /// To unit enum value, such as . - /// - public ConversionFunction GetConversionFunction(Enum from, Enum to) - where TQuantityFrom : IQuantity - where TQuantityTo : IQuantity - { - return GetConversionFunction(typeof(TQuantityFrom), from, typeof(TQuantityTo), to); - } - - /// - /// Gets the conversion function from two units of different quantity types. - /// - /// From quantity type, must implement . - /// From unit enum value, such as . - /// To quantity type, must implement . - /// To unit enum value, such as . - public ConversionFunction GetConversionFunction(Type fromType, Enum from, Type toType, Enum to) - { - var conversionLookup = new ConversionFunctionLookupKey(fromType, from, toType, to); - return GetConversionFunction(conversionLookup); - } - - /// - /// Gets the conversion function by its lookup key. - /// - /// - internal ConversionFunction GetConversionFunction(ConversionFunctionLookupKey lookupKey) - { - IQuantity EchoFunction(IQuantity fromQuantity) => fromQuantity; - - // If from/to units and to quantity types are equal, then return a function that echoes the input quantity - // in order to not have to map conversion functions to "self". - if (lookupKey.Item1 == lookupKey.Item3 && Equals(lookupKey.Item2, lookupKey.Item4)) - return EchoFunction; - - return ConversionFunctions[lookupKey]; - } - - /// - /// Gets the conversion function for two units of the same quantity type. - /// - /// The quantity type, must implement . - /// From unit enum value, such as . - /// To unit enum value, such as . - /// The quantity conversion function. - /// true if set; otherwise, false. - public bool TryGetConversionFunction(Enum from, Enum to, [NotNullWhen(true)] out ConversionFunction? conversionFunction) where TQuantity : IQuantity - { - return TryGetConversionFunction(typeof(TQuantity), from, typeof(TQuantity), to, out conversionFunction); - } - - /// - /// Gets the conversion function for two units of different quantity types. - /// - /// From quantity type, must implement . - /// To quantity type, must implement . - /// From unit enum value, such as . - /// To unit enum value, such as . - /// The quantity conversion function. - /// true if set; otherwise, false. - public bool TryGetConversionFunction(Enum from, Enum to, [NotNullWhen(true)] out ConversionFunction? conversionFunction) - where TQuantityFrom : IQuantity - where TQuantityTo : IQuantity - { - return TryGetConversionFunction(typeof(TQuantityFrom), from, typeof(TQuantityTo), to, out conversionFunction); - } - - /// - /// Try to get the conversion function for two units of the same quantity type. - /// - /// From quantity type, must implement . - /// From unit enum value, such as . - /// To quantity type, must implement . - /// To unit enum value, such as . - /// The quantity conversion function. - /// true if set; otherwise, false. - public bool TryGetConversionFunction(Type fromType, Enum from, Type toType, Enum to, [NotNullWhen(true)] out ConversionFunction? conversionFunction) - { - var conversionLookup = new ConversionFunctionLookupKey(fromType, from, toType, to); - return TryGetConversionFunction(conversionLookup, out conversionFunction); - } - - /// - /// - /// - /// - /// - /// true if set; otherwise, false. - public bool TryGetConversionFunction(ConversionFunctionLookupKey lookupKey, [NotNullWhen(true)] out ConversionFunction? conversionFunction) - { - return ConversionFunctions.TryGetValue(lookupKey, out conversionFunction); - } - - /// - /// Convert between any two quantity units given a numeric value and two unit enum values. - /// - /// Numeric value. - /// From unit enum value. - /// To unit enum value, must be compatible with . - /// The converted value in the new unit representation. - public static double Convert(double fromValue, Enum fromUnitValue, Enum toUnitValue) - { - return Quantity - .From(fromValue, fromUnitValue) - .As(toUnitValue); - } - - /// - /// Try to convert between any two quantity units given a numeric value and two unit enum values. - /// - /// Numeric value. - /// From unit enum value. - /// To unit enum value, must be compatible with . - /// The converted value, if successful. Otherwise default. - /// True if successful. - public static bool TryConvert(double fromValue, Enum fromUnitValue, Enum toUnitValue, out double convertedValue) - { - convertedValue = 0; - if (!Quantity.TryFrom(fromValue, fromUnitValue, out IQuantity? fromQuantity)) - return false; - - try + /// + /// Converts a quantity value from one unit to another using the specified quantity information. + /// + /// The value to be converted. + /// The unit of the value to be converted from. + /// The unit of the value to be converted to. + /// The converted quantity value. + /// Thrown when no unit information is found for the specified enum value. + /// + /// Thrown when the conversion between the specified units is not possible. + /// + /// + /// This method should succeed for any two units of the same quantity, but may fail if the units are not found or are + /// found to be from two + /// incompatible quantities. + /// + public virtual QuantityValue ConvertValue(QuantityValue value, UnitKey fromUnitKey, UnitKey toUnitKey) + { + if (fromUnitKey == toUnitKey) + { + return value; + } + + UnitInfo fromUnitInfo = GetUnitInfo(fromUnitKey); + UnitInfo toUnitInfo = GetUnitInfo(toUnitKey); + return ConvertValueInternal(value, fromUnitInfo, toUnitInfo); + } + + /// + /// Converts a quantity value from one unit to another. + /// + /// The quantity value to convert. + /// The unit information of the source unit. + /// The unit information of the target unit. + /// The converted quantity value. + /// + /// Thrown when the conversion between the specified units is not possible. + /// + /// + /// This method should succeed for any two units of the same quantity, but may fail if the units are from two + /// incompatible quantities. + /// + protected virtual QuantityValue ConvertValueInternal(QuantityValue value, UnitInfo fromUnitInfo, UnitInfo toUnitInfo) + { + return fromUnitInfo.QuantityInfo == toUnitInfo.QuantityInfo + ? toUnitInfo.GetValueFrom(value, fromUnitInfo) + : ConvertValueFromOneQuantityToAnother(value, fromUnitInfo, toUnitInfo); + } + + /// + /// Converts a value from one quantity to another, considering the units and their base dimensions. + /// + /// The value to be converted. + /// Information about the unit of the source quantity. + /// Information about the unit of the target quantity. + /// The converted value in the target quantity's unit. + /// + /// Thrown when no implicit conversion exists between the source and target quantities, + /// or when no compatible units are found for the conversion. + /// + /// + /// This method handles conversions between quantities with matching or inverse base dimensions. + /// + protected QuantityValue ConvertValueFromOneQuantityToAnother(QuantityValue value, UnitInfo fromUnitInfo, UnitInfo toUnitInfo) + { + QuantityInfo sourceQuantity = fromUnitInfo.QuantityInfo; + QuantityInfo targetQuantity = toUnitInfo.QuantityInfo; + if (!ConversionDefined(sourceQuantity, targetQuantity)) + { + throw InvalidConversionException.CreateImplicitConversionException(sourceQuantity, targetQuantity); + } + + ConvertValueDelegate conversionExpression; + if (sourceQuantity.BaseDimensions.IsInverseOf(targetQuantity.BaseDimensions)) + { + conversionExpression = QuantityValue.Inverse; + } + else if (sourceQuantity.BaseDimensions == targetQuantity.BaseDimensions) + { + if (sourceQuantity.BaseDimensions.IsDimensionless()) { - // We're not going to implement TryAs() in all quantities, so let's just try-catch here - convertedValue = fromQuantity.As(toUnitValue); - return true; + return toUnitInfo.ConvertValueFromBaseUnit(fromUnitInfo.ConvertValueToBaseUnit(value)); + } + + conversionExpression = sourceValue => sourceValue; + } + else + { + throw InvalidConversionException.CreateIncompatibleDimensionsException(sourceQuantity, targetQuantity); + } + + if (fromUnitInfo.BaseUnits != BaseUnits.Undefined) + { + if (toUnitInfo.BaseUnits == fromUnitInfo.BaseUnits) + { + return conversionExpression(value); } - catch + + if (targetQuantity.UnitInfos.TryGetUnitWithBase(fromUnitInfo.BaseUnits, out UnitInfo? matchingUnit)) { - return false; + return ConvertValueInternal(conversionExpression(value), matchingUnit, toUnitInfo); } - } - /// - /// Convert between any two quantity units by their names, such as converting a "Length" of N "Meter" to "Centimeter". - /// This is particularly useful for creating things like a generated unit conversion UI, - /// where you list some selectors: - /// a) Quantity: Length, Mass, Force etc. - /// b) From unit: Meter, Centimeter etc if Length is selected - /// c) To unit: Meter, Centimeter etc if Length is selected - /// - /// - /// Input value, which together with represents the quantity to - /// convert from. - /// - /// The invariant quantity name, such as "Length". Does not support localization. - /// The invariant unit enum name, such as "Meter". Does not support localization. - /// The invariant unit enum name, such as "Meter". Does not support localization. - /// double centimeters = ConvertByName(5, "Length", "Meter", "Centimeter"); // 500 - /// Output value as the result of converting to . - /// - /// Thrown when no quantity information is found for the specified quantity name. - /// - /// No units match the provided unit name. - /// More than one unit matches the abbreviation. - public static double ConvertByName(double fromValue, string quantityName, string fromUnitName, string toUnitName) - { - QuantityInfoLookup quantities = UnitsNetSetup.Default.Quantities; - UnitInfo fromUnit = quantities.GetUnitByName(quantityName, fromUnitName); - UnitInfo toUnit = quantities.GetUnitByName(quantityName, toUnitName); - return Quantity.From(fromValue, fromUnit.Value).As(toUnit.Value); - } - - /// - /// Convert between any two quantity units by their names, such as converting a "Length" of N "Meter" to "Centimeter". - /// This is particularly useful for creating things like a generated unit conversion UI, - /// where you list some selectors: - /// a) Quantity: Length, Mass, Force etc. - /// b) From unit: Meter, Centimeter etc if Length is selected - /// c) To unit: Meter, Centimeter etc if Length is selected - /// - /// - /// Input value, which together with represents the quantity to - /// convert from. - /// - /// The invariant quantity name, such as "Length". Does not support localization. - /// The invariant unit enum name, such as "Meter". Does not support localization. - /// The invariant unit enum name, such as "Meter". Does not support localization. - /// 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(double inputValue, string quantityName, string fromUnit, string toUnit, out double result) - { - QuantityInfoLookup quantities = UnitsNetSetup.Default.Quantities; - if (quantities.TryGetUnitByName(quantityName, fromUnit, out UnitInfo? fromUnitInfo) && - quantities.TryGetUnitByName(quantityName, toUnit, out UnitInfo? toUnitInfo) && - Quantity.TryFrom(inputValue, fromUnitInfo.Value, out IQuantity? quantity)) + UnitInfo fromBaseUnit = sourceQuantity.BaseUnitInfo; + if (fromUnitInfo.BaseUnits != fromBaseUnit.BaseUnits && fromBaseUnit.BaseUnits != BaseUnits.Undefined) { - result = quantity.As(toUnitInfo.Value); - return true; + if (toUnitInfo.QuantityInfo.BaseUnitInfo.BaseUnits == fromBaseUnit.BaseUnits) + { + return toUnitInfo.ConvertValueFromBaseUnit(conversionExpression(fromUnitInfo.ConversionToBase.Evaluate(value))); + } + } + } + else if (toUnitInfo.BaseUnits != BaseUnits.Undefined) + { + if (sourceQuantity.UnitInfos.TryGetUnitWithBase(toUnitInfo.BaseUnits, out UnitInfo? matchingUnit)) + { + return conversionExpression(ConvertValueInternal(value, fromUnitInfo, matchingUnit)); } - result = 0d; - return false; + UnitInfo toBaseUnit = targetQuantity.BaseUnitInfo; + if (toUnitInfo.BaseUnits != toBaseUnit.BaseUnits && toBaseUnit.BaseUnits != BaseUnits.Undefined) + { + if (sourceQuantity.BaseUnitInfo.BaseUnits == toBaseUnit.BaseUnits) + { + return toUnitInfo.ConversionFromBase.Evaluate(conversionExpression(fromUnitInfo.ConvertValueToBaseUnit(value))); + } + } } - /// - /// Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm". - /// This is particularly useful for creating things like a generated unit conversion UI, - /// where you list some selectors: - /// a) Quantity: Length, Mass, Force etc. - /// b) From unit: Meter, Centimeter etc if Length is selected - /// c) To unit: Meter, Centimeter etc if Length is selected - /// - /// - /// Input value, which together with represents the quantity to - /// convert from. - /// - /// The invariant quantity name, such as "Length". Does not support localization. - /// The abbreviation of the unit in the thread's current culture, such as "m". - /// The abbreviation of the unit in the thread's current culture, such as "m". - /// double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500 - /// Output value as the result of converting to . - /// - /// Thrown when no quantity information is found for the specified quantity name. - /// - /// No units match the abbreviation. - /// More than one unit matches the abbreviation. - public static double ConvertByAbbreviation(double fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev) - { - return ConvertByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, (IFormatProvider?)null); - } - - /// - /// Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm". - /// This is particularly useful for creating things like a generated unit conversion UI, - /// where you list some selectors: - /// a) Quantity: Length, Mass, Force etc. - /// b) From unit: Meter, Centimeter etc if Length is selected - /// c) To unit: Meter, Centimeter etc if Length is selected - /// - /// - /// Input value, which together with represents the quantity to - /// convert from. - /// - /// The invariant quantity name, such as "Length". Does not support localization. - /// The abbreviation of the unit in the given culture, such as "m". - /// The abbreviation of the unit in the given culture, such as "m". - /// Culture to parse abbreviations with. - /// double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500 - /// Output value as the result of converting to . - /// - /// Thrown when no quantity information is found for the specified quantity name. - /// - /// No units match the abbreviation. - /// More than one unit matches the abbreviation. - [Obsolete("Methods accepting a culture name are deprecated in favor of using an instance of the IFormatProvider.")] - public static double ConvertByAbbreviation(double fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, string? culture) - { - return ConvertByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, CultureHelper.GetCultureOrInvariant(culture)); - } - - /// - /// Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm". - /// This is particularly useful for creating things like a generated unit conversion UI, - /// where you list some selectors: - /// a) Quantity: Length, Mass, Force etc. - /// b) From unit: Meter, Centimeter etc if Length is selected - /// c) To unit: Meter, Centimeter etc if Length is selected - /// - /// - /// Input value, which together with represents the quantity to - /// convert from. - /// - /// The invariant quantity name, such as "Length". Does not support localization. - /// The abbreviation of the unit in the given culture, such as "m". - /// The abbreviation of the unit in the given culture, such as "m". - /// - /// The format provider to use for lookup. Defaults to - /// if null. - /// - /// double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500 - /// Output value as the result of converting to . - /// - /// Thrown when no quantity information is found for the specified quantity name. - /// - /// No units match the abbreviation. - /// More than one unit matches the abbreviation. - public static double ConvertByAbbreviation(double fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, IFormatProvider? formatProvider) - { - QuantityInfoLookup quantities = UnitsNetSetup.Default.Quantities; - UnitParser unitParser = UnitsNetSetup.Default.UnitParser; - QuantityInfo quantityInfo = quantities.GetQuantityByName(quantityName); - Enum fromUnit = unitParser.Parse(fromUnitAbbrev, quantityInfo.UnitType, formatProvider); // ex: ("m", LengthUnit) => LengthUnit.Meter - Enum toUnit = unitParser.Parse(toUnitAbbrev, quantityInfo.UnitType, formatProvider); // ex:("cm", LengthUnit) => LengthUnit.Centimeter - return Quantity.From(fromValue, fromUnit).As(toUnit); - } - - /// - /// Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm". - /// This is particularly useful for creating things like a generated unit conversion UI, - /// where you list some selectors: - /// a) Quantity: Length, Mass, Force etc. - /// b) From unit: Meter, Centimeter etc if Length is selected - /// c) To unit: Meter, Centimeter etc if Length is selected - /// - /// - /// Input value, which together with represents the quantity to - /// convert from. - /// - /// The invariant quantity name, such as "Length". Does not support localization. - /// The abbreviation of the unit in the thread's current culture, such as "m". - /// The abbreviation of the unit in the thread's current culture, such as "m". - /// 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(double fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out double result) - { - return TryConvertByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, out result, (IFormatProvider?)null); - } - - /// - /// Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm". - /// This is particularly useful for creating things like a generated unit conversion UI, - /// where you list some selectors: - /// a) Quantity: Length, Mass, Force etc. - /// b) From unit: Meter, Centimeter etc if Length is selected - /// c) To unit: Meter, Centimeter etc if Length is selected - /// - /// - /// Input value, which together with represents the quantity to - /// convert from. - /// - /// The invariant quantity name, such as "Length". Does not support localization. - /// The abbreviation of the unit in the given culture, such as "m". - /// The abbreviation of the unit in the given culture, such as "m". - /// Culture to parse abbreviations with. - /// Result if conversion was successful, 0 if not. - /// double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500 - /// True if conversion was successful. - [Obsolete("Methods accepting a culture name are deprecated in favor of using an instance of the IFormatProvider.")] - public static bool TryConvertByAbbreviation(double fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out double result, - string? culture) - { - return TryConvertByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, out result, CultureHelper.GetCultureOrInvariant(culture)); - } - - /// - /// Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm". - /// This is particularly useful for creating things like a generated unit conversion UI, - /// where you list some selectors: - /// a) Quantity: Length, Mass, Force etc. - /// b) From unit: Meter, Centimeter etc if Length is selected - /// c) To unit: Meter, Centimeter etc if Length is selected - /// - /// - /// Input value, which together with represents the quantity to - /// convert from. - /// - /// The invariant quantity name, such as "Length". Does not support localization. - /// The abbreviation of the unit in the given culture, such as "m". - /// The abbreviation of the unit in the given culture, such as "m". - /// - /// The format provider to use for lookup. Defaults to - /// if null. - /// - /// 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(double fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out double result, - IFormatProvider? formatProvider) - { - QuantityInfoLookup quantities = UnitsNetSetup.Default.Quantities; - UnitParser unitParser = UnitsNetSetup.Default.UnitParser; - if (!quantities.TryGetQuantityByName(quantityName, out QuantityInfo? quantityInfo) ) + IReadOnlyList sourceQuantityUnits = sourceQuantity.UnitInfos; + var nbSourceUnits = sourceQuantityUnits.Count; + for (var i = 0; i < nbSourceUnits; i++) + { + UnitInfo sourceUnit = sourceQuantityUnits[i]; + if (sourceUnit.BaseUnits == BaseUnits.Undefined || sourceUnit.BaseUnits == fromUnitInfo.BaseUnits) { - result = 0; - return false; + continue; } - if (!unitParser.TryParse(fromUnitAbbrev, quantityInfo.UnitType, formatProvider, out Enum? fromUnit) || - !unitParser.TryParse(toUnitAbbrev, quantityInfo.UnitType, formatProvider, out Enum? toUnit)) + if (targetQuantity.UnitInfos.TryGetUnitWithBase(sourceUnit.BaseUnits, out UnitInfo? matchingUnit)) { - result = 0; - return false; + return ConvertValueInternal(conversionExpression(ConvertValueInternal(value, fromUnitInfo, sourceUnit)), matchingUnit, toUnitInfo); } + } + + throw InvalidConversionException.CreateIncompatibleUnitsException(fromUnitInfo, targetQuantity); + } + + /// + /// Converts a quantity value from one unit to another specified unit type. + /// + /// The type of the source unit. + /// The type of the target quantity. + /// The type of the target unit. + /// The quantity value to convert. + /// The source unit of the quantity value. + /// The target quantity information which includes the target unit. + /// The converted quantity in the target unit type. + /// Thrown when is null. + /// Thrown when the source unit is not found. + /// Thrown when the conversion cannot be performed. + public virtual TTargetQuantity ConvertTo(QuantityValue value, TSourceUnit fromUnit, + QuantityInfo targetQuantityInfo) + where TSourceUnit : struct, Enum + where TTargetQuantity : IQuantity + where TTargetUnit : struct, Enum + { + UnitInfo fromUnitInfo = GetUnitInfo(UnitKey.ForUnit(fromUnit)); + QuantityInfo sourceQuantityInfo = fromUnitInfo.QuantityInfo; + if (!ConversionDefined(sourceQuantityInfo, targetQuantityInfo)) + { + throw InvalidConversionException.CreateImplicitConversionException(sourceQuantityInfo, targetQuantityInfo); + } + + return targetQuantityInfo.ConvertFrom(value, fromUnitInfo); + } + + /// + public virtual IQuantity ConvertTo(QuantityValue value, UnitKey fromUnitKey, QuantityInfo targetQuantityInfo) + { + UnitInfo fromUnitInfo = GetUnitInfo(fromUnitKey); + QuantityInfo sourceQuantityInfo = fromUnitInfo.QuantityInfo; + if (!ConversionDefined(sourceQuantityInfo, targetQuantityInfo)) + { + throw InvalidConversionException.CreateImplicitConversionException(sourceQuantityInfo, targetQuantityInfo); + } + + return targetQuantityInfo.ConvertFrom(value, fromUnitInfo); + } + + /// + /// Gets a conversion function that converts a value from one unit to another. + /// + /// The key representing the unit to convert from. + /// The key representing the unit to convert to. + /// + /// A delegate that converts a from the specified to + /// the specified . + /// + /// + /// Thrown if the specified or does not exist. + /// + /// + /// Thrown if the quantities are different and no conversion function exists between them. + /// + /// + /// If the and are the same, the returned function will + /// be an identity function. + /// + public virtual ConvertValueDelegate GetConversionFunction(UnitKey fromUnitKey, UnitKey toUnitKey) + { + if (fromUnitKey == toUnitKey) + { + return value => value; + } + + UnitInfo fromUnitInfo = GetUnitInfo(fromUnitKey); + UnitInfo toUnitInfo = GetUnitInfo(toUnitKey); + return fromUnitKey.UnitEnumType == toUnitKey.UnitEnumType + ? fromUnitInfo.GetUnitConversionExpressionTo(toUnitInfo) + : GetConversionFromOneQuantityToAnother(fromUnitInfo, toUnitInfo); + } + + /// + /// Retrieves the conversion expression required to convert a value from one unit of quantity to another. + /// + /// The unit information of the source quantity. + /// The unit information of the target quantity. + /// + /// A boolean value indicating whether to reduce constants in the conversion expression. + /// Default is true. + /// + /// A representing the conversion from the source unit to the target unit. + /// + /// Thrown when no implicit conversion exists between the specified source and target quantities. + /// + protected ConversionExpression GetConversionFromOneQuantityToAnother(UnitInfo fromUnitInfo, UnitInfo toUnitInfo, bool reduceConstants = true) + { + QuantityInfo sourceQuantity = fromUnitInfo.QuantityInfo; + QuantityInfo targetQuantity = toUnitInfo.QuantityInfo; + if (!ConversionDefined(sourceQuantity, targetQuantity)) + { + throw InvalidConversionException.CreateImplicitConversionException(sourceQuantity, targetQuantity); + } + + return fromUnitInfo.GetQuantityConversionExpressionTo(toUnitInfo); + } - result = Quantity.From(fromValue, fromUnit).As(toUnit); + /// + /// Attempts to get a conversion function that converts a value from one unit to another. + /// + /// The key representing the unit to convert from. + /// The key representing the unit to convert to. + /// + /// When this method returns, contains the conversion function if the conversion is possible; otherwise, null. + /// + /// + /// true if the conversion function was successfully retrieved; otherwise, false. + /// + /// + /// If the and are the same, the returned function will + /// be an identity function. + /// + public virtual bool TryGetConversionFunction(UnitKey fromUnitKey, UnitKey toUnitKey, [NotNullWhen(true)] out ConvertValueDelegate? conversionFunction) + { + if (fromUnitKey == toUnitKey) + { + conversionFunction = value => value; return true; + } + if (!TryGetUnitInfo(fromUnitKey, out UnitInfo? fromUnitInfo) || !TryGetUnitInfo(toUnitKey, out UnitInfo? toUnitInfo)) + { + conversionFunction = null; + return false; + } + + if (fromUnitKey.UnitEnumType != toUnitKey.UnitEnumType) + { + return TryGetConversionFromOneQuantityToAnother(fromUnitInfo, toUnitInfo, out conversionFunction); } + + conversionFunction = fromUnitInfo.GetUnitConversionExpressionTo(toUnitInfo); + return true; } -} + /// + /// Attempts to retrieve a conversion function that converts a value from one unit to another unit of a different + /// quantity. + /// + /// The unit information of the source unit. + /// The unit information of the target unit. + /// + /// When this method returns, contains the conversion function if the conversion is defined; otherwise, null. + /// + /// + /// true if a conversion function is successfully retrieved; otherwise, false. + /// + protected bool TryGetConversionFromOneQuantityToAnother(UnitInfo fromUnitInfo, UnitInfo toUnitInfo, out ConvertValueDelegate? conversionFunction) + { + if (ConversionDefined(fromUnitInfo.QuantityInfo, toUnitInfo.QuantityInfo) && + fromUnitInfo.TryGetQuantityConversionExpressionTo(toUnitInfo, true, out ConversionExpression? conversionExpression)) + { + conversionFunction = conversionExpression; + return true; + } + + conversionFunction = null; + return false; + } + + /// + /// Convert between any two quantity units by their names, such as converting a "Length" of N "Meter" to "Centimeter". + /// This is particularly useful for creating things like a generated unit conversion UI, + /// where you list some selectors: + /// a) Quantity: Length, Mass, Force etc. + /// b) From unit: Meter, Centimeter etc if Length is selected + /// c) To unit: Meter, Centimeter etc if Length is selected + /// + /// + /// Input value, which together with represents the quantity to + /// convert from. + /// + /// The invariant quantity name, such as "Length". Does not support localization. + /// The invariant unit enum name, such as "Meter". Does not support localization. + /// The invariant unit enum name, such as "Meter". Does not support localization. + /// double centimeters = ConvertByName(5, "Length", "Meter", "Centimeter"); // 500 + /// Output value as the result of converting to . + /// + /// Thrown when no quantity information is found for the specified quantity name. + /// + /// No units match the provided unit name. + /// More than one unit matches the abbreviation. + public QuantityValue ConvertValueByName(QuantityValue fromValue, string quantityName, string fromUnitName, string toUnitName) + { + UnitInfo fromUnitInfo = Quantities.GetUnitByName(quantityName, fromUnitName); + UnitInfo toUnitInfo = Quantities.GetUnitByName(quantityName, toUnitName); + return ConvertValueInternal(fromValue, fromUnitInfo, toUnitInfo); + } + + /// + /// Convert between any two quantity units by their names, such as converting a "Length" of N "Meter" to "Centimeter". + /// This is particularly useful for creating things like a generated unit conversion UI, + /// where you list some selectors: + /// a) Quantity: Length, Mass, Force etc. + /// b) From unit: Meter, Centimeter etc if Length is selected + /// c) To unit: Meter, Centimeter etc if Length is selected + /// + /// + /// Input value, which together with represents the quantity to + /// convert from. + /// + /// The invariant quantity name, such as "Length". Does not support localization. + /// The invariant unit enum name, such as "Meter". Does not support localization. + /// The invariant unit enum name, such as "Meter". Does not support localization. + /// 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 bool TryConvertValueByName(QuantityValue inputValue, string quantityName, string fromUnitName, string toUnitName, out QuantityValue result) + { + if (Quantities.TryGetUnitByName(quantityName, fromUnitName, out UnitInfo? fromUnitInfo) && + Quantities.TryGetUnitByName(quantityName, toUnitName, out UnitInfo? toUnitInfo)) + { + return TryConvertValueInternal(inputValue, fromUnitInfo, toUnitInfo, out result); + } + + result = default; + return false; + } + + /// + /// Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm". + /// This is particularly useful for creating things like a generated unit conversion UI, + /// where you list some selectors: + /// a) Quantity: Length, Mass, Force etc. + /// b) From unit: Meter, Centimeter etc if Length is selected + /// c) To unit: Meter, Centimeter etc if Length is selected + /// + /// + /// Input value, which together with represents the quantity to + /// convert from. + /// + /// The invariant quantity name, such as "Length". Does not support localization. + /// The abbreviation of the unit in the thread's current culture, such as "m". + /// The abbreviation of the unit in the thread's current culture, such as "m". + /// double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500 + /// Output value as the result of converting to . + /// + /// Thrown when no quantity information is found for the specified quantity name. + /// + /// No units match the abbreviation. + /// More than one unit matches the abbreviation. + public QuantityValue ConvertValueByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev) + { + return ConvertValueByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, null); + } + + /// + /// Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm". + /// This is particularly useful for creating things like a generated unit conversion UI, + /// where you list some selectors: + /// a) Quantity: Length, Mass, Force etc. + /// b) From unit: Meter, Centimeter etc if Length is selected + /// c) To unit: Meter, Centimeter etc if Length is selected + /// + /// + /// Input value, which together with represents the quantity to + /// convert from. + /// + /// The invariant quantity name, such as "Length". Does not support localization. + /// The abbreviation of the unit in the given culture, such as "m". + /// The abbreviation of the unit in the given culture, such as "m". + /// The unit localization culture. Defaults to if null. + /// double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500 + /// Output value as the result of converting to . + /// + /// Thrown when no quantity information is found for the specified quantity name. + /// + /// No units match the abbreviation. + /// More than one unit matches the abbreviation. + public QuantityValue ConvertValueByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, CultureInfo? culture) + { + QuantityInfo quantityInfo = Quantities.GetQuantityByName(quantityName); + UnitInfo fromUnitInfo = UnitParser.Parse(fromUnitAbbrev, quantityInfo.UnitInfos, culture); // ex: ("m", LengthUnit) => LengthUnit.Meter + UnitInfo toUnitInfo = UnitParser.Parse(toUnitAbbrev, quantityInfo.UnitInfos, culture); // ex:("cm", LengthUnit) => LengthUnit.Centimeter + return ConvertValueInternal(fromValue, fromUnitInfo, toUnitInfo); + } + + /// + /// Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm". + /// This is particularly useful for creating things like a generated unit conversion UI, + /// where you list some selectors: + /// a) Quantity: Length, Mass, Force etc. + /// b) From unit: Meter, Centimeter etc if Length is selected + /// c) To unit: Meter, Centimeter etc if Length is selected + /// + /// + /// Input value, which together with represents the quantity to + /// convert from. + /// + /// The invariant quantity name, such as "Length". Does not support localization. + /// The abbreviation of the unit in the thread's current culture, such as "m". + /// The abbreviation of the unit in the thread's current culture, such as "m". + /// Result if conversion was successful, 0 if not. + /// double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500 + /// True if conversion was successful. + public bool TryConvertValueByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out QuantityValue result) + { + return TryConvertValueByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, null, out result); + } + + /// + /// Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm". + /// This is particularly useful for creating things like a generated unit conversion UI, + /// where you list some selectors: + /// a) Quantity: Length, Mass, Force etc. + /// b) From unit: Meter, Centimeter etc if Length is selected + /// c) To unit: Meter, Centimeter etc if Length is selected + /// + /// + /// Input value, which together with represents the quantity to + /// convert from. + /// + /// The invariant quantity name, such as "Length". Does not support localization. + /// The abbreviation of the unit in the given culture, such as "m". + /// The abbreviation of the unit in the given culture, such as "m". + /// The unit localization culture. Defaults to if null. + /// Result if conversion was successful, 0 if not. + /// double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500 + /// True if conversion was successful. + public bool TryConvertValueByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, CultureInfo? culture, + out QuantityValue result) + { + if (!Quantities.TryGetQuantityByName(quantityName, out QuantityInfo? quantityInfo)) + { + result = default; + return false; + } + + if (UnitParser.TryParse(fromUnitAbbrev, quantityInfo.UnitInfos, culture, out UnitInfo? fromUnitInfo) && + UnitParser.TryParse(toUnitAbbrev, quantityInfo.UnitInfos, culture, out UnitInfo? toUnitInfo)) + { + result = ConvertValueInternal(fromValue, fromUnitInfo, toUnitInfo); + return true; + } + + result = default; + return false; + } + + #region Static methods + + /// + public static QuantityValue Convert(QuantityValue value, UnitKey fromUnitKey, UnitKey toUnitKey) + { + return Default.ConvertValue(value, fromUnitKey, toUnitKey); + } + + /// + public static bool TryConvert(QuantityValue value, UnitKey fromUnitKey, UnitKey toUnitKey, out QuantityValue result) + { + return Default.TryConvertValue(value, fromUnitKey, toUnitKey, out result); + } + + /// + public static QuantityValue ConvertByName(QuantityValue inputValue, string quantityName, string fromUnitName, string toUnitName) + { + return Default.ConvertValueByName(inputValue, quantityName, fromUnitName, toUnitName); + } + + /// + public static bool TryConvertByName(QuantityValue inputValue, string quantityName, string fromUnitName, string toUnitName, out QuantityValue result) + { + return Default.TryConvertValueByName(inputValue, quantityName, fromUnitName, toUnitName, out result); + } + + /// + public static QuantityValue ConvertByAbbreviation(QuantityValue inputValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev) + { + return Default.ConvertValueByAbbreviation(inputValue, quantityName, fromUnitAbbrev, toUnitAbbrev); + } + + /// + public static bool TryConvertByAbbreviation(QuantityValue inputValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out QuantityValue result) + { + return Default.TryConvertValueByAbbreviation(inputValue, quantityName, fromUnitAbbrev, toUnitAbbrev, out result); + } + + /// + public static QuantityValue ConvertByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, CultureInfo? culture) + { + return Default.ConvertValueByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, culture); + } + + /// + public static bool TryConvertByAbbreviation(QuantityValue inputValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, CultureInfo? culture, out QuantityValue result) + { + return Default.TryConvertValueByAbbreviation(inputValue, quantityName, fromUnitAbbrev, toUnitAbbrev, culture, out result); + } + + /// + /// Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm". + /// This is particularly useful for creating things like a generated unit conversion UI, + /// where you list some selectors: + /// a) Quantity: Length, Mass, Force etc. + /// b) From unit: Meter, Centimeter etc if Length is selected + /// c) To unit: Meter, Centimeter etc if Length is selected + /// + /// + /// Input value, which together with represents the quantity to + /// convert from. + /// + /// The invariant quantity name, such as "Length". Does not support localization. + /// The abbreviation of the unit in the given culture, such as "m". + /// The abbreviation of the unit in the given culture, such as "m". + /// Culture to parse abbreviations with. + /// double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500 + /// Output value as the result of converting to . + /// + /// Thrown when no quantity information is found for the specified quantity name. + /// + /// No units match the abbreviation. + /// More than one unit matches the abbreviation. + [Obsolete("Methods accepting a culture name are deprecated in favor of using an instance of CultureInfo.")] + public static QuantityValue ConvertByAbbreviation(QuantityValue fromValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, string? culture) + { + return Default.ConvertValueByAbbreviation(fromValue, quantityName, fromUnitAbbrev, toUnitAbbrev, CultureHelper.GetCultureOrInvariant(culture)); + } + + /// + /// Convert between any two quantity units by their abbreviations, such as converting a "Length" of N "m" to "cm". + /// This is particularly useful for creating things like a generated unit conversion UI, + /// where you list some selectors: + /// a) Quantity: Length, Mass, Force etc. + /// b) From unit: Meter, Centimeter etc if Length is selected + /// c) To unit: Meter, Centimeter etc if Length is selected + /// + /// + /// Input value, which together with represents the quantity to + /// convert from. + /// + /// The invariant quantity name, such as "Length". Does not support localization. + /// The abbreviation of the unit in the thread's current culture, such as "m". + /// The abbreviation of the unit in the thread's current culture, such as "m". + /// Culture to parse abbreviations with. + /// Result if conversion was successful, 0 if not. + /// double centimeters = ConvertByName(5, "Length", "m", "cm"); // 500 + /// True if conversion was successful. + [Obsolete("Methods accepting a culture name are deprecated in favor of using an instance of CultureInfo.")] + public static bool TryConvertByAbbreviation(QuantityValue inputValue, string quantityName, string fromUnitAbbrev, string toUnitAbbrev, out QuantityValue result, string? culture) + { + return Default.TryConvertValueByAbbreviation(inputValue, quantityName, fromUnitAbbrev, toUnitAbbrev, CultureHelper.GetCultureOrInvariant(culture), out result); + } + + #endregion +} diff --git a/UnitsNet/UnitFormatter.cs b/UnitsNet/UnitFormatter.cs deleted file mode 100644 index 0a2b827951..0000000000 --- a/UnitsNet/UnitFormatter.cs +++ /dev/null @@ -1,77 +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 System.Collections.Generic; -using System.Linq; - -namespace UnitsNet -{ - /// - /// Utility class for formatting units and values. - /// - internal static class UnitFormatter - { - /// - /// Gets the default ToString format for the specified value. - /// - /// The value to format. - /// - /// The number of digits after the radix point to display in the formatted - /// string. - /// - /// A ToString format for the specified value. - public static string GetFormat(double value, int significantDigitsAfterRadix) - { - double v = Math.Abs(value); - var sigDigitsAfterRadixStr = new string('#', significantDigitsAfterRadix); - string format; - - if (NearlyEqual(v, 0)) - { - format = "{0} {1}"; - } - // Values below 1e-3 are displayed in scientific notation. - else if (v < 1e-3) - { - format = "{0:0." + sigDigitsAfterRadixStr + "e-00} {1}"; - } - // Values from 1e-3 to 1 use fixed point notation. - else if ((v > 1e-4) && (v < 1)) - { - format = "{0:g" + significantDigitsAfterRadix + "} {1}"; - } - // Values between 1 and 1e5 use fixed point notation with digit grouping. - else if ((v >= 1) && (v < 1e6)) - { - // The comma will be automatically replaced with the correct digit separator if a different culture is used. - format = "{0:#,0." + sigDigitsAfterRadixStr + "} {1}"; - } - // Values above 1e5 use scientific notation. - else - { - format = "{0:0." + sigDigitsAfterRadixStr + "e+00} {1}"; - } - - return format; - } - - private static bool NearlyEqual(double a, double b) - { - return Math.Abs(a - b) < 1e-150; - } - - /// - /// Gets ToString format arguments. - /// - /// The unit abbreviation - /// The unit value to format. - /// The current culture. - /// The list of format arguments. - /// An array of ToString format arguments. - public static object[] GetFormatArgs(double value, string abbreviation, IFormatProvider? culture, IEnumerable args) - { - return new object[] {value, abbreviation}.Concat(args).ToArray(); - } - } -} diff --git a/UnitsNet/UnitInfo.cs b/UnitsNet/UnitInfo.cs index 68da6c5055..014b22e088 100644 --- a/UnitsNet/UnitInfo.cs +++ b/UnitsNet/UnitInfo.cs @@ -34,6 +34,8 @@ protected internal UnitInfo(IUnitDefinition mapping) Name = mapping.Name; PluralName = mapping.PluralName; BaseUnits = mapping.BaseUnits; + ConversionFromBase = mapping.ConversionFromBase; + ConversionToBase = mapping.ConversionToBase; } /// @@ -111,6 +113,12 @@ internal static TUnitInfo GetUnitWithBase(IEnumerable unit /// public BaseUnits BaseUnits { get; } + /// + public ConversionExpression ConversionFromBase { get; } + + /// + public ConversionExpression ConversionToBase { get; } + #endregion #region Implementation of IUnitInfo @@ -171,13 +179,13 @@ public string QuantityName /// /// This method utilizes the associated with this unit to create the quantity. /// - public IQuantity From(double value) + public IQuantity From(QuantityValue value) { return CreateGenericQuantity(value); } /// - protected internal abstract IQuantity CreateGenericQuantity(double value); + protected internal abstract IQuantity CreateGenericQuantity(QuantityValue value); #endregion } @@ -244,16 +252,16 @@ public override UnitKey UnitKey } /// - /// Converts a given to an instance of the quantity type associated with this unit. + /// Converts a given to an instance of the quantity type associated with this unit. /// /// The value to convert. /// An instance of the quantity type associated with this unit. - public new abstract TQuantity From(double value); + public new abstract TQuantity From(QuantityValue value); #region Overrides of UnitInfo /// - protected internal sealed override IQuantity CreateGenericQuantity(double value) + protected internal sealed override IQuantity CreateGenericQuantity(QuantityValue value) { return From(value); } @@ -285,7 +293,7 @@ internal UnitInfo(QuantityInfo quantityInfo, IUnitDefinition - public override TQuantity From(double value) + public override TQuantity From(QuantityValue value) { return QuantityInfo.From(value, Value); } diff --git a/UnitsNet/UnitMath.cs b/UnitsNet/UnitMath.cs index e9130bda08..83cfb667ad 100644 --- a/UnitsNet/UnitMath.cs +++ b/UnitsNet/UnitMath.cs @@ -33,7 +33,7 @@ public static TQuantity Abs(this TQuantity value) where TQuantity : I // #else // return value.QuantityInfo.Create(QuantityValue.Abs(value.Value), value.UnitKey); // #endif - return (TQuantity)value.QuantityInfo.From(Math.Abs(value.Value), value.UnitKey); + return QuantityValue.IsNegative(value.Value) ? (TQuantity)value.QuantityInfo.From(-value.Value, value.UnitKey) : value; } /// Returns the smaller of two values. @@ -166,10 +166,12 @@ public static TQuantity Max(this IEnumerable /// cannot be greater than . /// - public static TQuantity Clamp(TQuantity value, TQuantity min, TQuantity max) where TQuantity : IComparable, IQuantity + public static TQuantity Clamp(TQuantity value, TQuantity min, TQuantity max) + where TQuantity : IQuantityOfType, IComparable { - var minValue = (TQuantity)min.ToUnit(value.Unit); - var maxValue = (TQuantity)max.ToUnit(value.Unit); + UnitKey targetUnit = value.UnitKey; + TQuantity minValue = UnitConverter.Default.ConvertToUnit(min, targetUnit); + TQuantity maxValue = UnitConverter.Default.ConvertToUnit(max, targetUnit); if (minValue.CompareTo(maxValue) > 0) { diff --git a/UnitsNet/UnitSystem.cs b/UnitsNet/UnitSystem.cs index 0f57cac20f..3f4ba069d0 100644 --- a/UnitsNet/UnitSystem.cs +++ b/UnitsNet/UnitSystem.cs @@ -20,7 +20,7 @@ public sealed class UnitSystem : IEquatable public UnitSystem(BaseUnits baseUnits) { if (baseUnits is null) throw new ArgumentNullException(nameof(baseUnits)); - if (!baseUnits.IsFullyDefined) throw new ArgumentException("A unit system must have all base units defined.", nameof(baseUnits)); + if(baseUnits == BaseUnits.Undefined) throw new ArgumentException("A unit system must at least some base units defined.", nameof(baseUnits)); BaseUnits = baseUnits; } @@ -64,7 +64,7 @@ public bool Equals(UnitSystem? other) /// public override int GetHashCode() { - return new {BaseUnits}.GetHashCode(); + return BaseUnits.GetHashCode(); } /// @@ -72,12 +72,10 @@ public override int GetHashCode() /// public BaseUnits BaseUnits{ get; } - private static readonly BaseUnits SIBaseUnits = new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, - ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela); - /// /// Gets the SI unit system. /// - public static UnitSystem SI { get; } = new UnitSystem(SIBaseUnits); + public static UnitSystem SI { get; } = new UnitSystem(new BaseUnits(LengthUnit.Meter, MassUnit.Kilogram, DurationUnit.Second, + ElectricCurrentUnit.Ampere, TemperatureUnit.Kelvin, AmountOfSubstanceUnit.Mole, LuminousIntensityUnit.Candela)); } } diff --git a/UnitsNet/UnitsNet.csproj b/UnitsNet/UnitsNet.csproj index 74bb0cca8c..cd110dbe9b 100644 --- a/UnitsNet/UnitsNet.csproj +++ b/UnitsNet/UnitsNet.csproj @@ -1,8 +1,8 @@ - + UnitsNet - 6.0.0-pre017 + 6.0.0-pre018 Andreas Gullberg Larsen Units.NET Get all the common units of measurement and the conversions between them. It is light-weight and thoroughly tested. @@ -16,6 +16,7 @@ false unit units quantity quantities measurement si metric imperial abbreviation abbreviations convert conversion parse immutable README.md + true @@ -64,6 +65,7 @@ + diff --git a/UnitsNet/UnitsNet.csproj.DotSettings b/UnitsNet/UnitsNet.csproj.DotSettings index 99fb414ae9..f894c0387c 100644 --- a/UnitsNet/UnitsNet.csproj.DotSettings +++ b/UnitsNet/UnitsNet.csproj.DotSettings @@ -1,5 +1,15 @@  True True + True + True + True + True + True + True True - True \ No newline at end of file + True + True + True + True + True \ No newline at end of file